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

main
ts 130 lines 4.81 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import type { R2Error, ReadWriteBucketClient } from "@alchemy.run/cloudflare/R2/index";
3 import type { RuntimeContext } from "alchemy/RuntimeContext";
4 /**
5 * `Git.BlobStoreR2` — Cloudflare R2 implementation of {@link BlobStore}
6 * (the default), over the `Cloudflare.R2.ReadWriteBucket` capability.
7 */
8 import * as Effect from "effect/Effect";
9 import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Stream from "effect/Stream";
12 import {
13 BlobStore,
14 BlobStoreError,
15 orderedParts,
16 type BlobBody,
17 type BlobMeta,
18 type BlobMultipart,
19 type BlobStoreShape,
20 } from "./BlobStore.ts";
21
22 const r2Error = (what: string) => (error: R2Error) =>
23 new BlobStoreError({ reason: `${what}: ${error.message}` });
24
25 /**
26 * Builds the R2-backed shape from an already-resolved bucket client.
27 * Used directly by the Repo DO (which resolves its own binding) and by
28 * the {@link BlobStoreR2} layer.
29 */
30 export const makeBlobStoreR2 = (bucket: ReadWriteBucketClient): BlobStoreShape => ({
31 get: (key, range) =>
32 bucket.get(key, range === undefined ? undefined : { range }).pipe(
33 Effect.mapError(r2Error(`get ${key}`)),
34 Effect.map((object) =>
35 object === null
36 ? null
37 : ({
38 size: object.size,
39 bytes: object.bytes().pipe(Effect.mapError(r2Error(`read ${key}`))),
40 stream: object.body.pipe(Stream.mapError(r2Error(`stream ${key}`))),
41 readable: object.readable,
42 } satisfies BlobBody),
43 ),
44 ),
45 put: (key, body, options) => {
46 // A stream body's own BlobStoreError joins R2's error union — map
47 // only the R2 side, pass ours through.
48 const write: Effect.Effect<unknown, R2Error | BlobStoreError, RuntimeContext> =
49 body instanceof Uint8Array
50 ? bucket.put(key, body)
51 : bucket.put(key, body, {
52 contentLength: options?.contentLength ?? 0,
53 });
54 return write.pipe(
55 Effect.mapError((error) =>
56 error instanceof BlobStoreError ? error : r2Error(`put ${key}`)(error),
57 ),
58 Effect.asVoid,
59 );
60 },
61 head: (key) =>
62 bucket.head(key).pipe(
63 Effect.mapError(r2Error(`head ${key}`)),
64 Effect.map((object) => (object === null ? null : { key, size: object.size })),
65 ),
66 multipart: (key) =>
67 bucket.createMultipartUpload(key).pipe(
68 Effect.mapError(r2Error(`multipart ${key}`)),
69 Effect.map((upload): BlobMultipart => ({
70 uploadId: upload.uploadId,
71 uploadPart: (partNumber, part) =>
72 upload
73 .uploadPart(partNumber, part)
74 .pipe(Effect.mapError(r2Error(`part ${partNumber} of ${key}`))),
75 complete: (parts) =>
76 upload
77 .complete(orderedParts(parts))
78 .pipe(Effect.mapError(r2Error(`complete ${key}`)), Effect.asVoid),
79 abort: upload.abort().pipe(Effect.mapError(r2Error(`abort ${key}`)), Effect.asVoid),
80 })),
81 ),
82 uploadPart: (key, uploadId, partNumber, part) =>
83 bucket.resumeMultipartUpload(key, uploadId).pipe(
84 Effect.flatMap((upload) => upload.uploadPart(partNumber, part)),
85 Effect.mapError(r2Error(`part ${partNumber} of ${key}`)),
86 ),
87 delete: (keys) =>
88 bucket
89 .delete(typeof keys === "string" ? keys : [...keys])
90 .pipe(Effect.mapError(r2Error("delete")), Effect.asVoid),
91 list: (prefix) =>
92 Stream.paginate(undefined as string | undefined, (cursor) =>
93 bucket.list({ prefix, limit: 1000, cursor }).pipe(
94 Effect.mapError(r2Error(`list ${prefix}`)),
95 Effect.map((page) => {
96 const metas = page.objects.map((object): BlobMeta => ({
97 key: object.key,
98 size: object.size,
99 }));
100 return [
101 metas,
102 page.truncated ? Option.some(page.cursor) : Option.none<string>(),
103 ] as const;
104 }),
105 ),
106 ),
107 });
108
109 /**
110 * R2-backed {@link BlobStore}: packs, bundles, oversize objects, and
111 * push spill live in the given bucket. Requires the
112 * `Cloudflare.R2.ReadWriteBucket` capability; provide an implementation
113 * (`Cloudflare.R2.ReadWriteBucketBinding` or `ReadWriteBucketHttp`) on the
114 * Worker.
115 *
116 * @layer
117 * @provides Git.BlobStore
118 */
119 export const BlobStoreR2 = (
120 bucket: Parameters<typeof Cloudflare.R2.ReadWriteBucket>[0],
121 ): Layer.Layer<BlobStore, never, Cloudflare.R2.ReadWriteBucket> =>
122 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- declaration-Effect requirement is resolved at stack eval, see comment at the cast below
123 Layer.effect(
124 BlobStore,
125 Effect.gen(function* () {
126 const client = yield* Cloudflare.R2.ReadWriteBucket(bucket);
127 return makeBlobStoreR2(client);
128 }),
129 // `bucket` may be a declaration Effect, which widens the inferred requirement.
130 ) as Layer.Layer<BlobStore, never, Cloudflare.R2.ReadWriteBucket>;