-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
92 lines (80 loc) · 2.39 KB
/
Copy pathindex.ts
File metadata and controls
92 lines (80 loc) · 2.39 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { ulid } from "ulid";
import { interpret } from "xstate";
import { acquireLock, maybeReleaseLock, renewLock } from "~/services/lock";
import { createLockMachine } from "./machine";
// The worker ID is paramount for coordinating which
// server/container is holding the lock.
const workerId = ulid();
const lockKey = "lock.resource-worker";
const lockExpiryInSeconds = 10;
/**
* Simulate some background job
*/
async function consumeResource() {
console.log("Doing some heavy work...", { workerId });
await new Promise((res) => setTimeout(res, 2000));
return 1;
}
async function stopConsumingResource() {
console.log("Stopping work...");
await new Promise((res) => setTimeout(res, 1000));
return 1;
}
async function acquireWorkerLock() {
const didAcquireLock = await acquireLock(
lockKey,
workerId,
lockExpiryInSeconds
);
if (didAcquireLock) {
return true;
}
throw new Error("Lock not available");
}
async function renewWorkerLock() {
const didRenewLock = await renewLock(lockKey, workerId, lockExpiryInSeconds);
if (didRenewLock) {
return true;
}
throw new Error("Lock not available for renewal");
}
function releaseWorkerLock() {
return maybeReleaseLock(lockKey, workerId);
}
const service = interpret(
createLockMachine({
workerId,
acquireLock: acquireWorkerLock,
releaseLock: releaseWorkerLock,
renewLock: renewWorkerLock,
startWork: consumeResource,
stopWork: stopConsumingResource,
})
);
export function startLockWorker() {
service.start();
service.send("TRY_ACQUIRE_LOCK");
}
/**
* Stop the lock worker in a coordinated fashion.
* Once the worker stops, if it holds the lock, it should have been
* cleaned-up, giving the chance to another worker to pick it up.
*
* @param onStop Callback to notify when the worker fully stops
*/
export function stopLockWorker(onStop: () => void) {
// When our state machine gets back to the 'idle' state,
// it means that it completely stopped and had a reset,
// getting ready to start again.
// but at this point, our server wants to shutdown,
// so it should be safe to continue.
service.onTransition((state) => {
if (state.value === "idle") {
onStop();
}
});
// The stop event will trigger the state machine
// transition to safely stop the resources consuption and lock release,
// resetting our state machine to the initial state.
service.send("STOP");
}