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

main
ts 128 lines 5.33 KB
Raw
1 import { RuntimeContext } from "alchemy/RuntimeContext";
2 import * as Effect from "effect/Effect";
3 import * as Stream from "effect/Stream";
4 /**
5 * The delete-purge alarm job (DESIGN.md §2.3 Delete).
6 *
7 * `DELETE /repos/:o/:r` responds 204 immediately; this job then runs from
8 * the Repo DO's alarm until everything is gone:
9 *
10 * 1. **Registry row** — removed FIRST, freeing the `owner/name` for reuse
11 * right away (the fork pin below never reserves a name).
12 * 2. **R2 prefix** — a bounded list+delete loop over `{repoId}/`, but only
13 * while no live fork rows reference this repo (`fork_of` count): forks
14 * reference keys under the parent's prefix by full key (immutable,
15 * shared), so a forked repo's prefix is retained until its forks are
16 * gone.
17 * 3. **SQLite** — dropped via `deleteAll` once the pin clears and the
18 * prefix is drained.
19 *
20 * The job is idempotent and alarm-re-armable: every step tolerates having
21 * already run. A single alarm run deletes at most
22 * {@link MAX_PAGES_PER_RUN} × 1000 R2 objects and reports `"continue"` so
23 * the caller re-arms the alarm instead of blowing the 15-minute budget.
24 */
25 import type { BlobStoreError, BlobStoreShape } from "../BlobStore.ts";
26 import { StoreError } from "../Protocol/Store.ts";
27 import { repoPrefix } from "../Store/Keys.ts";
28
29 /** R2 `list` pages drained per alarm run (1000 keys per page). */
30 export const MAX_PAGES_PER_RUN = 10;
31
32 /** Outcome of one purge run. */
33 export type PurgeOutcome =
34 | {
35 /** Everything is gone (R2 prefix, SQLite, Registry row). */
36 readonly _tag: "done";
37 }
38 | {
39 /**
40 * More R2 keys remain (or the prefix is fork-pinned); the caller
41 * must re-arm the alarm and run again.
42 */
43 readonly _tag: "continue";
44 /** True when the prefix was retained because `fork_count > 0`. */
45 readonly forkPinned: boolean;
46 };
47
48 /** Dependencies of {@link runPurgeJob}. */
49 export interface PurgeJobOptions {
50 /** The repo's ULID (R2 key prefix). */
51 readonly repoId: string;
52 /** The swappable bulk-byte store. */
53 readonly blobs: BlobStoreShape;
54 /** Reads the current fork count from the Registry. */
55 readonly forkCount: Effect.Effect<number, StoreError>;
56 /** Drops the DO's entire SQLite/KV state (`storage.deleteAll`). */
57 readonly deleteAllStorage: Effect.Effect<void, StoreError>;
58 /** Removes the Registry row (FIRST step — frees the name; idempotent). */
59 readonly removeRegistryRow: Effect.Effect<void, StoreError>;
60 }
61
62 /** Folds R2 errors into the job's typed error. */
63 const r2ToStore =
64 (what: string) =>
65 <A>(effect: Effect.Effect<A, BlobStoreError, RuntimeContext>): Effect.Effect<A, StoreError> =>
66 effect.pipe(
67 Effect.mapError((error) => StoreError.make({ reason: `${what}: ${error.reason}` })),
68 Effect.provide(RuntimeContext.phantom),
69 );
70
71 /**
72 * Runs one bounded purge round. The registry row is removed FIRST — the
73 * `owner/name` frees immediately, even while forks pin the R2 prefix.
74 * Returns `"done"` when the repo is fully gone; `"continue"` when the
75 * caller must re-arm the alarm (more R2 keys, or the prefix is pinned by
76 * live forks — the DO's SQLite survives until the pin clears so the alarm
77 * keeps re-arming with the repoId at hand).
78 */
79 export const runPurgeJob = (options: PurgeJobOptions): Effect.Effect<PurgeOutcome, StoreError> =>
80 Effect.gen(function* () {
81 const prefix = repoPrefix(options.repoId);
82
83 // 1. Free the name IMMEDIATELY — even while fork-pinned. The pin only
84 // protects the R2 prefix (forks read shared keys under it); the
85 // `owner/name` must never stay reserved for the lifetime of a fork.
86 // `forkCount` derives from live `fork_of` rows, so it keeps working
87 // after this row is gone. Idempotent across alarm retries.
88 yield* options.removeRegistryRow;
89
90 const forks = yield* options.forkCount;
91 if (forks > 0) {
92 // Fork-retention pin: leave the R2 prefix in place and keep the DO's
93 // SQLite (config carries the repoId; jobs row keeps re-arming) until
94 // the last fork is purged.
95 return { _tag: "continue", forkPinned: true } satisfies PurgeOutcome;
96 }
97
98 // 2. Bounded R2 prefix drain.
99 // Bounded drain: take at most MAX_PAGES_PER_RUN pages worth of keys
100 // from the listing stream, delete in 1000-key batches, and treat a
101 // short take as fully drained.
102 const cap = MAX_PAGES_PER_RUN * 1000;
103 const keys = yield* options.blobs.list(prefix).pipe(
104 Stream.take(cap),
105 Stream.map((meta) => meta.key),
106 Stream.runCollect,
107 r2ToStore(`blob list ${prefix}`),
108 );
109 for (let at = 0; at < keys.length; at += 1000) {
110 yield* r2ToStore(`blob delete under ${prefix}`)(
111 options.blobs.delete(keys.slice(at, at + 1000)),
112 );
113 }
114 const drained = keys.length < cap;
115 if (!drained) {
116 return { _tag: "continue", forkPinned: false } satisfies PurgeOutcome;
117 }
118
119 // 3. Drop the DO's own state (the registry row is already gone — see
120 // step 1; a crash that loses this `deleteAll` is harmless because a
121 // re-created `owner/name` mints a fresh repoId and therefore a fresh
122 // DO, so the stale storage is never addressed again). NOTE: this
123 // wipes the `jobs` table — the caller must not touch SQLite after
124 // this point.
125 yield* options.deleteAllStorage;
126
127 return { _tag: "done" } satisfies PurgeOutcome;
128 });