@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 140 lines 5.21 KB
Raw
1 import { tmpdir } from "node:os";
2 import { join } from "node:path";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5
6 // API Gateway REST has a very low account-wide control-plane mutation quota,
7 // especially for deleting REST APIs. The authoritative AWS sweep runs a
8 // distributed lane and a Lambda-quota lane in separate Bun processes; an
9 // in-memory semaphore cannot coordinate a RestApiEventSource test in one lane
10 // with ordinary ApiGateway tests in the other. Use one service-local,
11 // cross-process lock directory instead. Unrelated AWS services remain fully
12 // parallel.
13 const profile = (process.env.ALCHEMY_PROFILE ?? "testing").replace(/[^a-zA-Z0-9_.-]/g, "-");
14 const uid = process.getuid?.() ?? 0;
15 const lockDirectory = join(tmpdir(), `alchemy-test-apigateway-${uid}-${profile}.lock`);
16 const ownerFile = join(lockDirectory, "owner");
17
18 const processIsAlive = (pid: number) => {
19 try {
20 process.kill(pid, 0);
21 return true;
22 } catch (error) {
23 return (error as NodeJS.ErrnoException).code === "EPERM";
24 }
25 };
26
27 const pollInterval = "250 millis";
28 // A freshly-acquired lock writes its owner file immediately after the atomic
29 // mkdir, so an unreadable owner is normally a sub-second race. If it stays
30 // unreadable for this many consecutive polls (~10s) the lock predates a crash
31 // or reboot that corrupted the directory (reads can then fail with
32 // EFAULT/ENOENT/EPERM in bun) and it is treated as stale.
33 const unreadableStalePolls = 40;
34
35 /**
36 * Cross-process test lease over a tmpdir lock directory.
37 *
38 * Robustness contract: NO filesystem failure may escape into the test run.
39 * A machine reboot can leave the lock directory in a state where even
40 * `rm`/`read` fail with EFAULT (observed bun edge case on stale tmp entries);
41 * every fs primitive below is therefore best-effort, and a stale lock whose
42 * removal keeps failing is stolen in place by overwriting the owner file.
43 */
44 export const makeApiGatewayTestLease = () => {
45 let held = false;
46
47 const acquire = Effect.gen(function* () {
48 const fs = yield* FileSystem.FileSystem;
49
50 const tryMakeDir = fs.makeDirectory(lockDirectory).pipe(
51 Effect.as(true),
52 Effect.catchCause(() => Effect.succeed(false)),
53 );
54 const tryWriteOwner = fs.writeFileString(ownerFile, String(process.pid)).pipe(
55 Effect.as(true),
56 Effect.catchCause(() => Effect.succeed(false)),
57 );
58 const tryReadOwnerPid = fs.readFileString(ownerFile).pipe(
59 Effect.map((content) => Number.parseInt(content, 10)),
60 Effect.catchCause(() => Effect.succeed<number | undefined>(undefined)),
61 );
62 const tryRemoveLock = fs.remove(lockDirectory, { recursive: true }).pipe(
63 Effect.as(true),
64 Effect.catchCause(() => Effect.succeed(false)),
65 );
66
67 let unreadablePolls = 0;
68
69 while (true) {
70 if (yield* tryMakeDir) {
71 if (yield* tryWriteOwner) {
72 held = true;
73 return;
74 }
75 // We created the directory but could not record ownership. Back out
76 // (best-effort) so other processes are not stuck waiting on a
77 // headless lock, then retry.
78 yield* tryRemoveLock;
79 yield* Effect.sleep(pollInterval);
80 continue;
81 }
82
83 // The directory already exists — or mkdir itself failed abnormally
84 // (e.g. EFAULT on a reboot-stale path). Inspect the recorded owner.
85 const ownerPid = yield* tryReadOwnerPid;
86
87 if (ownerPid !== undefined && Number.isFinite(ownerPid) && processIsAlive(ownerPid)) {
88 unreadablePolls = 0;
89 yield* Effect.sleep(pollInterval);
90 continue;
91 }
92
93 if (ownerPid === undefined) {
94 // Missing or unreadable owner file: give the current owner a grace
95 // window to finish writing it before declaring the lock stale.
96 unreadablePolls += 1;
97 if (unreadablePolls < unreadableStalePolls) {
98 yield* Effect.sleep(pollInterval);
99 continue;
100 }
101 }
102
103 // Stale lock: the owner is dead, invalid, or unreadable past the grace
104 // window. Prefer removing the directory so the atomic-mkdir path can
105 // re-acquire; if removal itself keeps failing (EFAULT on the stale
106 // directory), steal in place by overwriting the owner file and
107 // verifying we won any concurrent write race.
108 unreadablePolls = 0;
109 if (yield* tryRemoveLock) {
110 continue;
111 }
112 if (yield* tryWriteOwner) {
113 yield* Effect.sleep("100 millis");
114 if ((yield* tryReadOwnerPid) === process.pid) {
115 held = true;
116 return;
117 }
118 }
119 yield* Effect.sleep(pollInterval);
120 }
121 });
122
123 const release = Effect.gen(function* () {
124 if (!held) return;
125 held = false;
126 const fs = yield* FileSystem.FileSystem;
127 const removed = yield* fs.remove(lockDirectory, { recursive: true }).pipe(
128 Effect.as(true),
129 Effect.catchCause(() => Effect.succeed(false)),
130 );
131 if (!removed) {
132 // Could not remove the directory (stale-tmp EFAULT). Best-effort drop
133 // of the owner file so a successor's staleness detection steals the
134 // lock instead of waiting on this (soon-dead) pid. Never fail release.
135 yield* fs.remove(ownerFile).pipe(Effect.catchCause(() => Effect.void));
136 }
137 });
138
139 return { acquire, release };
140 };