Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Cache.ts

241 lines9.8 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Clock from "effect/Clock";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import type * as Cloudflare from "@cloudflare/workers-types";
7import { Summary, recordSummary } from "./Summary.ts";
8import * as Savings from "./Savings.ts";
9import type { ProtocolBindings } from "./protocolTypes.ts";
10import * as Admission from "./Admission.ts";
11import { developerIdentity } from "./developerAuth.ts";
12​
13const decodeSummary = Schema.decodeEffect(Schema.fromJsonString(Summary));
14​
15export class CacheError extends Schema.TaggedError<CacheError>()("CacheError", {
16 status: Schema.Number,
17 reason: Schema.String,
18}) {}
19​
20export class Bindings extends Context.Service<
21 Bindings,
22 ProtocolBindings & {
23 readonly developerKeys: string;
24 readonly readerKeys: string;
25 readonly readLimit: Cloudflare.RateLimit;
26 readonly storeLimit: Cloudflare.RateLimit;
27 }
28>()("@t3tools/task-cache/Cache/Bindings") {}
29​
30export class Cache extends Context.Service<
31 Cache,
32 {
33 readonly handle: (
34 request: Request,
35 context: Pick<Cloudflare.ExecutionContext, "waitUntil">,
36 ) => Effect.Effect<Response>;
37 readonly cleanup: Effect.Effect<void, CacheError>;
38 }
39>()("@t3tools/task-cache/Cache") {}
40​
41const make = Effect.gen(function* () {
42 const bindings = yield* Bindings;
43 const admission = yield* Admission.Admission;
44 const savings = yield* Savings.Savings;
45 // The source-only protocol dependency is bundled for Workers, never evaluated by Node during deployment.
46 const {
47 authorizeCacheWrite,
48 authorizeTelemetry,
49 keys,
50 cleanup,
51 getScope,
52 selectBlob,
53 errorResponse,
54 HttpError,
55 fetchMetadata,
56 defaults,
57 store,
58 readBody,
59 Deadline,
60 Observations,
61 } = yield* Effect.promise(() => import("./protocol.ts"));
62​
63 // The upstream adapter owns the experimental wire format and atomic D1 publication.
64 const protocol = <A>(run: (signal: AbortSignal) => Promise<A>) =>
65 Effect.tryPromise({
66 try: run,
67 catch: (cause) =>
68 new CacheError({
69 status: cause instanceof HttpError ? cause.status : 503,
70 reason: cause instanceof HttpError ? cause.code : "unavailable",
71 }),
72 });
73​
74 const checkLimit = Effect.fn("TaskCache.checkLimit")(function* (operation: string) {
75 const allowed = yield* protocol(() =>
76 (operation === "store" ? bindings.storeLimit : bindings.readLimit).limit({
77 key: `t3code:${operation.startsWith("blob/") ? "blob" : operation}`,
78 }),
79 );
80 if (!allowed.success) return yield* new CacheError({ status: 429, reason: "rate_limit" });
81 });
82​
83 const handle = Effect.fn("TaskCache.handle")(
84 function* (request: Request, context: Pick<Cloudflare.ExecutionContext, "waitUntil">) {
85 const url = new URL(request.url);
86 const route = /^\/projects\/t3code\/(fetch|store|telemetry|blob\/([0-9a-f-]{36}))$/.exec(
87 url.pathname,
88 );
89 const operation = route?.[1] ?? "unknown";
90 const writing = operation === "store";
91 yield* Effect.annotateCurrentSpan({
92 "cache.operation": operation.startsWith("blob/") ? "blob" : operation,
93 });
94 if (
95 !route ||
96 url.search ||
97 request.method !== (operation.startsWith("blob/") ? "GET" : "POST")
98 ) {
99 return yield* new CacheError({ status: 404, reason: "unknown_route" });
100 }
101 if (!request.headers.has("authorization"))
102 return yield* new CacheError({ status: 401, reason: "missing_identity" });
103 const developer = yield* developerIdentity(request, bindings.developerKeys);
104 if (writing || operation === "telemetry") {
105 if (developer === null)
106 return yield* new CacheError({ status: 403, reason: "invalid_identity" });
107 } else {
108 const reader = developer ?? (yield* developerIdentity(request, bindings.readerKeys));
109 if (typeof reader !== "string")
110 return yield* new CacheError({ status: 403, reason: "read_denied" });
111 }
112 return yield* admission
113 .withPermit(
114 writing,
115 Effect.scoped(
116 Effect.gen(function* () {
117 const controller = yield* Effect.acquireRelease(
118 Effect.sync(() => new AbortController()),
119 (value) => Effect.sync(() => value.abort()),
120 );
121 const deadline = yield* Effect.acquireRelease(
122 Effect.sync(
123 () =>
124 new Deadline(
125 writing ? defaults.deadlineMs : 15000,
126 AbortSignal.any([request.signal, controller.signal]),
127 ),
128 ),
129 (value) =>
130 Effect.sync(() => {
131 controller.abort();
132 value.dispose();
133 }),
134 );
135 const stats = new Observations();
136 yield* Effect.addFinalizer(() =>
137 Effect.annotateCurrentSpan(
138 Object.fromEntries(
139 Object.entries(stats.toJSON()).map(([key, value]) => [`cache.${key}`, value]),
140 ),
141 ),
142 );
143 if (!writing && operation !== "telemetry") yield* checkLimit(operation);
144 const scope = yield* protocol(() => getScope(bindings.INDEX, "t3code", stats));
145 if (operation === "telemetry") {
146 let identity = developer ?? undefined;
147 if (identity === undefined) {
148 identity = yield* protocol(() => authorizeTelemetry(request, scope, keys));
149 }
150 yield* checkLimit(operation);
151 const bytes = yield* protocol(() => readBody(request.body, 256 * 1024, deadline));
152 const summary = yield* decodeSummary(new TextDecoder().decode(bytes)).pipe(
153 Effect.mapError(() => new CacheError({ status: 400, reason: "invalid_summary" })),
154 );
155 if (summary.tasks.length === 0) return new Response(null, { status: 204 });
156 const now = yield* Clock.currentTimeMillis;
157 if (summary.recordedAt > now + 60_000 || summary.recordedAt < now - 30 * 86400_000)
158 return yield* new CacheError({ status: 400, reason: "summary_expired" });
159 yield* savings
160 .record(summary, identity)
161 .pipe(
162 Effect.mapError(
163 () => new CacheError({ status: 503, reason: "telemetry_unavailable" }),
164 ),
165 );
166 yield* recordSummary(summary, identity);
167 yield* savings
168 .emitTotals(identity, summary.host)
169 .pipe(
170 Effect.mapError(
171 () => new CacheError({ status: 503, reason: "telemetry_unavailable" }),
172 ),
173 );
174 return new Response(null, { status: 204 });
175 }
176 if (writing) {
177 if (developer !== undefined && !scope.writes_enabled) {
178 return yield* new CacheError({ status: 403, reason: "developer_write_denied" });
179 }
180 const now = yield* Clock.currentTimeMillis;
181 const identity =
182 developer === undefined
183 ? yield* protocol(() => authorizeCacheWrite(request, scope, keys))
184 : {
185 exp: Math.floor(now / 1000) + 900,
186 repository_id: scope.repository_id,
187 workflow_ref: `developer/${developer}`,
188 };
189 yield* checkLimit(operation);
190 return yield* protocol(() =>
191 store(request, bindings, context, scope, identity, defaults, deadline, stats),
192 );
193 }
194 if (operation === "fetch") {
195 const result = yield* protocol(() =>
196 fetchMetadata(request, bindings, context, "t3code", defaults, deadline, stats),
197 );
198 return result.response;
199 }
200 const selected = yield* protocol(() =>
201 selectBlob(bindings.INDEX, "t3code", route[2]!, stats),
202 );
203 if (!selected) return yield* new CacheError({ status: 404, reason: "blob_missing" });
204 stats.r2_operations++;
205 const object = yield* protocol(() => bindings.ARTIFACTS.get(selected.blob_object));
206 if (!object) return yield* new CacheError({ status: 404, reason: "blob_missing" });
207 if (object.size !== selected.blob_size)
208 return yield* new CacheError({ status: 503, reason: "blob_size" });
209 return new Response(object.body, {
210 headers: {
211 "Content-Type": "application/octet-stream",
212 "Content-Length": String(object.size),
213 "Cache-Control": "no-store",
214 },
215 });
216 }),
217 ),
218 )
219 .pipe(
220 Effect.timeout(writing ? "2 minutes" : "15 seconds"),
221 Effect.catchTags({
222 AdmissionRejected: () =>
223 Effect.fail(new CacheError({ status: 503, reason: "concurrency_limit" })),
224 TimeoutError: () => Effect.fail(new CacheError({ status: 503, reason: "deadline" })),
225 }),
226 );
227 },
228 Effect.catchTags({
229 // The enclosing operation owns the span for this inline handler.
230 CacheError: Effect.fnUntraced(function* (error) {
231 if (error.status >= 500)
232 yield* Effect.logWarning("Cache request failed", { reason: error.reason });
233 return errorResponse(new HttpError(error.status, error.reason));
234 }),
235 }),
236 );
237​
238 return Cache.of({ handle, cleanup: protocol(() => cleanup(bindings)) });
239});
240​
241export const layer = Layer.effect(Cache, make);