Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Deferred from "effect/Deferred";
4import * as Fiber from "effect/Fiber";
5import { Deadline } from "../vendor/vite-plus-remote-cache-cloudflare/src/streams.ts";
6import * as Layer from "effect/Layer";
7import * as Logger from "effect/Logger";
8import { vi } from "vite-plus/test";
9import { Observations } from "../vendor/vite-plus-remote-cache-cloudflare/src/observations.ts";
10import * as Admission from "./Admission.ts";
11import * as Cache from "./Cache.ts";
12import * as Savings from "./Savings.ts";
13
14vi.mock("../vendor/vite-plus-remote-cache-cloudflare/src/database.ts", () => ({
15 getScope: async () => ({}),
16 selectBlob: async () => ({ blob_object: "artifact", blob_size: 4 }),
17 cleanup: async () => {},
18}));
19
20it.effect("includes successful blob downloads in exported R2 usage", () =>
21 Effect.gen(function* () {
22 const get = vi.fn(async () => ({ size: 4, body: new Blob(["data"]).stream() }));
23 const bindings = {
24 developerKeys: JSON.stringify({
25 julius: "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
26 }),
27 ARTIFACTS: { get },
28 readLimit: { limit: async () => ({ success: true }) },
29 } as unknown as Cache.Bindings["Service"];
30 using observations = vi.spyOn(Observations.prototype, "toJSON");
31 const response = yield* Effect.gen(function* () {
32 const cache = yield* Cache.Cache;
33 return yield* cache.handle(
34 new Request(
35 "https://cache.example/projects/t3code/blob/12345678-1234-1234-1234-123456789abc",
36 {
37 headers: {
38 authorization: `Basic ${btoa("julius:fixture-token-012345678901234567890123456789")}`,
39 },
40 },
41 ),
42 { waitUntil: () => {} },
43 );
44 }).pipe(
45 Effect.provide(
46 Cache.layer.pipe(
47 Layer.provide([
48 Layer.succeed(Cache.Bindings, bindings),
49 Admission.layer,
50 Layer.succeed(Savings.Savings, {
51 record: () => Effect.void,
52 emitTotals: () => Effect.void,
53 cleanup: Effect.void,
54 }),
55 ]),
56 ),
57 ),
58 );
59 expect(response.status).toBe(200);
60 expect(yield* Effect.promise(() => response.text())).toBe("data");
61 expect(get).toHaveBeenCalledWith("artifact");
62 expect(observations.mock.results.at(-1)?.value.r2_operations).toBe(1);
63 }),
64);
65
66it.effect("returns 503 immediately when authenticated requests fill all read permits", () =>
67 Effect.gen(function* () {
68 const entered = yield* Deferred.make<void>();
69 const logs: unknown[] = [];
70 const get = vi.fn(() => {
71 if (get.mock.calls.length === 4) Deferred.doneUnsafe(entered, Effect.void);
72 return new Promise(() => {});
73 });
74 const bindings = {
75 developerKeys: JSON.stringify({
76 julius: "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
77 }),
78 ARTIFACTS: { get },
79 readLimit: { limit: async () => ({ success: true }) },
80 } as unknown as Cache.Bindings["Service"];
81 yield* Effect.gen(function* () {
82 const cache = yield* Cache.Cache;
83 const request = () =>
84 cache.handle(
85 new Request(
86 "https://cache.example/projects/t3code/blob/12345678-1234-1234-1234-123456789abc",
87 {
88 headers: {
89 authorization: `Basic ${btoa("julius:fixture-token-012345678901234567890123456789")}`,
90 },
91 },
92 ),
93 { waitUntil: () => {} },
94 );
95 const pending = yield* Effect.all(
96 Array.from({ length: 4 }, () => request().pipe(Effect.forkChild)),
97 );
98 yield* Deferred.await(entered);
99 const response = yield* request();
100 expect(response.status).toBe(503);
101 expect(yield* Effect.promise(() => response.text())).toBe(
102 "Service unavailable (concurrency_limit)",
103 );
104 expect(logs).toContainEqual(["Cache request failed", { reason: "concurrency_limit" }]);
105 expect(get).toHaveBeenCalledTimes(4);
106 yield* Effect.forEach(pending, Fiber.interrupt);
107 }).pipe(
108 Effect.provide([
109 Cache.layer.pipe(
110 Layer.provide([
111 Layer.succeed(Cache.Bindings, bindings),
112 Admission.layer,
113 Layer.succeed(Savings.Savings, {
114 record: () => Effect.void,
115 emitTotals: () => Effect.void,
116 cleanup: Effect.void,
117 }),
118 ]),
119 ),
120 Logger.layer([Logger.make(({ message }) => logs.push(message))], {
121 mergeWithExisting: false,
122 }),
123 ]),
124 );
125 }),
126);
127
128it.effect("aborts the upstream deadline before disposing it on interruption", () =>
129 Effect.gen(function* () {
130 const entered = yield* Deferred.make<void>();
131 const cancelled: boolean[] = [];
132 const originalDispose = Deadline.prototype.dispose;
133 using _dispose = vi.spyOn(Deadline.prototype, "dispose").mockImplementation(function (
134 this: Deadline,
135 ) {
136 try {
137 this.check();
138 cancelled.push(false);
139 } catch {
140 cancelled.push(true);
141 }
142 originalDispose.call(this);
143 });
144 const bindings = {
145 developerKeys: JSON.stringify({
146 julius: "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
147 }),
148 ARTIFACTS: {
149 get: () => {
150 Deferred.doneUnsafe(entered, Effect.void);
151 return new Promise(() => {});
152 },
153 },
154 readLimit: { limit: async () => ({ success: true }) },
155 } as unknown as Cache.Bindings["Service"];
156 yield* Effect.gen(function* () {
157 const cache = yield* Cache.Cache;
158 const fiber = yield* cache
159 .handle(
160 new Request(
161 "https://cache.example/projects/t3code/blob/12345678-1234-1234-1234-123456789abc",
162 {
163 headers: {
164 authorization: `Basic ${btoa("julius:fixture-token-012345678901234567890123456789")}`,
165 },
166 },
167 ),
168 { waitUntil: () => {} },
169 )
170 .pipe(Effect.forkChild);
171 yield* Deferred.await(entered);
172 yield* Fiber.interrupt(fiber);
173 expect(cancelled).toEqual([true]);
174 }).pipe(
175 Effect.provide(
176 Cache.layer.pipe(
177 Layer.provide([
178 Layer.succeed(Cache.Bindings, bindings),
179 Admission.layer,
180 Layer.succeed(Savings.Savings, {
181 record: () => Effect.void,
182 emitTotals: () => Effect.void,
183 cleanup: Effect.void,
184 }),
185 ]),
186 ),
187 ),
188 );
189 }),
190);
191
192it.effect("does not charge authenticated budgets for anonymous or malformed requests", () => {
193 const limit = vi.fn(async (_options: { key: string }) => ({ success: true }));
194 return Effect.gen(function* () {
195 const cache = yield* Cache.Cache;
196 for (const operation of [
197 "fetch",
198 "store",
199 "telemetry",
200 "blob/12345678-1234-1234-1234-123456789abc",
201 ]) {
202 for (const method of ["GET", "POST"]) {
203 yield* cache.handle(
204 new Request(`https://cache.example/projects/t3code/${operation}`, { method }),
205 { waitUntil: () => {} },
206 );
207 }
208 }
209 expect(limit).not.toHaveBeenCalled();
210 const headers = {
211 authorization: `Basic ${btoa("julius:fixture-token-012345678901234567890123456789")}`,
212 };
213 yield* cache.handle(
214 new Request("https://cache.example/projects/t3code/telemetry", {
215 method: "POST",
216 headers,
217 body: "{}",
218 }),
219 { waitUntil: () => {} },
220 );
221 yield* cache.handle(
222 new Request(
223 "https://cache.example/projects/t3code/blob/12345678-1234-1234-1234-123456789abc",
224 { headers },
225 ),
226 { waitUntil: () => {} },
227 );
228 expect(limit.mock.calls).toEqual([[{ key: "t3code:telemetry" }], [{ key: "t3code:blob" }]]);
229 }).pipe(
230 Effect.provide(
231 Cache.layer.pipe(
232 Layer.provide([
233 Layer.succeed(Cache.Bindings, {
234 developerKeys: JSON.stringify({
235 julius: "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
236 }),
237 readerKeys: "{}",
238 readLimit: { limit },
239 storeLimit: { limit },
240 ARTIFACTS: { get: async () => ({ size: 4, body: new Blob(["data"]).stream() }) },
241 } as unknown as Cache.Bindings["Service"]),
242 Admission.layer,
243 Layer.succeed(Savings.Savings, {
244 record: () => Effect.void,
245 emitTotals: () => Effect.void,
246 cleanup: Effect.void,
247 }),
248 ]),
249 ),
250 ),
251 );
252});
253
254it.effect("authenticates setup probes without recording empty savings", () => {
255 const record = vi.fn(() => Effect.void);
256 const emitTotals = vi.fn(() => Effect.void);
257 return Effect.gen(function* () {
258 const cache = yield* Cache.Cache;
259 const response = yield* cache.handle(
260 new Request("https://cache.example/projects/t3code/telemetry", {
261 method: "POST",
262 headers: {
263 authorization: `Basic ${btoa("julius:fixture-token-012345678901234567890123456789")}`,
264 },
265 body: JSON.stringify({
266 id: "a".repeat(64),
267 recordedAt: 0,
268 host: "setup-host",
269 platform: "linux",
270 arch: "x64",
271 ci: false,
272 runId: "setup",
273 tasks: [],
274 }),
275 }),
276 { waitUntil: () => {} },
277 );
278 expect(response.status).toBe(204);
279 expect(record).not.toHaveBeenCalled();
280 expect(emitTotals).not.toHaveBeenCalled();
281 }).pipe(
282 Effect.provide(
283 Cache.layer.pipe(
284 Layer.provide([
285 Layer.succeed(Cache.Bindings, {
286 developerKeys: JSON.stringify({
287 julius: "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
288 }),
289 readLimit: { limit: async () => ({ success: true }) },
290 } as unknown as Cache.Bindings["Service"]),
291 Admission.layer,
292 Layer.succeed(Savings.Savings, { record, emitTotals, cleanup: Effect.void }),
293 ]),
294 ),
295 ),
296 );
297});
298
299it.effect("keeps artifacts private and limits CI reader credentials to reads", () =>
300 Effect.gen(function* () {
301 const cache = yield* Cache.Cache;
302 const context = { waitUntil: () => {} };
303 const blob = "https://cache.example/projects/t3code/blob/12345678-1234-1234-1234-123456789abc";
304 for (const url of [blob, "https://cache.example/projects/t3code/fetch"]) {
305 const method = url === blob ? "GET" : "POST";
306 expect((yield* cache.handle(new Request(url, { method }), context)).status).toBe(401);
307 expect(
308 (yield* cache.handle(
309 new Request(url, {
310 method,
311 headers: { authorization: `Basic ${btoa("ci-reader:wrong")}` },
312 }),
313 context,
314 )).status,
315 ).toBe(403);
316 }
317 const headers = {
318 authorization: `Basic ${btoa("ci-reader:fixture-token-012345678901234567890123456789")}`,
319 };
320 expect((yield* cache.handle(new Request(blob, { headers }), context)).status).toBe(200);
321 expect(
322 (yield* cache.handle(
323 new Request("https://cache.example/projects/t3code/store", { method: "POST", headers }),
324 context,
325 )).status,
326 ).toBe(403);
327 }).pipe(
328 Effect.provide(
329 Cache.layer.pipe(
330 Layer.provide([
331 Layer.succeed(Cache.Bindings, {
332 developerKeys: "{}",
333 readerKeys: JSON.stringify({
334 "ci-reader": "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984",
335 }),
336 ARTIFACTS: { get: vi.fn(async () => ({ size: 4, body: new Blob(["data"]).stream() })) },
337 readLimit: { limit: async () => ({ success: true }) },
338 storeLimit: { limit: async () => ({ success: true }) },
339 } as unknown as Cache.Bindings["Service"]),
340 Admission.layer,
341 Layer.succeed(Savings.Savings, {
342 record: () => Effect.void,
343 emitTotals: () => Effect.void,
344 cleanup: Effect.void,
345 }),
346 ]),
347 ),
348 ),
349 ),
350);
351
352it.effect("rejects anonymous and invalid Basic requests before admission", () =>
353 Effect.gen(function* () {
354 const cache = yield* Cache.Cache;
355 for (const operation of ["store", "telemetry", "fetch"]) {
356 for (const authorization of [undefined, `Basic ${btoa("attacker:invalid")}`]) {
357 const response = yield* cache.handle(
358 new Request(`https://cache.example/projects/t3code/${operation}`, {
359 method: "POST",
360 headers: authorization ? { authorization } : {},
361 }),
362 { waitUntil: () => {} },
363 );
364 expect(response.status).toBe(authorization ? 403 : 401);
365 }
366 }
367 }).pipe(
368 Effect.provide(
369 Cache.layer.pipe(
370 Layer.provide([
371 Layer.succeed(Cache.Bindings, {
372 developerKeys: "{}",
373 readerKeys: "{}",
374 } as Cache.Bindings["Service"]),
375 Layer.succeed(Admission.Admission, {
376 withPermit: () => Effect.die("Unauthenticated request reached admission"),
377 }),
378 Layer.succeed(Savings.Savings, {
379 record: () => Effect.void,
380 emitTotals: () => Effect.void,
381 cleanup: Effect.void,
382 }),
383 ]),
384 ),
385 ),
386 ),
387);