@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 227 lines 9.41 KB
Raw
1 import { existsSync } from "node:fs";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Layer from "effect/Layer";
5 import * as Path from "effect/Path";
6 import type { PlatformError } from "effect/PlatformError";
7 import { dotAlchemyDirectory } from "../AlchemyContext.ts";
8 import { decodeFqn, encodeFqn } from "../FQN.ts";
9 import { recordStateStoreInit } from "../Telemetry/Metrics.ts";
10 import { writeFileAtomic } from "../Util/AtomicFile.ts";
11 import { initialCwd } from "../Util/Node.ts";
12 import { STATE_STORE_VERSION } from "./HttpStateApi.ts";
13 import { State, StateStoreError, type StateService } from "./State.ts";
14 import { encodeState, reviveState } from "./StateEncoding.ts";
15
16 export const localState = () =>
17 Layer.effect(
18 State,
19 Effect.gen(function* () {
20 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
21
22 const make = makeLocalState().pipe(recordStateStoreInit, Effect.provideContext(context));
23
24 return yield* Effect.cached(make);
25 }),
26 );
27
28 export const makeLocalState = () =>
29 Effect.gen(function* () {
30 const fs = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 const dotAlchemy = yield* dotAlchemyDirectory;
33 // Keep the store anchored across deploy/destroy even if another task changes cwd.
34 const stateDir = path.resolve(initialCwd, dotAlchemy, "state");
35
36 const fail = (err: PlatformError) =>
37 Effect.fail(
38 new StateStoreError({
39 message: err.message,
40 cause: err,
41 }),
42 );
43
44 const recover = <T>(effect: Effect.Effect<T, PlatformError, never>) =>
45 effect.pipe(
46 Effect.catchTag("PlatformError", (e) =>
47 e.reason._tag === "NotFound" ? Effect.void : fail(e),
48 ),
49 );
50
51 // Directory-level NotFound recovery with a trust-but-verify twist.
52 //
53 // `list` and `deleteStack` treat a missing stage/stack directory as
54 // "no state" — the legitimate shape for a never-deployed (or fully
55 // destroyed) stack. But a FALSE NotFound here is catastrophic: a
56 // destroy that cannot see its state plans "no changes" and silently
57 // leaks every cloud resource of the stack. So before recovering, the
58 // async result is cross-checked with a synchronous `existsSync` — a
59 // deliberately independent code path (`node:fs`, not the FileSystem
60 // service) so a misbehaving async fs answer cannot vouch for itself.
61 // If the directory actually exists, fail loudly instead of degrading
62 // to an empty listing. A directory cannot legitimately reappear
63 // between the two checks: nothing recreates a stage dir concurrently
64 // with the session that is listing or deleting it.
65 const recoverMissingDir = <T>(dir: string, effect: Effect.Effect<T, PlatformError, never>) =>
66 effect.pipe(
67 Effect.catchTag("PlatformError", (e) => {
68 if (e.reason._tag !== "NotFound") return fail(e);
69 return Effect.flatMap(
70 Effect.sync(() => existsSync(dir)),
71 (exists) =>
72 exists
73 ? Effect.fail(
74 new StateStoreError({
75 message:
76 `state store reported NotFound for '${dir}', but the directory exists — ` +
77 `refusing to treat the stack's state as empty (a destroy acting on this ` +
78 `answer would leak every resource of the stack)`,
79 cause: e,
80 }),
81 )
82 : Effect.void,
83 );
84 }),
85 );
86
87 const stageDir = ({ stack, stage }: { stack: string; stage: string }) =>
88 path.join(stateDir, stack, stage);
89
90 const resource = ({ stack, stage, fqn }: { stack: string; stage: string; fqn: string }) =>
91 path.join(stateDir, stack, stage, `${encodeFqn(fqn)}.json`);
92
93 const outputFile = ({ stack, stage }: { stack: string; stage: string }) =>
94 path.join(stateDir, stack, stage, `__stack_output__.json`);
95
96 // Write state files atomically so a concurrent `get` (e.g. a parallel
97 // test reading shared `.alchemy/state`) never observes a truncated,
98 // mid-write file — which would otherwise surface as `JSON.parse("")` →
99 // "Unexpected end of JSON input".
100 const writeAtomic = (file: string, contents: string) => writeFileAtomic(fs, file, contents);
101
102 // Parse a state file, tolerating an empty read. A zero-length file can
103 // linger from a write that was interrupted before this atomic-write change
104 // (or any non-atomic external writer); treat it as "absent" rather than
105 // throwing a JSON parse error that would abort the whole operation.
106 const parseState = (contents: string) =>
107 contents.trim().length === 0 ? undefined : JSON.parse(contents, reviveState);
108
109 const created = new Set<string>();
110
111 const ensure = (dir: string) =>
112 created.has(dir)
113 ? Effect.void
114 : fs
115 .makeDirectory(dir, { recursive: true })
116 .pipe(Effect.tap(() => Effect.sync(() => created.add(dir))));
117
118 const state: StateService = {
119 id: "local",
120 getVersion: () => Effect.succeed(STATE_STORE_VERSION),
121 listStacks: () =>
122 fs.readDirectory(stateDir).pipe(
123 recover,
124 Effect.map((files) => files ?? []),
125 ),
126 listStages: (stack: string) =>
127 fs.readDirectory(path.join(stateDir, stack)).pipe(
128 recover,
129 Effect.map((files) => files ?? []),
130 ),
131 get: (request) =>
132 fs.readFile(resource(request)).pipe(
133 Effect.map((file) => parseState(file.toString())),
134 recover,
135 ),
136 getReplacedResources: Effect.fn(function* (request) {
137 return (yield* Effect.forEach(yield* state.list(request), (fqn) =>
138 state.get({
139 stack: request.stack,
140 stage: request.stage,
141 fqn,
142 }),
143 )).filter((r) => r?.status === "replaced");
144 }),
145 set: (request) =>
146 ensure(stageDir(request)).pipe(
147 Effect.flatMap(() =>
148 writeAtomic(resource(request), JSON.stringify(encodeState(request.value), null, 2)),
149 ),
150 recover,
151 Effect.map(() => request.value),
152 ),
153 delete: (request) => fs.remove(resource(request)).pipe(recover),
154 deleteStack: ({ stack, stage }) =>
155 Effect.suspend(() => {
156 const dir = stage === undefined ? path.join(stateDir, stack) : stageDir({ stack, stage });
157 return fs.remove(dir, { recursive: true }).pipe(
158 (eff) => recoverMissingDir(dir, eff),
159 // Drop cached `ensure`d directories under the removed tree, or a
160 // later `set` for the same (stack, stage) skips makeDirectory and
161 // its write fails with NotFound — silently swallowed by `recover`.
162 Effect.tap(() =>
163 Effect.sync(() => {
164 for (const cached of created) {
165 if (cached === dir || cached.startsWith(dir + path.sep)) {
166 created.delete(cached);
167 }
168 }
169 }),
170 ),
171 // Deleting the last stage leaves an empty `{stack}/` husk that
172 // `listStacks` would keep reporting forever (and durable
173 // per-test scratch stacks would accumulate one per test). Prune
174 // it when no stages remain. The read-then-remove is not racy:
175 // nothing recreates a stage dir concurrently with the session
176 // that is deleting it (same invariant as recoverMissingDir).
177 Effect.tap(() => {
178 if (stage === undefined) return Effect.void;
179 const stackDir = path.join(stateDir, stack);
180 return fs.readDirectory(stackDir).pipe(
181 Effect.flatMap((entries) =>
182 entries.length === 0
183 ? fs
184 .remove(stackDir, { recursive: true })
185 .pipe(Effect.tap(() => Effect.sync(() => created.delete(stackDir))))
186 : Effect.void,
187 ),
188 Effect.ignore,
189 );
190 }),
191 );
192 }),
193 list: (request) =>
194 fs.readDirectory(stageDir(request)).pipe(
195 (eff) => recoverMissingDir(stageDir(request), eff),
196 Effect.map((files) =>
197 (files ?? [])
198 // Only decode committed state files. Exclude:
199 // - the `__stack_output__.json` bookkeeping file — `decodeFqn`
200 // turns `__` into `/`, which would slip the literal name past
201 // a bare-name filter and make the engine look up a
202 // non-existent resource;
203 // - in-flight `*.tmp` files written by `writeAtomic` (and any
204 // other non-`.json` entry), which are not resources.
205 .filter((file) => file.endsWith(".json") && file !== "__stack_output__.json")
206 .map((file) => decodeFqn(file.replace(/\.json$/, ""))),
207 ),
208 ),
209 getOutput: (request) =>
210 fs.readFile(outputFile(request)).pipe(
211 Effect.map((file) => parseState(file.toString())),
212 recover,
213 ),
214 setOutput: (request) =>
215 ensure(stageDir(request)).pipe(
216 Effect.flatMap(() =>
217 writeAtomic(
218 outputFile(request),
219 JSON.stringify(encodeState(request.value as any), null, 2),
220 ),
221 ),
222 recover,
223 Effect.map(() => request.value),
224 ),
225 };
226 return state;
227 });