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

main
ts 1,038 lines 34.9 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import { Base64 } from "effect/encoding";
4 /** Repository operations over storage services. HTTP handlers adapt these results. */
5 import type * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
6 import * as Layer from "effect/Layer";
7 import type {
8 CompactRepo,
9 Compare,
10 CreatePull,
11 CreateRepo,
12 DeleteRepo,
13 ForkRepo,
14 GetBlob,
15 GetCommit,
16 GetDiff,
17 GetLog,
18 GetPull,
19 GetRef,
20 GetRepo,
21 GetTree,
22 ImportRepo,
23 ListPulls,
24 ListRefs,
25 ListRepos,
26 MergePull,
27 RemoveRef,
28 UpdatePull,
29 UpdateRef,
30 UpdateRepo,
31 } from "./Api.ts";
32 import {
33 CommitDiff,
34 CommitInfo,
35 Comparison,
36 DiffEntry,
37 ImportFailed,
38 MergeResult,
39 ObjectStats,
40 ObjectTooLarge,
41 Pull,
42 PullDetail,
43 PushStats,
44 Ref,
45 Repo,
46 RepoAlreadyExists,
47 RepoCreated,
48 RepoNotFound,
49 RepoNotReady,
50 TreeEntry,
51 type Oid,
52 } from "./Api.ts";
53 import { parseCommit, parseTree, treeEntryKind } from "./Protocol/ObjectCodec.ts";
54 import type { StoreError } from "./Protocol/Store.ts";
55 import { RegistryStore, type RegistryEntry } from "./RegistryObject.ts";
56 import {
57 RepoStore,
58 type CommitData,
59 type DiffEntryData,
60 type PullData,
61 type PullDetailData,
62 type RefData,
63 type RepoMetaData,
64 } from "./RepoObject.ts";
65
66 /** TTL of the in-isolate `owner/name → repoId` cache (DESIGN.md §2.1). */
67 export const RESOLVE_CACHE_TTL_MS = 60_000;
68
69 /** Max entries of the in-isolate resolve cache (insertion-order eviction). */
70 export const RESOLVE_CACHE_MAX = 1024;
71
72 /** Blobs above this size are 422 on the JSON endpoint (use `/raw`). */
73 export const MAX_JSON_BLOB_BYTES = 1024 * 1024;
74
75 // ─────────────────────────────────────────────────────────────────────────────
76 // Pure mapping helpers
77 // ─────────────────────────────────────────────────────────────────────────────
78
79 const asOid = (value: string): Oid => value as Oid;
80
81 /** Maps the Repo DO's plain metadata onto the REST `Repo` schema class. */
82 const toRepo = (meta: RepoMetaData): Repo =>
83 Repo.make({
84 owner: meta.owner,
85 name: meta.name,
86 repoId: meta.repoId,
87 defaultBranch: meta.defaultBranch,
88 description: meta.description,
89 readOnly: meta.readOnly,
90 public: meta.public,
91 forkOf: meta.forkOf,
92 status: meta.status,
93 createdAt: meta.createdAt,
94 objects: ObjectStats.make(meta.objects),
95 lastPush: meta.lastPush === null ? null : PushStats.make(meta.lastPush),
96 });
97
98 /** Maps a DO ref onto the REST `Ref` schema class. */
99 const toRef = (ref: RefData): Ref =>
100 ref.peeled === undefined
101 ? Ref.make({ name: ref.name, oid: asOid(ref.oid) })
102 : Ref.make({
103 name: ref.name,
104 oid: asOid(ref.oid),
105 peeled: asOid(ref.peeled),
106 });
107
108 /** Maps a DO diff entry onto the REST `DiffEntry` schema class. */
109 const toDiffEntry = (entry: DiffEntryData): DiffEntry =>
110 DiffEntry.make({
111 path: entry.path,
112 status: entry.status,
113 oldOid: entry.oldOid === undefined ? undefined : asOid(entry.oldOid),
114 newOid: entry.newOid === undefined ? undefined : asOid(entry.newOid),
115 oldMode: entry.oldMode,
116 newMode: entry.newMode,
117 oldSize: entry.oldSize,
118 newSize: entry.newSize,
119 });
120
121 /** Maps a DO pull row onto the REST `Pull` schema class. */
122 const toPull = (pull: PullData): Pull =>
123 Pull.make({
124 number: pull.number,
125 title: pull.title,
126 body: pull.body,
127 baseRef: pull.baseRef,
128 headRef: pull.headRef,
129 state: pull.state,
130 createdAt: pull.createdAt,
131 updatedAt: pull.updatedAt,
132 mergedAt: pull.mergedAt,
133 mergeCommit: pull.mergeCommit === null ? null : asOid(pull.mergeCommit),
134 });
135
136 /** Maps a DO pull detail onto the REST `PullDetail` schema class. */
137 const toPullDetail = (pull: PullDetailData): PullDetail =>
138 PullDetail.make({
139 number: pull.number,
140 title: pull.title,
141 body: pull.body,
142 baseRef: pull.baseRef,
143 headRef: pull.headRef,
144 state: pull.state,
145 createdAt: pull.createdAt,
146 updatedAt: pull.updatedAt,
147 mergedAt: pull.mergedAt,
148 mergeCommit: pull.mergeCommit === null ? null : asOid(pull.mergeCommit),
149 baseOid: pull.baseOid === null ? null : asOid(pull.baseOid),
150 headOid: pull.headOid === null ? null : asOid(pull.headOid),
151 mergeBase: pull.mergeBase === null ? null : asOid(pull.mergeBase),
152 aheadBy: pull.aheadBy,
153 behindBy: pull.behindBy,
154 mergeable: pull.mergeable,
155 mergeableReason: pull.mergeableReason,
156 });
157
158 /** Maps a DO commit onto the REST `CommitInfo` schema class. */
159 const toCommitInfo = (commit: CommitData): CommitInfo =>
160 CommitInfo.make({
161 oid: asOid(commit.oid),
162 tree: asOid(commit.tree),
163 parents: commit.parents.map(asOid),
164 author: commit.author,
165 committer: commit.committer,
166 message: commit.message,
167 });
168
169 /**
170 * Registry-derived fallback `Repo` for list pages when a Repo DO cannot be
171 * consulted (e.g. its config was never seeded because the create crashed
172 * between the Registry insert and `initRepo`).
173 */
174 const registryFallbackRepo = (entry: RegistryEntry): Repo =>
175 Repo.make({
176 owner: entry.owner,
177 name: entry.name,
178 repoId: entry.repoId,
179 defaultBranch: entry.defaultBranch,
180 description: entry.description,
181 readOnly: entry.readOnly,
182 public: entry.public,
183 forkOf: entry.forkOf,
184 status: entry.deletedAt !== null ? "deleting" : (entry.status as Repo["status"]),
185 createdAt: entry.createdAt,
186 // No DO to ask (unseeded or mid-purge) — report an empty store.
187 objects: ObjectStats.make({
188 loose: 0,
189 resident: 0,
190 packed: 0,
191 r2: 0,
192 bytes: 0,
193 }),
194 lastPush: null,
195 });
196
197 export const makeOperations = Effect.gen(function* () {
198 const registry = yield* RegistryStore;
199 const repos = yield* RepoStore;
200 // The registry block, whichever backend the assembly provided.
201 const registryStub = () => registry;
202
203 // ── owner/name → RegistryEntry, 60 s in-isolate LRU (DESIGN.md §2.1) ──
204 // A stale hit fails safe: the Repo DO stores its own (owner, name) and
205 // 404s mismatched requests, and cache entries are dropped on delete.
206 interface CacheSlot {
207 readonly entry: RegistryEntry;
208 readonly expires: number;
209 }
210 const resolveCache = new Map<string, CacheSlot>();
211
212 const cacheKey = (owner: string, repo: string) => `${owner.toLowerCase()}/${repo.toLowerCase()}`;
213
214 const dropCached = (owner: string, repo: string) =>
215 Effect.sync(() => {
216 resolveCache.delete(cacheKey(owner, repo));
217 });
218
219 const resolveCached = (owner: string, repo: string) =>
220 Effect.gen(function* () {
221 const key = cacheKey(owner, repo);
222 const now = yield* Effect.sync(() => Date.now());
223 const hit = resolveCache.get(key);
224 if (hit !== undefined && hit.expires > now) return hit.entry;
225 const entry = yield* registryStub().resolve(owner, repo);
226 // Rows mid-purge are transient (removed when the purge alarm
227 // finishes) — never cache them, or a 60 s stale hit would keep
228 // reporting "deleting" after the name has freed.
229 if (entry !== undefined && entry.deletedAt === null) {
230 yield* Effect.sync(() => {
231 if (resolveCache.size >= RESOLVE_CACHE_MAX) {
232 const oldest = resolveCache.keys().next().value;
233 if (oldest !== undefined) resolveCache.delete(oldest);
234 }
235 resolveCache.set(key, {
236 entry,
237 expires: now + RESOLVE_CACHE_TTL_MS,
238 });
239 });
240 }
241 return entry;
242 });
243
244 /**
245 * Resolve including rows whose async purge is still draining
246 * (`deletedAt` set) — only `repos.get` (report `status: "deleting"`)
247 * and `repos.delete` (idempotent 204) want those.
248 */
249 const resolveIncludingDeleting = (owner: string, repo: string) =>
250 resolveCached(owner, repo).pipe(
251 Effect.catchTag("StoreError", (error: StoreError) => Effect.die(error)),
252 Effect.flatMap((entry) =>
253 entry === undefined
254 ? Effect.fail(RepoNotFound.make({ owner, repo }))
255 : Effect.succeed(entry),
256 ),
257 );
258
259 /**
260 * Resolve or fail with a typed 404. Rows mid-purge count as gone for
261 * every data-plane route (the name is reserved but the repo is dead).
262 * Storage failures are defects.
263 */
264 const resolveOrNotFound = (owner: string, repo: string) =>
265 resolveIncludingDeleting(owner, repo).pipe(
266 Effect.filterOrFail(
267 (entry) => entry.deletedAt === null,
268 () => RepoNotFound.make({ owner, repo }),
269 ),
270 );
271
272 const remoteUrl = (owner: string, name: string) => Effect.succeed(`/${owner}/${name}.git`);
273
274 // Accept decoded fields rather than endpoint metadata so these handlers also
275 // work with APIs that add middleware or prefixes.
276 // ── REST handler groups ────────────────────────────────────────────────
277
278 /**
279 * Inserts the registry row, repairing an ORPHAN first: a row whose Repo
280 * DO was never seeded (a create that died between the registry insert
281 * and `initRepo`). An orphan poisons the name permanently — `GET` 404s
282 * because the DO has no config, while `POST` 409s because the row
283 * exists — so detect it (registry row present + DO reports
284 * `RepoNotFound`), drop the row, and insert again.
285 */
286 const insertRepoRow = (input: {
287 readonly owner: string;
288 readonly name: string;
289 readonly description?: string | undefined;
290 readonly public?: boolean | undefined;
291 }) =>
292 registryStub()
293 .createRepo(input)
294 .pipe(
295 Effect.catchTags({
296 StoreError: (error) => Effect.die(error),
297 RepoAlreadyExists: (conflict) =>
298 Effect.gen(function* () {
299 const existing = yield* resolveCached(input.owner, input.name).pipe(
300 Effect.catchTag("StoreError", (error) => Effect.die(error)),
301 );
302 if (existing === undefined) {
303 return yield* conflict;
304 }
305 const orphaned = yield* repos
306 .getByName(existing.repoId)
307 .readMeta()
308 .pipe(
309 Effect.as(false),
310 Effect.catchTag("RepoNotFound", () => Effect.succeed(true)),
311 Effect.catchCause(() => Effect.succeed(false)),
312 );
313 if (!orphaned) {
314 return yield* conflict;
315 }
316 yield* registryStub()
317 .removeRow(existing.repoId)
318 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
319 yield* dropCached(input.owner, input.name);
320 return yield* registryStub()
321 .createRepo(input)
322 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
323 }),
324 }),
325 );
326
327 const reposRoutes = {
328 create: ({ payload }: Pick<HttpApiEndpoint.Request<typeof CreateRepo>, "payload">) =>
329 Effect.gen(function* () {
330 const entry = yield* insertRepoRow({
331 owner: payload.owner,
332 name: payload.name,
333 description: payload.description,
334 public: payload.public,
335 });
336 const init = yield* repos
337 .getByName(entry.repoId)
338 .initRepo({
339 repoId: entry.repoId,
340 owner: entry.owner,
341 name: entry.name,
342 defaultBranch: payload.defaultBranch ?? "main",
343 description: payload.description ?? null,
344 readOnly: payload.readOnly ?? false,
345 public: payload.public ?? false,
346 forkOf: null,
347 })
348 .pipe(
349 // Seeding the DO failed (or died): drop the row we just
350 // inserted rather than leave an orphan behind.
351 Effect.onError(() =>
352 registryStub()
353 .removeRow(entry.repoId)
354 .pipe(Effect.ignore, Effect.andThen(dropCached(entry.owner, entry.name))),
355 ),
356 Effect.catchTag("StoreError", (error) => Effect.die(error)),
357 );
358 const remote = yield* remoteUrl(entry.owner, entry.name);
359 return RepoCreated.make({
360 repo: toRepo(init.meta),
361 remote,
362 });
363 }),
364 get: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetRepo>, "params">) =>
365 Effect.gen(function* () {
366 // Includes rows mid-purge: GET keeps reporting
367 // status "deleting" until the purge alarm frees the name (only
368 // then a 404), so "poll GET until 404 then re-create" never
369 // races the purge.
370 const entry = yield* resolveIncludingDeleting(params.owner, params.repo);
371 if (entry.deletedAt !== null) {
372 return registryFallbackRepo(entry);
373 }
374 const meta = yield* repos
375 .getByName(entry.repoId)
376 .getRepoMeta()
377 .pipe(
378 Effect.catchTags({
379 StoreError: (error) => Effect.die(error),
380 RepoNotFound: () =>
381 Effect.fail(
382 RepoNotFound.make({
383 owner: params.owner,
384 repo: params.repo,
385 }),
386 ),
387 }),
388 );
389 return toRepo(meta);
390 }),
391 update: ({
392 params,
393 payload,
394 }: Pick<HttpApiEndpoint.Request<typeof UpdateRepo>, "params" | "payload">) =>
395 Effect.gen(function* () {
396 const entry = yield* resolveOrNotFound(params.owner, params.repo);
397 const meta = yield* repos
398 .getByName(entry.repoId)
399 .updateRepoMeta({
400 description: payload.description,
401 defaultBranch: payload.defaultBranch,
402 readOnly: payload.readOnly,
403 public: payload.public,
404 })
405 .pipe(
406 Effect.catchTags({
407 StoreError: (error) => Effect.die(error),
408 RepoNotFound: () =>
409 Effect.fail(
410 RepoNotFound.make({
411 owner: params.owner,
412 repo: params.repo,
413 }),
414 ),
415 }),
416 );
417 return toRepo(meta);
418 }),
419 list: ({ query }: Pick<HttpApiEndpoint.Request<typeof ListRepos>, "query">) =>
420 Effect.gen(function* () {
421 // Everything the Registry holds; `public: true` narrows it. Who
422 // may list at all was decided in front of the route.
423 const page = yield* registryStub()
424 .list({
425 owner: query.owner,
426 cursor: query.cursor,
427 limit: query.limit,
428 publicOnly: query.public === true,
429 })
430 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
431 // Rendered straight from the Registry's denormalised columns:
432 // listing must NOT wake one Durable Object per row (measured at
433 // ~30 ms per row — DESIGN.md §14.1 / §15 bottleneck 7). Live
434 // `objects` stats need the DO, so a listing reports zeros and
435 // callers who want them read the repo directly.
436 const items = page.items.map(registryFallbackRepo);
437 return {
438 items,
439 nextCursor: page.nextCursor,
440 hasMore: page.hasMore,
441 };
442 }),
443 delete: ({ params }: Pick<HttpApiEndpoint.Request<typeof DeleteRepo>, "params">) =>
444 Effect.gen(function* () {
445 const entry = yield* resolveIncludingDeleting(params.owner, params.repo);
446 // Always (re-)arm the purge — even when the row is already
447 // soft-deleted. A second DELETE mid-drain is an idempotent 204,
448 // and re-arming is what recovers a purge whose alarm was lost
449 // (crash between markDeleted and the first alarm run).
450 yield* repos
451 .getByName(entry.repoId)
452 .startPurge()
453 .pipe(
454 Effect.catchTags({
455 StoreError: (error) => Effect.die(error),
456 // The registry row exists but the DO holds no state — an
457 // orphan, or a purge that already wiped storage. There is
458 // nothing to purge, so free the name directly (never 404:
459 // the caller can see this repo, so DELETE must remove it).
460 RepoNotFound: () =>
461 registryStub()
462 .removeRow(entry.repoId)
463 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error))),
464 }),
465 );
466 yield* registryStub()
467 .markDeleted(entry.repoId)
468 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
469 yield* dropCached(params.owner, params.repo);
470 }),
471 fork: ({
472 params,
473 payload,
474 }: Pick<HttpApiEndpoint.Request<typeof ForkRepo>, "params" | "payload">) =>
475 Effect.gen(function* () {
476 const source = yield* resolveOrNotFound(params.owner, params.repo);
477 const sourceMeta = yield* repos
478 .getByName(source.repoId)
479 .readMeta()
480 .pipe(
481 Effect.catchTags({
482 StoreError: (error) => Effect.die(error),
483 RepoNotFound: () =>
484 Effect.fail(
485 RepoNotFound.make({
486 owner: params.owner,
487 repo: params.repo,
488 }),
489 ),
490 }),
491 );
492 if (sourceMeta.status !== "ready") {
493 return yield* RepoNotReady.make({ status: sourceMeta.status });
494 }
495 const entry = yield* registryStub()
496 .createRepo({
497 owner: payload.targetOwner,
498 name: payload.targetName,
499 description: sourceMeta.description ?? undefined,
500 forkOf: source.repoId,
501 })
502 .pipe(
503 Effect.catchTags({
504 StoreError: (error) => Effect.die(error),
505 // `fork` declares no ValidationError (reserved target
506 // owner) — surface it as the closest declared conflict.
507 ValidationError: () =>
508 Effect.fail(
509 RepoAlreadyExists.make({
510 owner: payload.targetOwner,
511 repo: payload.targetName,
512 }),
513 ),
514 }),
515 );
516 const init = yield* repos
517 .getByName(entry.repoId)
518 .startFork({
519 repoId: entry.repoId,
520 owner: entry.owner,
521 name: entry.name,
522 defaultBranch: sourceMeta.defaultBranch,
523 description: sourceMeta.description,
524 readOnly: false,
525 // Forks inherit the source's visibility.
526 public: sourceMeta.public,
527 forkOf: source.repoId,
528 parentRepoId: source.repoId,
529 })
530 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
531 const remote = yield* remoteUrl(entry.owner, entry.name);
532 return RepoCreated.make({
533 repo: toRepo(init.meta),
534 remote,
535 });
536 }),
537 compact: ({ params }: Pick<HttpApiEndpoint.Request<typeof CompactRepo>, "params">) =>
538 Effect.gen(function* () {
539 const entry = yield* resolveOrNotFound(params.owner, params.repo);
540 yield* repos
541 .getByName(entry.repoId)
542 .startCompact()
543 .pipe(
544 Effect.catchTags({
545 StoreError: (error) => Effect.die(error),
546 RepoNotFound: () =>
547 Effect.fail(
548 RepoNotFound.make({
549 owner: params.owner,
550 repo: params.repo,
551 }),
552 ),
553 }),
554 );
555 }),
556 import: ({ payload }: Pick<HttpApiEndpoint.Request<typeof ImportRepo>, "payload">) =>
557 Effect.gen(function* () {
558 const entry = yield* registryStub()
559 .createRepo({
560 owner: payload.owner,
561 name: payload.name,
562 })
563 .pipe(
564 Effect.catchTags({
565 StoreError: (error) => Effect.die(error),
566 // `import` declares no ValidationError — a reserved owner
567 // is an import that can never succeed.
568 ValidationError: (error) => Effect.fail(ImportFailed.make({ reason: error.message })),
569 }),
570 );
571 const init = yield* repos
572 .getByName(entry.repoId)
573 .startImport({
574 repoId: entry.repoId,
575 owner: entry.owner,
576 name: entry.name,
577 defaultBranch: "main",
578 description: null,
579 readOnly: false,
580 public: false,
581 forkOf: null,
582 source: {
583 url: payload.source.url,
584 ref: payload.source.ref,
585 depth: payload.source.depth,
586 },
587 })
588 .pipe(Effect.catchTag("StoreError", (error) => Effect.die(error)));
589 const remote = yield* remoteUrl(entry.owner, entry.name);
590 return RepoCreated.make({
591 repo: toRepo(init.meta),
592 remote,
593 });
594 }),
595 };
596
597 const refsRoutes = {
598 list: ({ params, query }: Pick<HttpApiEndpoint.Request<typeof ListRefs>, "params" | "query">) =>
599 Effect.gen(function* () {
600 const entry = yield* resolveOrNotFound(params.owner, params.repo);
601 const page = yield* repos
602 .getByName(entry.repoId)
603 .listRefs(query.prefix)
604 .pipe(
605 Effect.catchTags({
606 StoreError: (error) => Effect.die(error),
607 RepoNotFound: () =>
608 Effect.fail(
609 RepoNotFound.make({
610 owner: params.owner,
611 repo: params.repo,
612 }),
613 ),
614 }),
615 );
616 return { head: page.head, refs: page.refs.map(toRef) };
617 }),
618 get: ({ params, query }: Pick<HttpApiEndpoint.Request<typeof GetRef>, "params" | "query">) =>
619 Effect.gen(function* () {
620 const entry = yield* resolveOrNotFound(params.owner, params.repo);
621 const ref = yield* repos
622 .getByName(entry.repoId)
623 .getRef(query.name)
624 .pipe(
625 Effect.catchTags({
626 StoreError: (error) => Effect.die(error),
627 RepoNotFound: () =>
628 Effect.fail(
629 RepoNotFound.make({
630 owner: params.owner,
631 repo: params.repo,
632 }),
633 ),
634 }),
635 );
636 return toRef(ref);
637 }),
638 update: ({
639 params,
640 query,
641 payload,
642 }: Pick<HttpApiEndpoint.Request<typeof UpdateRef>, "params" | "query" | "payload">) =>
643 Effect.gen(function* () {
644 const entry = yield* resolveOrNotFound(params.owner, params.repo);
645 const stub = repos.getByName(entry.repoId);
646 const ref = yield* stub
647 .updateRef({
648 name: query.name,
649 newOid: payload.newOid,
650 expectedOid: payload.expectedOid,
651 })
652 .pipe(
653 Effect.catchTags({
654 StoreError: (error) => Effect.die(error),
655 RepoNotFound: () =>
656 Effect.fail(
657 RepoNotFound.make({
658 owner: params.owner,
659 repo: params.repo,
660 }),
661 ),
662 }),
663 );
664 return toRef(ref);
665 }),
666 remove: ({
667 params,
668 query,
669 payload,
670 }: Pick<HttpApiEndpoint.Request<typeof RemoveRef>, "params" | "query" | "payload">) =>
671 Effect.gen(function* () {
672 const entry = yield* resolveOrNotFound(params.owner, params.repo);
673 const stub = repos.getByName(entry.repoId);
674 yield* stub
675 .removeRef({
676 name: query.name,
677 expectedOid: payload.expectedOid,
678 })
679 .pipe(
680 Effect.catchTags({
681 StoreError: (error) => Effect.die(error),
682 RepoNotFound: () =>
683 Effect.fail(
684 RepoNotFound.make({
685 owner: params.owner,
686 repo: params.repo,
687 }),
688 ),
689 }),
690 );
691 }),
692 };
693
694 const objectsRoutes = {
695 commit: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetCommit>, "params">) =>
696 Effect.gen(function* () {
697 const entry = yield* resolveOrNotFound(params.owner, params.repo);
698 const data = yield* repos
699 .getByName(entry.repoId)
700 .readObject({ oid: params.oid, expect: "commit" })
701 .pipe(
702 Effect.catchTags({
703 StoreError: (error) => Effect.die(error),
704 RepoNotFound: () =>
705 Effect.fail(
706 RepoNotFound.make({
707 owner: params.owner,
708 repo: params.repo,
709 }),
710 ),
711 }),
712 );
713 // A stored commit that fails to parse is corrupt — a defect.
714 const parsed = yield* parseCommit(data.content).pipe(Effect.orDie);
715 return CommitInfo.make({
716 oid: params.oid,
717 tree: asOid(parsed.tree),
718 parents: parsed.parents.map(asOid),
719 author: {
720 name: parsed.author.name,
721 email: parsed.author.email,
722 date: parsed.author.when,
723 tz: parsed.author.tz,
724 },
725 committer: {
726 name: parsed.committer.name,
727 email: parsed.committer.email,
728 date: parsed.committer.when,
729 tz: parsed.committer.tz,
730 },
731 message: parsed.message,
732 });
733 }),
734 log: ({ params, query }: Pick<HttpApiEndpoint.Request<typeof GetLog>, "params" | "query">) =>
735 Effect.gen(function* () {
736 const entry = yield* resolveOrNotFound(params.owner, params.repo);
737 const page = yield* repos
738 .getByName(entry.repoId)
739 .readCommitLog({
740 ref: query.ref,
741 cursor: query.cursor,
742 limit: query.limit,
743 })
744 .pipe(
745 Effect.catchTags({
746 StoreError: (error) => Effect.die(error),
747 RepoNotFound: () =>
748 Effect.fail(
749 RepoNotFound.make({
750 owner: params.owner,
751 repo: params.repo,
752 }),
753 ),
754 }),
755 );
756 return {
757 items: page.items.map(toCommitInfo),
758 nextCursor: page.nextCursor,
759 hasMore: page.hasMore,
760 };
761 }),
762 tree: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetTree>, "params">) =>
763 Effect.gen(function* () {
764 const entry = yield* resolveOrNotFound(params.owner, params.repo);
765 const data = yield* repos
766 .getByName(entry.repoId)
767 .readObject({ oid: params.oid, expect: "tree" })
768 .pipe(
769 Effect.catchTags({
770 StoreError: (error) => Effect.die(error),
771 RepoNotFound: () =>
772 Effect.fail(
773 RepoNotFound.make({
774 owner: params.owner,
775 repo: params.repo,
776 }),
777 ),
778 }),
779 );
780 const entries = yield* parseTree(data.content).pipe(Effect.orDie);
781 return {
782 oid: params.oid,
783 entries: entries.map((item) =>
784 TreeEntry.make({
785 mode: item.mode,
786 name: item.name,
787 oid: asOid(item.oid),
788 type: treeEntryKind(item.mode),
789 }),
790 ),
791 };
792 }),
793 blob: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetBlob>, "params">) =>
794 Effect.gen(function* () {
795 const entry = yield* resolveOrNotFound(params.owner, params.repo);
796 const data = yield* repos
797 .getByName(entry.repoId)
798 .readObject({ oid: params.oid, expect: "blob" })
799 .pipe(
800 Effect.catchTags({
801 StoreError: (error) => Effect.die(error),
802 RepoNotFound: () =>
803 Effect.fail(
804 RepoNotFound.make({
805 owner: params.owner,
806 repo: params.repo,
807 }),
808 ),
809 }),
810 );
811 if (data.size > MAX_JSON_BLOB_BYTES) {
812 return yield* ObjectTooLarge.make({
813 oid: params.oid,
814 size: data.size,
815 });
816 }
817 return {
818 oid: params.oid,
819 size: data.size,
820 encoding: "base64" as const,
821 content: Base64.encode(data.content),
822 };
823 }),
824 diff: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetDiff>, "params">) =>
825 Effect.gen(function* () {
826 const entry = yield* resolveOrNotFound(params.owner, params.repo);
827 const data = yield* repos
828 .getByName(entry.repoId)
829 .readCommitDiff({ oid: params.oid })
830 .pipe(
831 Effect.catchTags({
832 StoreError: (error) => Effect.die(error),
833 RepoNotFound: () =>
834 Effect.fail(
835 RepoNotFound.make({
836 owner: params.owner,
837 repo: params.repo,
838 }),
839 ),
840 }),
841 );
842 return CommitDiff.make({
843 oid: params.oid,
844 parent: data.parent === null ? null : asOid(data.parent),
845 files: data.files.map(toDiffEntry),
846 truncated: data.truncated,
847 });
848 }),
849 compare: ({
850 params,
851 query,
852 }: Pick<HttpApiEndpoint.Request<typeof Compare>, "params" | "query">) =>
853 Effect.gen(function* () {
854 const entry = yield* resolveOrNotFound(params.owner, params.repo);
855 const data = yield* repos
856 .getByName(entry.repoId)
857 .compareCommits({ base: query.base, head: query.head })
858 .pipe(
859 Effect.catchTags({
860 StoreError: (error) => Effect.die(error),
861 RepoNotFound: () =>
862 Effect.fail(
863 RepoNotFound.make({
864 owner: params.owner,
865 repo: params.repo,
866 }),
867 ),
868 }),
869 );
870 return Comparison.make({
871 base: asOid(data.base),
872 head: asOid(data.head),
873 mergeBase: asOid(data.mergeBase),
874 aheadBy: data.aheadBy,
875 behindBy: data.behindBy,
876 commits: data.commits.map(toCommitInfo),
877 commitsTruncated: data.commitsTruncated,
878 files: data.files.map(toDiffEntry),
879 filesTruncated: data.filesTruncated,
880 });
881 }),
882 };
883
884 const pullsRoutes = {
885 create: ({
886 params,
887 payload,
888 }: Pick<HttpApiEndpoint.Request<typeof CreatePull>, "params" | "payload">) =>
889 Effect.gen(function* () {
890 const entry = yield* resolveOrNotFound(params.owner, params.repo);
891 const pull = yield* repos
892 .getByName(entry.repoId)
893 .createPull({
894 title: payload.title,
895 body: payload.body,
896 base: payload.base,
897 head: payload.head,
898 })
899 .pipe(
900 Effect.catchTags({
901 StoreError: (error) => Effect.die(error),
902 RepoNotFound: () =>
903 Effect.fail(
904 RepoNotFound.make({
905 owner: params.owner,
906 repo: params.repo,
907 }),
908 ),
909 }),
910 );
911 return toPull(pull);
912 }),
913 list: ({
914 params,
915 query,
916 }: Pick<HttpApiEndpoint.Request<typeof ListPulls>, "params" | "query">) =>
917 Effect.gen(function* () {
918 const entry = yield* resolveOrNotFound(params.owner, params.repo);
919 const page = yield* repos
920 .getByName(entry.repoId)
921 .listPulls({
922 state: query.state,
923 cursor: query.cursor,
924 limit: query.limit,
925 })
926 .pipe(
927 Effect.catchTags({
928 StoreError: (error) => Effect.die(error),
929 RepoNotFound: () =>
930 Effect.fail(
931 RepoNotFound.make({
932 owner: params.owner,
933 repo: params.repo,
934 }),
935 ),
936 }),
937 );
938 return {
939 items: page.items.map(toPull),
940 nextCursor: page.nextCursor,
941 hasMore: page.hasMore,
942 };
943 }),
944 get: ({ params }: Pick<HttpApiEndpoint.Request<typeof GetPull>, "params">) =>
945 Effect.gen(function* () {
946 const entry = yield* resolveOrNotFound(params.owner, params.repo);
947 const detail = yield* repos
948 .getByName(entry.repoId)
949 .getPull(params.number)
950 .pipe(
951 Effect.catchTags({
952 StoreError: (error) => Effect.die(error),
953 RepoNotFound: () =>
954 Effect.fail(
955 RepoNotFound.make({
956 owner: params.owner,
957 repo: params.repo,
958 }),
959 ),
960 }),
961 );
962 return toPullDetail(detail);
963 }),
964 update: ({
965 params,
966 payload,
967 }: Pick<HttpApiEndpoint.Request<typeof UpdatePull>, "params" | "payload">) =>
968 Effect.gen(function* () {
969 const entry = yield* resolveOrNotFound(params.owner, params.repo);
970 const pull = yield* repos
971 .getByName(entry.repoId)
972 .updatePull({
973 number: params.number,
974 title: payload.title,
975 body: payload.body,
976 state: payload.state,
977 })
978 .pipe(
979 Effect.catchTags({
980 StoreError: (error) => Effect.die(error),
981 RepoNotFound: () =>
982 Effect.fail(
983 RepoNotFound.make({
984 owner: params.owner,
985 repo: params.repo,
986 }),
987 ),
988 }),
989 );
990 return toPull(pull);
991 }),
992 merge: ({
993 params,
994 payload,
995 }: Pick<HttpApiEndpoint.Request<typeof MergePull>, "params" | "payload">) =>
996 Effect.gen(function* () {
997 const entry = yield* resolveOrNotFound(params.owner, params.repo);
998 const stub = repos.getByName(entry.repoId);
999 const result = yield* stub
1000 .mergePull({
1001 number: params.number,
1002 message: payload.message,
1003 expectedHeadOid: payload.expectedHeadOid,
1004 })
1005 .pipe(
1006 Effect.catchTags({
1007 StoreError: (error) => Effect.die(error),
1008 RepoNotFound: () =>
1009 Effect.fail(
1010 RepoNotFound.make({
1011 owner: params.owner,
1012 repo: params.repo,
1013 }),
1014 ),
1015 }),
1016 );
1017 return MergeResult.make({
1018 method: result.method,
1019 oid: asOid(result.oid),
1020 pull: toPull(result.pull),
1021 });
1022 }),
1023 };
1024
1025 return {
1026 repos: reposRoutes,
1027 refs: refsRoutes,
1028 objects: objectsRoutes,
1029 pulls: pullsRoutes,
1030 resolveCached,
1031 };
1032 });
1033 /** @internal Shared operations/cache used by the engine and default HTTP adapters. */
1034 export class Operations extends Context.Service<
1035 Operations,
1036 Effect.Success<typeof makeOperations>
1037 >()("alchemy/Git/Operations") {}
1038 export const OperationsLive = Layer.effect(Operations, makeOperations);