|
| 1 | +import type * as Cloudflare from "@cloudflare/workers-types"; |
| 2 | +import * as Context from "effect/Context"; |
| 3 | +import * as Effect from "effect/Effect"; |
| 4 | +import * as Layer from "effect/Layer"; |
| 5 | +import * as Schema from "effect/Schema"; |
| 6 | +import { developerIdentity } from "./developerAuth.ts"; |
| 7 | + |
| 8 | +export const routePrefix = "/projects/t3code/native-clients/"; |
| 9 | + |
| 10 | +export class NativeClientsError extends Schema.TaggedError<NativeClientsError>()( |
| 11 | + "NativeClientsError", |
| 12 | + { status: Schema.Number, reason: Schema.String }, |
| 13 | +) {} |
| 14 | + |
| 15 | +export class Bindings extends Context.Service< |
| 16 | + Bindings, |
| 17 | + { |
| 18 | + readonly CLIENTS: Cloudflare.R2Bucket; |
| 19 | + readonly developerKeys: string; |
| 20 | + readonly readerKeys: string; |
| 21 | + readonly readLimit: Cloudflare.RateLimit; |
| 22 | + readonly storeLimit: Cloudflare.RateLimit; |
| 23 | + } |
| 24 | +>()("@t3tools/task-cache/NativeClients/Bindings") {} |
| 25 | + |
| 26 | +export class NativeClients extends Context.Service< |
| 27 | + NativeClients, |
| 28 | + { readonly handle: (request: Request) => Effect.Effect<Response> } |
| 29 | +>()("@t3tools/task-cache/NativeClients") {} |
| 30 | + |
| 31 | +const CompleteBody = Schema.fromJsonString( |
| 32 | + Schema.Struct({ |
| 33 | + parts: Schema.Array(Schema.Struct({ partNumber: Schema.Number, etag: Schema.String })).check( |
| 34 | + Schema.isMinLength(1), |
| 35 | + Schema.isMaxLength(64), |
| 36 | + ), |
| 37 | + }), |
| 38 | +); |
| 39 | +const decodeComplete = Schema.decodeUnknownEffect(CompleteBody); |
| 40 | + |
| 41 | +// <platform>/<variant>/<fingerprint>[/uploads[/<uploadId>[/<part>|/complete]]] |
| 42 | +const route = |
| 43 | + /^((?:ios|android)\/[a-z0-9_-]{1,32}\/[a-f0-9]{40,64})(?:\/uploads(?:\/([^/]{1,1024})(?:\/(complete|[1-9][0-9]?))?)?)?$/; |
| 44 | +const digestPattern = /^[a-f0-9]{64}$/; |
| 45 | + |
| 46 | +const make = Effect.gen(function* () { |
| 47 | + const bindings = yield* Bindings; |
| 48 | + |
| 49 | + const r2 = <A>(run: () => Promise<A>) => |
| 50 | + Effect.tryPromise({ |
| 51 | + try: run, |
| 52 | + catch: () => new NativeClientsError({ status: 503, reason: "storage_unavailable" }), |
| 53 | + }); |
| 54 | + |
| 55 | + const limit = Effect.fn("NativeClients.limit")(function* (writing: boolean) { |
| 56 | + const allowed = yield* r2(() => |
| 57 | + (writing ? bindings.storeLimit : bindings.readLimit).limit({ |
| 58 | + key: writing ? "t3code:native-store" : "t3code:native-read", |
| 59 | + }), |
| 60 | + ); |
| 61 | + if (!allowed.success) |
| 62 | + return yield* new NativeClientsError({ status: 429, reason: "rate_limit" }); |
| 63 | + }); |
| 64 | + |
| 65 | + const handle = Effect.fn("NativeClients.handle")( |
| 66 | + function* (request: Request) { |
| 67 | + const url = new URL(request.url); |
| 68 | + const match = route.exec(url.pathname.slice(routePrefix.length)); |
| 69 | + if (!match || url.search || !url.pathname.startsWith(routePrefix)) |
| 70 | + return yield* new NativeClientsError({ status: 404, reason: "unknown_route" }); |
| 71 | + const [, key, uploadId, part] = match as unknown as [ |
| 72 | + string, |
| 73 | + string, |
| 74 | + string | undefined, |
| 75 | + string | undefined, |
| 76 | + ]; |
| 77 | + const operation = |
| 78 | + uploadId === undefined |
| 79 | + ? url.pathname.endsWith("/uploads") |
| 80 | + ? "create" |
| 81 | + : "download" |
| 82 | + : part === undefined |
| 83 | + ? "abort" |
| 84 | + : part === "complete" |
| 85 | + ? "complete" |
| 86 | + : "part"; |
| 87 | + const method = { |
| 88 | + download: "GET", |
| 89 | + create: "POST", |
| 90 | + part: "PUT", |
| 91 | + complete: "POST", |
| 92 | + abort: "DELETE", |
| 93 | + }[operation]; |
| 94 | + yield* Effect.annotateCurrentSpan({ "native.operation": operation, "native.key": key }); |
| 95 | + if (request.method !== method) |
| 96 | + return yield* new NativeClientsError({ status: 405, reason: "method_not_allowed" }); |
| 97 | + if (!request.headers.has("authorization")) |
| 98 | + return yield* new NativeClientsError({ status: 401, reason: "missing_identity" }); |
| 99 | + |
| 100 | + const developer = yield* developerIdentity(request, bindings.developerKeys); |
| 101 | + const writing = operation !== "download"; |
| 102 | + if (writing) { |
| 103 | + if (typeof developer !== "string") |
| 104 | + return yield* new NativeClientsError({ status: 403, reason: "write_denied" }); |
| 105 | + } else if ( |
| 106 | + typeof developer !== "string" && |
| 107 | + typeof (yield* developerIdentity(request, bindings.readerKeys)) !== "string" |
| 108 | + ) { |
| 109 | + return yield* new NativeClientsError({ status: 403, reason: "read_denied" }); |
| 110 | + } |
| 111 | + yield* limit(writing); |
| 112 | + |
| 113 | + if (operation === "download") { |
| 114 | + const object = yield* r2(() => bindings.CLIENTS.get(key)); |
| 115 | + if (!object) return yield* new NativeClientsError({ status: 404, reason: "missing" }); |
| 116 | + return new Response(object.body as unknown as ReadableStream, { |
| 117 | + headers: { |
| 118 | + "Content-Type": "application/octet-stream", |
| 119 | + "Content-Length": String(object.size), |
| 120 | + "Cache-Control": "no-store", |
| 121 | + "X-T3-Digest": object.customMetadata?.digest ?? "", |
| 122 | + }, |
| 123 | + }); |
| 124 | + } |
| 125 | + if (operation === "create") { |
| 126 | + const digest = request.headers.get("x-t3-digest") ?? ""; |
| 127 | + if (!digestPattern.test(digest)) |
| 128 | + return yield* new NativeClientsError({ status: 400, reason: "invalid_digest" }); |
| 129 | + if (yield* r2(() => bindings.CLIENTS.head(key))) return Response.json({ exists: true }); |
| 130 | + const upload = yield* r2(() => |
| 131 | + bindings.CLIENTS.createMultipartUpload(key, { |
| 132 | + customMetadata: { digest, writer: developer! }, |
| 133 | + }), |
| 134 | + ); |
| 135 | + return Response.json({ uploadId: upload.uploadId }); |
| 136 | + } |
| 137 | + |
| 138 | + const upload = bindings.CLIENTS.resumeMultipartUpload(key, decodeURIComponent(uploadId!)); |
| 139 | + if (operation === "abort") { |
| 140 | + yield* r2(() => upload.abort()); |
| 141 | + return new Response(null, { status: 204 }); |
| 142 | + } |
| 143 | + if (operation === "part") { |
| 144 | + if (!request.body || !request.headers.has("content-length")) |
| 145 | + return yield* new NativeClientsError({ status: 411, reason: "length_required" }); |
| 146 | + const uploaded = yield* r2(() => |
| 147 | + upload.uploadPart(Number(part), request.body as unknown as Cloudflare.ReadableStream), |
| 148 | + ); |
| 149 | + return Response.json({ etag: uploaded.etag }); |
| 150 | + } |
| 151 | + const body = yield* decodeComplete( |
| 152 | + yield* r2(() => request.text().then((text) => text.slice(0, 64 * 1024))), |
| 153 | + ).pipe( |
| 154 | + Effect.mapError(() => new NativeClientsError({ status: 400, reason: "invalid_parts" })), |
| 155 | + ); |
| 156 | + yield* r2(() => upload.complete([...body.parts])); |
| 157 | + return new Response(null, { status: 204 }); |
| 158 | + }, |
| 159 | + Effect.catchTags({ |
| 160 | + NativeClientsError: (error) => |
| 161 | + Effect.gen(function* () { |
| 162 | + if (error.status >= 500) |
| 163 | + yield* Effect.logWarning("Native client request failed", { reason: error.reason }); |
| 164 | + return Response.json({ error: error.reason }, { status: error.status }); |
| 165 | + }), |
| 166 | + }), |
| 167 | + ); |
| 168 | + |
| 169 | + return NativeClients.of({ handle }); |
| 170 | +}); |
| 171 | + |
| 172 | +export const layer = Layer.effect(NativeClients, make); |
0 commit comments