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

main
ts 284 lines 10.4 KB
Raw
1 import { Query, type UnwrapPlan } from "@distilled.cloud/core/query";
2 import {
3 Railway,
4 type SandboxCheckpoint as RailwaySandboxCheckpoint,
5 } from "@distilled.cloud/railway";
6 import { OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
7 import { isResolved } from "alchemy/Diff";
8 import * as Provider from "alchemy/Provider";
9 import { Resource } from "alchemy/Resource";
10 import * as Effect from "effect/Effect";
11 import { waitUntilDeleted } from "./GraphQL.ts";
12 import { createRailwayName, matchesAlchemyPhysicalName } from "./Metadata.ts";
13 import { ownedProjects, projectEnvironmentIds } from "./Project.ts";
14 import type { Providers } from "./Providers.ts";
15 import type { SandboxIdentity } from "./Sandbox.ts";
16
17 const checkpointFields = <E>(checkpoint: Query<RailwaySandboxCheckpoint, E>) => ({
18 id: checkpoint.id,
19 key: checkpoint.key,
20 environmentId: checkpoint.environmentId,
21 createdAt: checkpoint.createdAt,
22 });
23
24 type CloudCheckpoint = UnwrapPlan<ReturnType<typeof checkpointFields>>;
25
26 export interface SandboxCheckpointProps {
27 /**
28 * Running sandbox to capture. Accepts a Railway.Sandbox or a
29 * `{ sandboxId, environmentId }` identity. Changing either ID replaces
30 * the checkpoint; the old checkpoint is deleted first when reusing its name.
31 */
32 sandbox: SandboxIdentity;
33 /**
34 * Checkpoint name, unique within the environment. Defaults to an
35 * instance-specific physical name. Changing it renames the existing
36 * snapshot without capturing the source again. Removing it restores
37 * the generated name.
38 */
39 name?: string;
40 }
41
42 export type SandboxCheckpoint = Resource<
43 "Railway.SandboxCheckpoint",
44 SandboxCheckpointProps,
45 {
46 /** Railway checkpoint ID. May change when the checkpoint is renamed. */
47 sandboxCheckpointId: string;
48 /** Environment that stores the snapshot. */
49 environmentId: string;
50 /** Source sandbox ID, or undefined for checkpoints discovered by listing. */
51 sandboxId: string | undefined;
52 /** Checkpoint name, usable as Sandbox's `template.name`. */
53 name: string;
54 /** Railway checkpoint key, identical to the checkpoint name. */
55 key: string;
56 /** RFC3339 capture timestamp; also distinguishes recaptures under the same ID. */
57 createdAt: string;
58 },
59 never,
60 Providers
61 >;
62
63 /**
64 * A managed, named snapshot of a running Railway sandbox's disk. Capture is
65 * synchronous: the checkpoint is bootable when deployment completes. Files
66 * survive restoration, but running processes and memory do not.
67 *
68 * The snapshot is captured once, not on every deploy. Changing the source
69 * replaces it; changing the name renames it. Existing explicit names require
70 * adoption. Persisted ID and capture time protect against deleting or
71 * overwriting a different capture that later occupies the same name.
72 * Interrupted renames are recovered from the persisted attempted name and
73 * original capture time. Recovery never searches arbitrary names by timestamp;
74 * losing either piece of evidence requires explicit operator recovery.
75 * Railway exposes no conditional mutations, so concurrent external writers
76 * must not mutate the same checkpoint while Alchemy is reconciling it.
77 *
78 * ### Capture a sandbox
79 * **Example:** Managed snapshot
80 * ```typescript
81 * const box = yield* Railway.Sandbox("Box", { environment: site });
82 * const checkpoint = yield* Railway.SandboxCheckpoint("Prepared", {
83 * sandbox: box,
84 * });
85 * ```
86 *
87 * ### Restore a checkpoint
88 * **Example:** Boot an independent sandbox
89 * ```typescript
90 * const restored = yield* Railway.Sandbox("Restored", {
91 * environment: site,
92 * template: { name: checkpoint.key },
93 * });
94 * ```
95 *
96 * ### Adopt an existing checkpoint
97 * **Example:** Manage a named snapshot without recapturing it
98 * ```typescript
99 * const checkpoint = yield* Railway.SandboxCheckpoint("Prepared", {
100 * sandbox: box,
101 * name: "after-deps",
102 * }).pipe(Alchemy.adopt(true));
103 * ```
104 *
105 * @see https://docs.railway.com/sandboxes#checkpoints
106 *
107 * @resource
108 * @product Sandbox
109 */
110 export const SandboxCheckpoint = Resource<SandboxCheckpoint>("Railway.SandboxCheckpoint");
111
112 const listCheckpoints = Query.fn((environmentId: string) =>
113 Railway.sandboxCheckpoints({ environmentId }).pipe(Query.map(checkpointFields)),
114 );
115
116 const sandboxCheckpointCreate = Query.fn(
117 (input: { environmentId: string; sandboxId: string; name: string }) =>
118 checkpointFields(Railway.sandboxCheckpointCreate(input)),
119 );
120
121 const sandboxCheckpointRename = Query.fn(
122 (input: { environmentId: string; id: string; name: string }) =>
123 checkpointFields(Railway.sandboxCheckpointRename(input)),
124 );
125
126 /** Railway answers a missing checkpoint with `false`, not an error. */
127 const sandboxCheckpointDelete = Query.fn((input: { environmentId: string; id: string }) =>
128 Railway.sandboxCheckpointDelete(input),
129 );
130
131 const toAttrs = (
132 checkpoint: CloudCheckpoint,
133 sandboxId?: string,
134 ): SandboxCheckpoint["Attributes"] => ({
135 sandboxCheckpointId: checkpoint.id,
136 environmentId: checkpoint.environmentId,
137 sandboxId,
138 name: checkpoint.key,
139 key: checkpoint.key,
140 createdAt: checkpoint.createdAt,
141 });
142
143 const sameCapture = (checkpoint: CloudCheckpoint, output: SandboxCheckpoint["Attributes"]) =>
144 checkpoint.id === output.sandboxCheckpointId && checkpoint.createdAt === output.createdAt;
145
146 const findRecordedCheckpoint = Effect.fn(function* (
147 id: string,
148 props: SandboxCheckpointProps | undefined,
149 output: SandboxCheckpoint["Attributes"],
150 items: readonly CloudCheckpoint[],
151 ) {
152 const byId = items.find((item) => item.id === output.sandboxCheckpointId);
153 if (byId !== undefined) return byId;
154 if (
155 props?.sandbox?.environmentId !== output.environmentId ||
156 props?.sandbox?.sandboxId !== output.sandboxId
157 ) {
158 return undefined;
159 }
160 // Updating rows retain attempted props alongside the pre-rename attributes.
161 const attemptedName = props?.name ?? (yield* createRailwayName(id));
162 return items.find((item) => item.key === attemptedName);
163 });
164
165 const conflict = (id: string, name: string) =>
166 new OwnedBySomeoneElse({
167 message: `Sandbox checkpoint ${name} belongs to another capture; adopt it explicitly or choose a different name`,
168 resourceType: "Railway.SandboxCheckpoint",
169 logicalId: id,
170 physicalName: name,
171 });
172
173 export const SandboxCheckpointProvider = () =>
174 Provider.succeed(SandboxCheckpoint, {
175 stables: ["environmentId", "sandboxId"],
176 nuke: { dependsOn: ["Railway.Project", "Railway.Environment"] },
177
178 diff: Effect.fn(function* ({ news, output }) {
179 if (!isResolved(news) || output === undefined) return;
180 if (
181 news.sandbox.sandboxId !== output.sandboxId ||
182 news.sandbox.environmentId !== output.environmentId
183 ) {
184 return {
185 action: "replace" as const,
186 deleteFirst:
187 news.sandbox.environmentId === output.environmentId && news.name === output.name,
188 };
189 }
190 }),
191
192 read: Effect.fn(function* ({ id, olds, output }) {
193 const environmentId = output?.environmentId ?? olds?.sandbox?.environmentId;
194 if (environmentId === undefined) return;
195 const items = yield* listCheckpoints(environmentId);
196 if (output !== undefined) {
197 const found = yield* findRecordedCheckpoint(id, olds, output, items);
198 if (found === undefined) return;
199 if (found.createdAt !== output.createdAt) {
200 return yield* conflict(id, found.key);
201 }
202 return toAttrs(found, output.sandboxId);
203 }
204 const generatedName = yield* createRailwayName(id);
205 const name = olds?.name ?? generatedName;
206 const found = items.find((item) => item.key === name);
207 if (found === undefined) return;
208 const attrs = toAttrs(found, olds?.sandbox?.sandboxId);
209 return found.key === generatedName ? attrs : Unowned(attrs);
210 }),
211
212 list: Effect.fn(function* () {
213 const projects = yield* ownedProjects();
214 const rows = yield* Effect.forEach(projects, (project) =>
215 Effect.gen(function* () {
216 const environments = yield* projectEnvironmentIds(project);
217 return (yield* Effect.forEach(environments, (environmentId) =>
218 listCheckpoints(environmentId).pipe(
219 Effect.map((items) =>
220 items
221 .filter((item) => matchesAlchemyPhysicalName(item.key))
222 .map((item) => toAttrs(item)),
223 ),
224 ),
225 )).flat();
226 }),
227 );
228 return rows.flat();
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const { sandboxId, environmentId } = news.sandbox;
233 const generatedName = yield* createRailwayName(id);
234 const name = news.name ?? generatedName;
235 const items = yield* listCheckpoints(environmentId);
236 let current = output
237 ? items.find((item) => item.id === output.sandboxCheckpointId)
238 : items.find((item) => item.key === name);
239 if (
240 current !== undefined &&
241 (output ? !sameCapture(current, output) : current.key !== generatedName)
242 ) {
243 return yield* conflict(id, current.key);
244 }
245 const target = items.find((item) => item.key === name);
246 if (target !== undefined && target.id !== current?.id) {
247 // Rename can succeed before state persistence; capture time survives it.
248 if (
249 output !== undefined &&
250 current === undefined &&
251 target.createdAt === output.createdAt
252 ) {
253 current = target;
254 } else {
255 return yield* conflict(id, name);
256 }
257 }
258 if (current === undefined) {
259 current = yield* sandboxCheckpointCreate({ environmentId, sandboxId, name });
260 }
261 if (current.key !== name) {
262 current = yield* sandboxCheckpointRename({ environmentId, id: current.id, name });
263 }
264 return toAttrs(current, sandboxId);
265 }),
266
267 delete: Effect.fn(function* ({ id, olds, output }) {
268 const items = yield* listCheckpoints(output.environmentId);
269 const current = yield* findRecordedCheckpoint(id, olds, output, items);
270 if (current === undefined || current.createdAt !== output.createdAt) return;
271 yield* sandboxCheckpointDelete({ environmentId: output.environmentId, id: current.id });
272 yield* waitUntilDeleted(
273 "SandboxCheckpoint",
274 current.id,
275 listCheckpoints(output.environmentId).pipe(
276 Effect.map(
277 (rows) =>
278 !rows.some((item) => item.id === current.id && item.createdAt === current.createdAt),
279 ),
280 ),
281 10,
282 );
283 }),
284 });