Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceSelectionLock.test.ts

68 lines2.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6​
7import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
8​
9it.layer(NodeServices.layer)("service selection lock", (it) => {
10 it.effect("reclaims a lease from an earlier boot even when its PID is live again", () =>
11 Effect.gen(function* () {
12 const fs = yield* FileSystem.FileSystem;
13 const path = yield* Path.Path;
14 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-selection-lock-" });
15 const selectionPath = path.join(root, "service-state.json");
16 const lock = `${selectionPath}.selection-lock`;
17 const stale = `${process.pid}.1.00000000-0000-4000-8000-000000000000`;
18 yield* fs.makeDirectory(lock, { recursive: true });
19 yield* fs.writeFileString(path.join(lock, stale), "");
20​
21 const release = yield* Effect.promise(() => acquireServiceSelectionLock(selectionPath));
22 const owners = yield* fs.readDirectory(lock);
23 assert.equal(owners.length, 1);
24 assert.notEqual(owners[0], stale);
25 assert.isTrue(owners[0]!.startsWith(`${process.pid}.`));
26 release();
27 assert.isFalse(yield* fs.exists(lock));
28 }),
29 );
30​
31 it.effect("waits on a contended live lease until the first holder releases it", () =>
32 Effect.gen(function* () {
33 const fs = yield* FileSystem.FileSystem;
34 const path = yield* Path.Path;
35 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-selection-lock-" });
36 const selectionPath = path.join(root, "service-state.json");
37 const lock = `${selectionPath}.selection-lock`;
38​
39 const releaseFirst = yield* Effect.promise(() => acquireServiceSelectionLock(selectionPath));
40 let signalRetryStarted!: () => void;
41 const retryStarted = new Promise<void>((resolve) => {
42 signalRetryStarted = resolve;
43 });
44 let releaseRetryGate!: () => void;
45 const retryGate = new Promise<void>((resolve) => {
46 releaseRetryGate = resolve;
47 });
48 let secondAcquired = false;
49 const second = acquireServiceSelectionLock(selectionPath, {
50 waitForRetry: () => {
51 signalRetryStarted();
52 return retryGate;
53 },
54 }).then((release) => {
55 secondAcquired = true;
56 return release;
57 });
58 yield* Effect.promise(() => retryStarted);
59 assert.isFalse(secondAcquired);
60 releaseFirst();
61 releaseRetryGate();
62 const releaseSecond = yield* Effect.promise(() => second);
63 assert.isTrue(secondAcquired);
64 releaseSecond();
65 assert.isFalse(yield* fs.exists(lock));
66 }),
67 );
68});