Description
Describe the bug
I'm not certain if this is the correct place to report this, but the Amplify v2 Optimistic UI example at: https://docs.amplify.aws/swift/build-a-backend/data/optimistic-ui/#complete-example
is quite buggy.
It uses an actor to protect mutable state, but it carries values derived from that state across suspension points, introducing bugs that can cause crashes.
For instance the updateProperty
function reads an index
and a rollbackProperty
, then awaits an API call (allowing other modification of the state to occur, for instance someone deleting all properties).
Then after the await, the index is used without re-validating, so in case the properties
array has a size change, the index can now be invalid.
Example that can cause a crash:
- call
createProperty
and thenupdateProperty
with the same property - in an offline situation, so all API calls will fail createProperty
runs first andproperties
now has a count of 1- The Amplify API is called and suspends execution of
createProperty
updateProperty
runs and stores the value0
inindex
- The Amplify API is called and suspends execution of
updateProperty
createProperty
resumes execution, but due to being offline we have an error, and we are removing the item at index 0 of theproperties
array - leaving an empty array. ThecreateProperty
function completes- The
updateProperty
resumes, also with an error, it attempts to updateproperties
at index 0 which now doesn't exist, and it causes a crash.
Steps To Reproduce
This is a documentation issue.
Read https://docs.amplify.aws/swift/build-a-backend/data/optimistic-ui/#complete-example thoroughly and consider Swift actor re-entrancy.
Expected behavior
Documentation should not suggest anti-patterns that may cause crashes. :-)
Amplify Framework Version
2
Amplify Categories
API
Dependency manager
Swift PM
Swift version
5.10
CLI version
Xcode version
14.3.1
Relevant log output
<details>
<summary>Log Messages</summary>
INSERT LOG MESSAGES HERE
Is this a regression?
No
Regression additional context
No response
Platforms
No response
OS Version
iOS 15.3
Device
iPhone 15
Specific to simulators
No response
Additional context
No response