1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { runValAPI } from "https://esm.town/v/stevekrouse/runValAPI";
import { safeCounter as safeCounter2 } from "https://esm.town/v/stevekrouse/safeCounter";
import { sleep } from "https://esm.town/v/stevekrouse/sleep";
import { dlock } from "https://esm.town/v/stevekrouse/dlock";
import { runVal } from "https://esm.town/v/std/runVal";
export let safeCounter = async () => {
// 1. Try to acquire a lock
let { lease } = await dlock();
console.log(lease);
if (!lease) {
// 2. wait a second and try to acquire it again
await sleep(1000);
return safeCounter2();
}
// 3. I have a lock!
// 4. Get most up to date state
//
// Note 1: If I referenced @stevekrouse.threadsafeStateEx here
// it would return the value of that val at the beginning of this function,
// before I acquired the lock. I fetch it's value now to get the most up-to-date
// value of it, now that I know it can't be updated until I release this lock.
//
// Note 2: I use `@stevekrouse.runValAPI` here instead of `api` (used below)
// because `api` only works on funcitons and @stevekrouse.threadsafeStateEx
// is a JSON val.
let { state } = await runValAPI(
"@stevekrouse.threadsafeStateEx",
);
// 5. Update the state
//
// Note 3: I update the state via an API call here to ensure that the state
// is fully updated *before* I release the lock. If I were to update the state
// directly in this val, `@stevekrouse.updateThreadsafeStateEx = `, those
// changes wouldn't be saved in the database until *after* I released the lock
let newState = state + 1;
await runVal("stevekrouse.updateThreadsafeStateEx", {
lease,
state: newState,
});
// 6. i release the lock
await dlock({ release: true });
return newState;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let { threadsafeStateEx } = await import("https://esm.town/v/stevekrouse/threadsafeStateEx");
export async function updateThreadsafeStateEx({ lease, state }) {
// TODO confirm it's me updating the state using auth
if (lease > threadsafeStateEx.lease) {
threadsafeStateEx = {
state,
lease,
};
return threadsafeStateEx.state;
}
else {
throw Error("State already updated");
}
}
1
Next