@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, 04:45 UTC

main
ts 120 lines 4.15 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Update leases coordinate Node server processes.
2 import * as NodeCrypto from "node:crypto";
3 import * as NodeFSP from "node:fs/promises";
4 import * as NodeOS from "node:os";
5 import * as NodePath from "node:path";
6 import * as KeyedLock from "@t3tools/shared/KeyedLock";
7 import { lock } from "proper-lockfile";
8 import * as Effect from "effect/Effect";
9 import * as Ref from "effect/Ref";
10 import * as Schedule from "effect/Schedule";
11 import * as Schema from "effect/Schema";
12
13 export interface ProviderMaintenanceCommandCoordinatorShape<E> {
14 readonly withCommandLock: <A, R>(input: {
15 readonly targetKey: string;
16 readonly lockKey: string;
17 readonly onQueued?: Effect.Effect<void, E, R>;
18 readonly run: Effect.Effect<A, E, R>;
19 }) => Effect.Effect<A, E, R>;
20 }
21
22 class MachineLockError extends Schema.TaggedError<MachineLockError>()("MachineLockError", {
23 held: Schema.Boolean,
24 cause: Schema.Defect(),
25 }) {}
26
27 const lockDirectory = () => NodePath.join(NodeOS.tmpdir(), "t3code-provider-updates");
28
29 /** @internal */
30 export const machineLockFile = (lockKey: string) =>
31 NodePath.join(
32 lockDirectory(),
33 NodeCrypto.createHash("sha256").update(lockKey).digest("hex").slice(0, 32),
34 );
35
36 // Other T3 servers on this machine can run the same installation's updater; one replacing its own
37 // files makes the other's spawn or capability check fail. Without a usable lock directory, run anyway.
38 const withMachineLock = <A, E, R>(
39 lockKey: string,
40 run: Effect.Effect<A, E, R>,
41 ): Effect.Effect<A, E, R> => {
42 const directory = lockDirectory();
43 const file = machineLockFile(lockKey);
44 const acquire = Effect.acquireRelease(
45 Effect.tryPromise({
46 try: async () => {
47 await NodeFSP.mkdir(directory, { recursive: true });
48 return await lock(file, {
49 realpath: false,
50 stale: 60_000,
51 update: 10_000,
52 onCompromised: () => {},
53 });
54 },
55 catch: (cause) =>
56 new MachineLockError({
57 held: (cause as { code?: unknown } | null)?.code === "ELOCKED",
58 cause,
59 }),
60 }),
61 // A compromised lease rejects on release; the update has already finished by then.
62 (release) => Effect.promise(() => release().catch(() => undefined)),
63 ).pipe(
64 Effect.retry({ while: (error) => error.held, schedule: Schedule.spaced("1 second") }),
65 Effect.catch((error) =>
66 Effect.logWarning("Could not lock provider update across servers", {
67 lockKey,
68 cause: String(error.cause),
69 }),
70 ),
71 );
72 return Effect.scoped(acquire.pipe(Effect.andThen(run)));
73 };
74
75 export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
76 "makeProviderMaintenanceCommandCoordinator",
77 )(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
78 const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
79 const locks = yield* KeyedLock.make<string>();
80
81 const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
82 return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
83 if (runningTargets.has(targetKey)) {
84 return [false, runningTargets] as const;
85 }
86 const next = new Set(runningTargets);
87 next.add(targetKey);
88 return [true, next] as const;
89 });
90 });
91
92 const releaseTarget = (targetKey: string) =>
93 Ref.update(runningTargetsRef, (runningTargets) => {
94 const next = new Set(runningTargets);
95 next.delete(targetKey);
96 return next;
97 });
98
99 const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] =
100 Effect.fn("providerMaintenanceCommandCoordinator.withCommandLock")(function* ({
101 targetKey,
102 lockKey,
103 onQueued,
104 run,
105 }) {
106 const acquired = yield* acquireTarget(targetKey);
107 if (!acquired) {
108 return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
109 }
110
111 return yield* (onQueued ?? Effect.void).pipe(
112 Effect.andThen(locks.withLock(lockKey, withMachineLock(lockKey, run))),
113 Effect.ensuring(releaseTarget(targetKey)),
114 );
115 });
116
117 return {
118 withCommandLock,
119 } satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
120 });