Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as NativeClients from "./NativeClients.ts";
5
6const tokenDigest = "210eb3d2c67a7207923e1999751300a87a2dd22839b258b80c3d805a6fe64984";
7const auth = (name: string) => ({
8 authorization: `Basic ${btoa(`${name}:fixture-token-012345678901234567890123456789`)}`,
9});
10const key = `ios/development/${"a".repeat(40)}`;
11const base = `https://cache.example${NativeClients.routePrefix}${key}`;
12
13function memoryBucket() {
14 const objects = new Map<string, { bytes: ArrayBuffer; customMetadata: Record<string, string> }>();
15 const uploads = new Map<
16 string,
17 { key: string; customMetadata: Record<string, string>; parts: Map<number, ArrayBuffer> }
18 >();
19 const resume = (objectKey: string, uploadId: string) => ({
20 uploadPart: async (partNumber: number, body: ReadableStream) => {
21 uploads.get(uploadId)!.parts.set(partNumber, await new Response(body).arrayBuffer());
22 return { partNumber, etag: `etag-${partNumber}` };
23 },
24 complete: async (parts: ReadonlyArray<{ partNumber: number }>) => {
25 const upload = uploads.get(uploadId)!;
26 const chunks = parts.map(({ partNumber }) => upload.parts.get(partNumber)!);
27 objects.set(objectKey, {
28 bytes: await new Blob(chunks).arrayBuffer(),
29 customMetadata: upload.customMetadata,
30 });
31 uploads.delete(uploadId);
32 },
33 abort: async () => void uploads.delete(uploadId),
34 });
35 return {
36 head: async (objectKey: string) => (objects.has(objectKey) ? {} : null),
37 get: async (objectKey: string) => {
38 const object = objects.get(objectKey);
39 return object
40 ? {
41 size: object.bytes.byteLength,
42 body: new Blob([object.bytes]).stream(),
43 customMetadata: object.customMetadata,
44 }
45 : null;
46 },
47 createMultipartUpload: async (
48 objectKey: string,
49 options: { customMetadata: Record<string, string> },
50 ) => {
51 const uploadId = `upload/${uploads.size}+`;
52 uploads.set(uploadId, {
53 key: objectKey,
54 customMetadata: options.customMetadata,
55 parts: new Map(),
56 });
57 return { uploadId };
58 },
59 resumeMultipartUpload: resume,
60 uploads,
61 };
62}
63
64const request = (path: string, init: RequestInit & { name: string }) =>
65 Effect.gen(function* () {
66 const native = yield* NativeClients.NativeClients;
67 return yield* native.handle(
68 new Request(`${base}${path}`, {
69 ...init,
70 headers: { ...auth(init.name), ...init.headers },
71 }),
72 );
73 });
74
75it.effect("serves a writer's multipart upload to readers with its digest", () => {
76 const bucket = memoryBucket();
77 const bindings = {
78 CLIENTS: bucket,
79 developerKeys: JSON.stringify({ julius: tokenDigest }),
80 readerKeys: JSON.stringify({ "ci-reader": tokenDigest }),
81 readLimit: { limit: async () => ({ success: true }) },
82 storeLimit: { limit: async () => ({ success: true }) },
83 } as unknown as NativeClients.Bindings["Service"];
84 const digest = "d".repeat(64);
85 return Effect.gen(function* () {
86 const denied = yield* request("/uploads", {
87 name: "ci-reader",
88 method: "POST",
89 headers: { "x-t3-digest": digest },
90 });
91 expect(denied.status).toBe(403);
92
93 const created = yield* request("/uploads", {
94 name: "julius",
95 method: "POST",
96 headers: { "x-t3-digest": digest, "x-t3-build-ms": "540000" },
97 });
98 const { uploadId } = (yield* Effect.promise(() => created.json())) as { uploadId: string };
99 const parts = [];
100 for (const [index, chunk] of ["native ", "client"].entries()) {
101 const response = yield* request(`/uploads/${encodeURIComponent(uploadId)}/${index + 1}`, {
102 name: "julius",
103 method: "PUT",
104 body: chunk,
105 headers: { "content-length": String(chunk.length) },
106 });
107 const { etag } = (yield* Effect.promise(() => response.json())) as { etag: string };
108 parts.push({ partNumber: index + 1, etag });
109 }
110 const completed = yield* request(`/uploads/${encodeURIComponent(uploadId)}/complete`, {
111 name: "julius",
112 method: "POST",
113 body: JSON.stringify({ parts }),
114 headers: { "content-length": String(JSON.stringify({ parts }).length) },
115 });
116 expect(completed.status).toBe(204);
117
118 const download = yield* request("", { name: "ci-reader", method: "GET" });
119 expect(download.status).toBe(200);
120 expect(download.headers.get("x-t3-digest")).toBe(digest);
121 expect(download.headers.get("x-t3-build-ms")).toBe("540000");
122 expect(download.headers.get("content-disposition")).toMatch(/filename="[a-f0-9]+\.tgz"$/);
123 expect(yield* Effect.promise(() => download.text())).toBe("native client");
124
125 const again = yield* request("/uploads", {
126 name: "julius",
127 method: "POST",
128 headers: { "x-t3-digest": digest },
129 });
130 expect(yield* Effect.promise(() => again.json())).toEqual({ exists: true });
131 expect(bucket.uploads.size).toBe(0);
132 }).pipe(
133 Effect.provide(
134 NativeClients.layer.pipe(Layer.provide(Layer.succeed(NativeClients.Bindings, bindings))),
135 ),
136 );
137});