The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import type { Database } from "@alchemy.run/cloudflare/D1"; |
| 3 | import type { QueryDatabaseClient } from "@alchemy.run/cloudflare/D1"; |
| 4 | /** |
| 5 | * `Git.RegistryD1` — the repo index on a D1 database. |
| 6 | * |
| 7 | * An interchangeable implementation of {@link RegistryStore}: same |
| 8 | * contract as {@link RegistryDurableObject}, different scaling shape. |
| 9 | * The Durable Object is one single-threaded object in one region for the |
| 10 | * whole service; D1 replicates reads, and `owner/name` resolution plus |
| 11 | * `WHERE owner = ?` listing are exactly what a relational store is built |
| 12 | * for. Writes (create, delete, summary refresh) are rare by comparison. |
| 13 | * |
| 14 | * Uniqueness moves with it. The DO gets a compare-and-swap from its own |
| 15 | * single-threaded `transactionSync`; here it comes from the schema — |
| 16 | * `PRIMARY KEY (owner, name)` plus an insert guarded by `WHERE NOT |
| 17 | * EXISTS`, which SQLite evaluates atomically within the statement. A |
| 18 | * losing racer sees `changes === 0` and reports `RepoAlreadyExists`, |
| 19 | * with no error-string sniffing. |
| 20 | * |
| 21 | * ### Choosing an index |
| 22 | * **Example:** D1 instead of the default Durable Object |
| 23 | * ```typescript |
| 24 | * const RepoIndex = Cloudflare.D1.Database("RepoIndex"); |
| 25 | * |
| 26 | * const GitLive = Git.ApiLive.pipe( |
| 27 | * Layer.provide(Git.ApiHandlersLive), |
| 28 | * Layer.provide(Authentication.layer), |
| 29 | * Layer.provide(Git.ReposDurableObject), |
| 30 | * Layer.provide(Git.RegistryD1(RepoIndex)), |
| 31 | * Layer.provide(Git.BlobStoreR2(GitObjects)), |
| 32 | * ); |
| 33 | * ``` |
| 34 | * |
| 35 | * @layer |
| 36 | * @provides Git.RegistryStore |
| 37 | * @product Git |
| 38 | */ |
| 39 | import type * as runtime from "@cloudflare/workers-types"; |
| 40 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 41 | import * as Cause from "effect/Cause"; |
| 42 | import * as Effect from "effect/Effect"; |
| 43 | import * as Layer from "effect/Layer"; |
| 44 | import { RepoAlreadyExists, ValidationError } from "./Api.ts"; |
| 45 | import { StoreError } from "./Protocol/Store.ts"; |
| 46 | import { |
| 47 | DEFAULT_LIST_LIMIT, |
| 48 | RegistryStore, |
| 49 | RESERVED_OWNERS, |
| 50 | decodeCursor, |
| 51 | encodeCursor, |
| 52 | toEntry, |
| 53 | ulid, |
| 54 | type CreateRepoInput, |
| 55 | type ListReposInput, |
| 56 | type ListReposResult, |
| 57 | type RegistryEntry, |
| 58 | type RegistryShape, |
| 59 | type RepoSummary, |
| 60 | } from "./RegistryObject.ts"; |
| 61 | import { REGISTRY_DDL, type RegistryRepoRow } from "./Store/Sql.ts"; |
| 62 | |
| 63 | /** |
| 64 | * D1's executors put failures in the defect channel (their error channel |
| 65 | * is `never`), so every call is wrapped to surface as a typed |
| 66 | * {@link StoreError} like the rest of the service. |
| 67 | */ |
| 68 | const d1 = <A>( |
| 69 | what: string, |
| 70 | effect: Effect.Effect<A, never, RuntimeContext>, |
| 71 | ): Effect.Effect<A, StoreError, RuntimeContext> => |
| 72 | Effect.catchCause(effect, (cause) => |
| 73 | Effect.fail(StoreError.make({ reason: `registry ${what}: ${Cause.pretty(cause)}` })), |
| 74 | ); |
| 75 | |
| 76 | /** |
| 77 | * The repo index on D1. The database must already exist; the table is |
| 78 | * created idempotently on first use from the same DDL the Durable Object |
| 79 | * applies, so the two backends stay schema-identical. |
| 80 | */ |
| 81 | export const RegistryD1 = (database: Database): Layer.Layer<RegistryStore> => |
| 82 | Layer.effect( |
| 83 | RegistryStore, |
| 84 | Effect.gen(function* () { |
| 85 | const db: QueryDatabaseClient = yield* Cloudflare.D1.QueryDatabase(database); |
| 86 | |
| 87 | // The DDL is shared with the DO (Store/Sql.ts) — one definition, so |
| 88 | // the backends can never drift apart. |
| 89 | const ready = Effect.suspend(() => |
| 90 | Effect.forEach(REGISTRY_DDL, (statement) => d1("schema", db.prepare(statement).run())), |
| 91 | ).pipe(Effect.asVoid, Effect.cached); |
| 92 | const schema = yield* ready; |
| 93 | |
| 94 | const rows = <T>(result: runtime.D1Result<T>): ReadonlyArray<T> => |
| 95 | (result.results ?? []) as ReadonlyArray<T>; |
| 96 | |
| 97 | const shape: RegistryShape = { |
| 98 | createRepo: Effect.fn(function* (input: CreateRepoInput) { |
| 99 | const owner = input.owner.toLowerCase(); |
| 100 | const name = input.name.toLowerCase(); |
| 101 | if (RESERVED_OWNERS.has(owner)) { |
| 102 | return yield* ValidationError.make({ |
| 103 | message: `owner name '${owner}' is reserved`, |
| 104 | }); |
| 105 | } |
| 106 | yield* schema; |
| 107 | const repoId = yield* ulid(); |
| 108 | const createdAt = Date.now(); |
| 109 | |
| 110 | // Guarded insert: SQLite evaluates the NOT EXISTS and the write |
| 111 | // atomically, so this is the CAS the DO gets from its single |
| 112 | // thread. `changes === 0` means someone already holds the name |
| 113 | // (a soft-deleted row still does, until purge frees it). |
| 114 | const inserted = yield* d1( |
| 115 | "createRepo", |
| 116 | db |
| 117 | .prepare( |
| 118 | `INSERT INTO repos |
| 119 | (owner, name, repo_id, description, is_public, fork_of, fork_count, created_at, deleted_at) |
| 120 | SELECT ?, ?, ?, ?, ?, ?, 0, ?, NULL |
| 121 | WHERE NOT EXISTS ( |
| 122 | SELECT 1 FROM repos WHERE owner = ? AND name = ? |
| 123 | )`, |
| 124 | ) |
| 125 | .bind( |
| 126 | owner, |
| 127 | name, |
| 128 | repoId, |
| 129 | input.description ?? null, |
| 130 | input.public === true ? 1 : 0, |
| 131 | input.forkOf ?? null, |
| 132 | createdAt, |
| 133 | owner, |
| 134 | name, |
| 135 | ) |
| 136 | .run(), |
| 137 | ); |
| 138 | if ((inserted.meta?.changes ?? 0) === 0) { |
| 139 | return yield* RepoAlreadyExists.make({ owner, repo: name }); |
| 140 | } |
| 141 | if (input.forkOf !== undefined) { |
| 142 | // Deliberately not batched with the insert: the fork count is |
| 143 | // only ever READ derived from live `fork_of` rows (see |
| 144 | // `bumpForkCount` with delta 0), so a crash between the two |
| 145 | // cannot strand a purge. |
| 146 | yield* d1( |
| 147 | "recordFork", |
| 148 | db |
| 149 | .prepare(`UPDATE repos SET fork_count = fork_count + 1 WHERE repo_id = ?`) |
| 150 | .bind(input.forkOf) |
| 151 | .run(), |
| 152 | ); |
| 153 | } |
| 154 | return { |
| 155 | owner, |
| 156 | name, |
| 157 | repoId, |
| 158 | defaultBranch: "main", |
| 159 | readOnly: false, |
| 160 | public: input.public === true, |
| 161 | status: "ready", |
| 162 | description: input.description ?? null, |
| 163 | forkOf: input.forkOf ?? null, |
| 164 | forkCount: 0, |
| 165 | createdAt, |
| 166 | deletedAt: null, |
| 167 | } satisfies RegistryEntry; |
| 168 | }), |
| 169 | |
| 170 | resolve: Effect.fn(function* (owner: string, name: string) { |
| 171 | yield* schema; |
| 172 | // Soft-deleted rows ARE returned (with `deletedAt` set) so the |
| 173 | // Worker can report `status: "deleting"` rather than a 404 that |
| 174 | // would race a re-create against the purge. |
| 175 | const row = yield* d1( |
| 176 | "resolve", |
| 177 | db |
| 178 | .prepare(`SELECT * FROM repos WHERE owner = ? AND name = ?`) |
| 179 | .bind(owner.toLowerCase(), name.toLowerCase()) |
| 180 | .first<RegistryRepoRow>(), |
| 181 | ); |
| 182 | return row === null ? undefined : toEntry(row); |
| 183 | }), |
| 184 | |
| 185 | list: Effect.fn(function* (input: ListReposInput) { |
| 186 | yield* schema; |
| 187 | const limit = Math.max(1, Math.min(input.limit ?? DEFAULT_LIST_LIMIT, 100)); |
| 188 | const after = input.cursor === undefined ? undefined : decodeCursor(input.cursor); |
| 189 | const conditions: Array<string> = ["deleted_at IS NULL"]; |
| 190 | const bindings: Array<string | number> = []; |
| 191 | if (input.publicOnly === true) { |
| 192 | conditions.push("is_public = 1"); |
| 193 | } |
| 194 | if (input.owner !== undefined) { |
| 195 | conditions.push("owner = ?"); |
| 196 | bindings.push(input.owner.toLowerCase()); |
| 197 | } |
| 198 | if (after !== undefined) { |
| 199 | conditions.push("(owner > ? OR (owner = ? AND name > ?))"); |
| 200 | bindings.push(after[0], after[0], after[1]); |
| 201 | } |
| 202 | const page = yield* d1( |
| 203 | "list", |
| 204 | db |
| 205 | .prepare( |
| 206 | `SELECT * FROM repos WHERE ${conditions.join(" AND ")} |
| 207 | ORDER BY owner, name LIMIT ?`, |
| 208 | ) |
| 209 | .bind(...bindings, limit + 1) |
| 210 | .all<RegistryRepoRow>(), |
| 211 | ); |
| 212 | const all = rows(page); |
| 213 | const hasMore = all.length > limit; |
| 214 | const items = hasMore ? all.slice(0, limit) : all; |
| 215 | const last = items[items.length - 1]; |
| 216 | return { |
| 217 | items: items.map(toEntry), |
| 218 | nextCursor: hasMore && last !== undefined ? encodeCursor(last.owner, last.name) : null, |
| 219 | hasMore, |
| 220 | } satisfies ListReposResult; |
| 221 | }), |
| 222 | |
| 223 | recordFork: (parentRepoId) => shape.bumpForkCount(parentRepoId, 1), |
| 224 | |
| 225 | bumpForkCount: Effect.fn(function* (repoId: string, delta: number) { |
| 226 | yield* schema; |
| 227 | if (delta !== 0) { |
| 228 | yield* d1( |
| 229 | "bumpForkCount", |
| 230 | db |
| 231 | .prepare(`UPDATE repos SET fork_count = MAX(0, fork_count + ?) WHERE repo_id = ?`) |
| 232 | .bind(delta, repoId) |
| 233 | .run(), |
| 234 | ); |
| 235 | const row = yield* d1( |
| 236 | "bumpForkCount read", |
| 237 | db |
| 238 | .prepare(`SELECT fork_count FROM repos WHERE repo_id = ?`) |
| 239 | .bind(repoId) |
| 240 | .first<{ fork_count: number }>(), |
| 241 | ); |
| 242 | return row?.fork_count ?? 0; |
| 243 | } |
| 244 | // Delta 0 DERIVES the count from live fork rows rather than the |
| 245 | // stored column, so the purge fork-pin keeps working after the |
| 246 | // parent's own row is removed (matching the DO exactly). |
| 247 | const row = yield* d1( |
| 248 | "forkCount", |
| 249 | db |
| 250 | .prepare(`SELECT COUNT(*) AS n FROM repos WHERE fork_of = ?`) |
| 251 | .bind(repoId) |
| 252 | .first<{ n: number }>(), |
| 253 | ); |
| 254 | return row?.n ?? 0; |
| 255 | }), |
| 256 | |
| 257 | markDeleted: Effect.fn(function* (repoId: string) { |
| 258 | yield* schema; |
| 259 | yield* d1( |
| 260 | "markDeleted", |
| 261 | db |
| 262 | .prepare(`UPDATE repos SET deleted_at = ? WHERE repo_id = ? AND deleted_at IS NULL`) |
| 263 | .bind(Date.now(), repoId) |
| 264 | .run(), |
| 265 | ); |
| 266 | }), |
| 267 | |
| 268 | updateSummary: Effect.fn(function* (repoId: string, summary: RepoSummary) { |
| 269 | yield* schema; |
| 270 | yield* d1( |
| 271 | "updateSummary", |
| 272 | db |
| 273 | .prepare( |
| 274 | `UPDATE repos SET default_branch = ?, read_only = ?, is_public = ?, status = ? |
| 275 | WHERE repo_id = ?`, |
| 276 | ) |
| 277 | .bind( |
| 278 | summary.defaultBranch, |
| 279 | summary.readOnly ? 1 : 0, |
| 280 | summary.public ? 1 : 0, |
| 281 | summary.status, |
| 282 | repoId, |
| 283 | ) |
| 284 | .run(), |
| 285 | ); |
| 286 | }), |
| 287 | |
| 288 | removeRow: Effect.fn(function* (repoId: string) { |
| 289 | yield* schema; |
| 290 | const row = yield* d1( |
| 291 | "removeRow read", |
| 292 | db |
| 293 | .prepare(`SELECT * FROM repos WHERE repo_id = ?`) |
| 294 | .bind(repoId) |
| 295 | .first<RegistryRepoRow>(), |
| 296 | ); |
| 297 | if (row === null) { |
| 298 | return; // idempotent — purge re-runs are expected |
| 299 | } |
| 300 | // One batch: the row goes and the fork parent is decremented |
| 301 | // together, or neither happens. |
| 302 | const statements = [ |
| 303 | db.prepare(`DELETE FROM repos WHERE repo_id = ?`).bind(repoId), |
| 304 | ...(row.fork_of !== null |
| 305 | ? [ |
| 306 | db |
| 307 | .prepare( |
| 308 | `UPDATE repos SET fork_count = MAX(0, fork_count - 1) WHERE repo_id = ?`, |
| 309 | ) |
| 310 | .bind(row.fork_of), |
| 311 | ] |
| 312 | : []), |
| 313 | ]; |
| 314 | yield* d1("removeRow", db.batch(statements)); |
| 315 | }), |
| 316 | }; |
| 317 | |
| 318 | return shape; |
| 319 | }), |
| 320 | ).pipe(Layer.provide(Cloudflare.D1.QueryDatabaseBinding)) as never; |