The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as r2 from "@distilled.cloud/cloudflare/r2"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import * as Stream from "effect/Stream"; |
| 5 | import { authorizeWith } from "../HttpClientUtils.ts"; |
| 6 | import { |
| 7 | baseObject, |
| 8 | makeHttpBucketBinding, |
| 9 | makeR2HttpScope, |
| 10 | toR2Error, |
| 11 | type HttpMetadata, |
| 12 | type R2Auth, |
| 13 | } from "./BucketHttp.ts"; |
| 14 | import { R2Error, type GetOptions, type ListOptions, type Objects } from "./BucketTypes.ts"; |
| 15 | import { ReadBucket, type ReadBucketClient } from "./ReadBucket.ts"; |
| 16 | |
| 17 | /** |
| 18 | * HTTP-backed implementation of the {@link ReadBucket} binding. |
| 19 | * |
| 20 | * It creates a scoped {@link AccountApiToken} with the `Workers R2 Storage Read` and `Workers R2 Storage Write` permissions. |
| 21 | */ |
| 22 | export const ReadBucketHttp = Layer.effect( |
| 23 | ReadBucket, |
| 24 | Effect.suspend(() => |
| 25 | makeHttpBucketBinding({ |
| 26 | permissionGroups: ["Workers R2 Storage Read"], |
| 27 | makeClient: (token, bucketName, jurisdiction) => |
| 28 | makeReadR2HttpClient( |
| 29 | { authorize: authorizeWith(token), accountId: token.accountId }, |
| 30 | bucketName, |
| 31 | jurisdiction, |
| 32 | ), |
| 33 | }), |
| 34 | ), |
| 35 | ); |
| 36 | |
| 37 | export const makeReadR2HttpClient = ( |
| 38 | auth: R2Auth, |
| 39 | bucketName: Effect.Effect<string>, |
| 40 | jurisdiction: Effect.Effect<string>, |
| 41 | ): ReadBucketClient => { |
| 42 | const authorize = auth.authorize; |
| 43 | const scope = makeR2HttpScope(auth.accountId, bucketName, jurisdiction); |
| 44 | |
| 45 | return { |
| 46 | raw: Effect.die( |
| 47 | new R2Error({ |
| 48 | message: |
| 49 | "R2BucketBindingHttp does not expose a native `raw` Bucket; use the binary HTTP methods instead.", |
| 50 | cause: new Error("unsupported"), |
| 51 | }), |
| 52 | ), |
| 53 | head: (key: string) => |
| 54 | scope.pipe( |
| 55 | Effect.flatMap(({ accountId, bucketName, cfR2Jurisdiction }) => |
| 56 | authorize( |
| 57 | r2.getObject({ |
| 58 | accountId, |
| 59 | bucketName, |
| 60 | objectName: key, |
| 61 | cfR2Jurisdiction, |
| 62 | }), |
| 63 | ), |
| 64 | ), |
| 65 | // The HTTP body is lazy, so reading headers does not download it. |
| 66 | Effect.map((res) => |
| 67 | baseObject(key, httpMetadataOf(res), { |
| 68 | size: res.contentLength, |
| 69 | etag: res.etag, |
| 70 | uploaded: res.lastModified ? new Date(res.lastModified) : undefined, |
| 71 | storageClass: res.cfR2StorageClass, |
| 72 | }), |
| 73 | ), |
| 74 | // Native R2 `head` resolves to `null` for a missing object rather |
| 75 | // than failing — mirror that for the HTTP-backed client. |
| 76 | Effect.catchTag("NoSuchKey", () => Effect.succeed(null)), |
| 77 | Effect.mapError(toR2Error), |
| 78 | ), |
| 79 | get: ((key: string, _options?: GetOptions) => |
| 80 | scope.pipe( |
| 81 | Effect.flatMap(({ accountId, bucketName, cfR2Jurisdiction }) => |
| 82 | authorize( |
| 83 | r2.getObject({ |
| 84 | accountId, |
| 85 | bucketName, |
| 86 | objectName: key, |
| 87 | cfR2Jurisdiction, |
| 88 | }), |
| 89 | ), |
| 90 | ), |
| 91 | Effect.map((res) => objectBodyFromResponse(key, res)), |
| 92 | // Native R2 `get` resolves to `null` for a missing object. |
| 93 | Effect.catchTag("NoSuchKey", () => Effect.succeed(null)), |
| 94 | Effect.mapError(toR2Error), |
| 95 | )) as any, |
| 96 | list: (options?: ListOptions) => |
| 97 | scope.pipe( |
| 98 | Effect.flatMap(({ accountId, bucketName, cfR2Jurisdiction }) => |
| 99 | authorize( |
| 100 | r2.listObjects({ |
| 101 | accountId, |
| 102 | bucketName, |
| 103 | cfR2Jurisdiction, |
| 104 | prefix: options?.prefix, |
| 105 | delimiter: options?.delimiter, |
| 106 | cursor: options?.cursor, |
| 107 | startAfter: options?.startAfter, |
| 108 | perPage: options?.limit, |
| 109 | }), |
| 110 | ), |
| 111 | ), |
| 112 | Effect.mapError(toR2Error), |
| 113 | Effect.map((res) => { |
| 114 | const objects = res.result.map((o) => |
| 115 | baseObject( |
| 116 | o.key ?? "", |
| 117 | {}, |
| 118 | { |
| 119 | size: o.size ?? undefined, |
| 120 | etag: o.etag ?? undefined, |
| 121 | uploaded: o.lastModified ? new Date(o.lastModified) : undefined, |
| 122 | storageClass: o.storageClass ?? undefined, |
| 123 | customMetadata: (o.customMetadata as Record<string, string> | null) ?? undefined, |
| 124 | }, |
| 125 | ), |
| 126 | ); |
| 127 | const cursor = res.resultInfo?.cursor ?? undefined; |
| 128 | return ( |
| 129 | cursor |
| 130 | ? { objects, delimitedPrefixes: [], truncated: true, cursor } |
| 131 | : { objects, delimitedPrefixes: [], truncated: false } |
| 132 | ) as Objects; |
| 133 | }), |
| 134 | ), |
| 135 | }; |
| 136 | }; |
| 137 | |
| 138 | const objectBodyFromResponse = (key: string, res: r2.GetObjectResponse): R2ObjectBody => { |
| 139 | const meta = httpMetadataOf(res); |
| 140 | // The HTTP body is a single-consumption stream — expose it both as a Stream |
| 141 | // and via the buffering accessors, but the caller may only read it once. |
| 142 | let response: Response | undefined; |
| 143 | const getResponse = () => (response ??= new Response(Stream.toReadableStream(res.body) as any)); |
| 144 | const consume = <T>(fn: (r: Response) => Promise<T>): Effect.Effect<T, R2Error> => |
| 145 | Effect.tryPromise({ try: () => fn(getResponse()), catch: toR2Error }); |
| 146 | return { |
| 147 | ...baseObject(key, meta, { |
| 148 | size: res.contentLength, |
| 149 | etag: res.etag, |
| 150 | uploaded: res.lastModified ? new Date(res.lastModified) : undefined, |
| 151 | storageClass: res.cfR2StorageClass, |
| 152 | }), |
| 153 | body: Stream.fromReadableStream({ |
| 154 | evaluate: () => getResponse().body as ReadableStream<Uint8Array>, |
| 155 | onError: toR2Error, |
| 156 | }), |
| 157 | bodyUsed: false, |
| 158 | arrayBuffer: () => consume((r) => r.arrayBuffer()), |
| 159 | bytes: () => consume((r) => r.arrayBuffer().then((b) => new Uint8Array(b))), |
| 160 | text: () => consume((r) => r.text()), |
| 161 | json: <T>() => consume((r) => r.json() as Promise<T>), |
| 162 | blob: () => consume((r) => r.blob()), |
| 163 | } as unknown as R2ObjectBody; |
| 164 | }; |
| 165 | |
| 166 | const httpMetadataOf = (res: r2.GetObjectResponse): HttpMetadata => ({ |
| 167 | contentType: res.contentType, |
| 168 | contentEncoding: res.contentEncoding, |
| 169 | contentDisposition: res.contentDisposition, |
| 170 | contentLanguage: res.contentLanguage, |
| 171 | cacheControl: res.cacheControl, |
| 172 | cacheExpiry: res.expires ? new Date(res.expires) : undefined, |
| 173 | }); |