Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Shared with the standalone launcher, which has no Effect runtime.
2// @effect-diagnostics globalTimers:off -- Bounded cross-process lease acquisition in the standalone launcher.
3// @effect-diagnostics globalDate:off -- The standalone launcher has no Effect clock for its acquisition deadline.
4import * as NodeCrypto from "node:crypto";
5import * as NodeFS from "node:fs";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8
9// Coarse boot time: a lease from an earlier boot is dead even when its PID is live again.
10const bootEpochSeconds = () => Math.round(Date.now() / 1000 - NodeOS.uptime());
11
12/** Serialize durable selection and unit writes, never manager stop/start commands. */
13export async function acquireServiceSelectionLock(
14 selectionPath: string,
15 options?: { readonly waitForRetry?: () => Promise<void> },
16): Promise<() => void> {
17 const waitForRetry =
18 options?.waitForRetry ?? (() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
19 const directory = NodePath.dirname(selectionPath);
20 NodeFS.mkdirSync(directory, { recursive: true, mode: 0o700 });
21 const lock = selectionPath + ".selection-lock";
22 const owner = `${process.pid}.${bootEpochSeconds()}.${NodeCrypto.randomUUID()}`;
23 const candidate = `${lock}.${owner}`;
24 const deadline = Date.now() + 30_000;
25 // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
26 const windows = NodeOS.platform() === "win32";
27 const removeEmptyLock = () => {
28 try {
29 NodeFS.rmdirSync(lock);
30 } catch (error) {
31 const code = (error as NodeJS.ErrnoException).code ?? "";
32 if (
33 !["ENOENT", "ENOTEMPTY", "EEXIST"].includes(code) &&
34 !(windows && ["EBUSY", "EPERM", "EACCES"].includes(code))
35 )
36 throw error;
37 }
38 };
39 NodeFS.mkdirSync(candidate, { mode: 0o700 });
40 try {
41 NodeFS.writeFileSync(NodePath.join(candidate, owner), "", { mode: 0o600 });
42 while (true) {
43 try {
44 // Publish the owner atomically; rename cannot replace another populated directory.
45 NodeFS.renameSync(candidate, lock);
46 return () => {
47 NodeFS.unlinkSync(NodePath.join(lock, owner));
48 removeEmptyLock();
49 };
50 } catch (error) {
51 const code = (error as NodeJS.ErrnoException).code ?? "";
52 // Windows MoveFileExW fails with EPERM/EACCES when the target directory already exists.
53 const contended =
54 code === "EEXIST" ||
55 code === "ENOTEMPTY" ||
56 (windows && (code === "EPERM" || code === "EACCES"));
57 if (!contended) throw error;
58 }
59 let owners: string[] = [];
60 try {
61 owners = NodeFS.readdirSync(lock);
62 } catch (error) {
63 // A Windows rename can fail with EPERM while no lock exists; keep the deadline and delay.
64 if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
65 }
66 if (owners.length === 1) {
67 const previous = owners[0]!;
68 const [pidText, bootText] = previous.split(".");
69 const pid = Number(pidText);
70 if (!Number.isSafeInteger(pid) || pid <= 0)
71 throw new Error(`Invalid service selection lock owner at ${lock}.`);
72 const ownerBoot = Number(bootText);
73 const fromEarlierBoot =
74 Number.isSafeInteger(ownerBoot) && Math.abs(ownerBoot - bootEpochSeconds()) > 60;
75 let dead = fromEarlierBoot;
76 if (!dead) {
77 try {
78 process.kill(pid, 0);
79 } catch (error) {
80 const code = (error as NodeJS.ErrnoException).code;
81 if (code !== "ESRCH" && code !== "EPERM") throw error;
82 dead = code === "ESRCH";
83 }
84 }
85 if (dead) {
86 // Remove only this dead owner's unique file, never a replacement owner's.
87 try {
88 NodeFS.unlinkSync(NodePath.join(lock, previous));
89 } catch (error) {
90 if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
91 }
92 }
93 }
94 removeEmptyLock();
95 if (Date.now() >= deadline)
96 throw new Error(
97 `Service selection is locked at ${lock}. Retry when the other operation finishes.`,
98 );
99 await waitForRetry();
100 }
101 } finally {
102 NodeFS.rmSync(candidate, { recursive: true, force: true });
103 }
104}