Skip to content

Commit

Permalink
fix: prevent race condition in KeyValueStore.getAutoSavedValue() (#2193)
Browse files Browse the repository at this point in the history
This was painful to discover the hard way :(

Code to test this:


```js
const store = await Actor.openKeyValueStore("test", { forceCloud: true });

const key = "something";
const res = await Promise.all([
  store.getAutoSavedValue(key, { foo: [] }),
  new Promise((r) => setTimeout(r, Math.random() * 1000)).then(() =>
    store.getAutoSavedValue(key, { foo: [] })
  ),
]);
res[0].foo.push("test");
console.log(res);
```

Run this a few times and at some point you will get two different values
in the console.log. (Note that it's using `forceCloud` to make
`this.GetValue()` run for a little longer.)
  • Loading branch information
mvolfik authored Nov 24, 2023
1 parent a2d7f49 commit e340e2b
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/core/src/storages/key_value_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,15 @@ export class KeyValueStore {
}

const value = await this.getValue<T>(key, defaultValue);

// The await above could have run in parallel with another call to this function. If the other call finished more quickly,
// the value will in cache at this point, and returning the new fetched value would introduce two different instances of
// the auto-saved object, and only the latter one would be persisted.
// Therefore we re-check the cache here, and if such race condition happened, we drop the fetched value and return the cached one.
if (this.cache.has(key)) {
return this.cache.get(key) as T;
}

this.cache.set(key, value!);
this.ensurePersistStateEvent();

Expand Down

0 comments on commit e340e2b

Please sign in to comment.