1import { bucketAccessKeyLogicalId } from "@/Prisma/BucketBinding";
2import type { Bucket as PrismaBucket } from "@/Prisma/Bucket";
3import type { ReadBucketClient } from "@/Prisma/ReadBucket";
4import type { ReadWriteBucketClient } from "@/Prisma/ReadWriteBucket";
5import type { WriteBucketClient } from "@/Prisma/WriteBucket";
6import * as Prisma from "@/Prisma";
7import * as Test from "@/Test/Alchemy";
8import { describe, expect, it } from "alchemy-test";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import { MinimumLogLevel } from "effect/References";
12import * as Schedule from "effect/Schedule";
13import * as HttpClient from "effect/http/HttpClient";
14import * as HttpClientRequest from "effect/http/HttpClientRequest";
15import type * as HttpClientResponse from "effect/http/HttpClientResponse";
16import Stack from "./fixtures/stack.ts";
17
18type Equal<A, B> =
19 (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
20 ? true
21 : false;
22type Expect<T extends true> = T;
23
24// The access-level split is a type-level contract first: a Read client must
25// not offer a way to write, and a Write client must not offer a way to read.
26type _ReadHasNoWrites = Expect<
27 Equal<Extract<keyof ReadBucketClient, "put" | "delete">, never>
28>;
29type _WriteHasNoReads = Expect<
30 Equal<Extract<keyof WriteBucketClient, "get" | "head" | "list">, never>
31>;
32type _ReadWriteHasBoth = Expect<
33 Equal<Extract<keyof ReadWriteBucketClient, "get" | "put">, "get" | "put">
34>;
35
36const bucket = {
37 Type: "Prisma.Bucket",
38 LogicalId: "Uploads",
39 FQN: "Api/Uploads",
40} as PrismaBucket;
41
42describe(
43 "Prisma bucket binding identity",
44 { tags: ["unit", "provider:prisma", "provider:prisma:bucket", "local"] },
45 () => {
46 it("derives a stable bucket key logical id per bucket and access level", () => {
47 expect(bucketAccessKeyLogicalId(bucket, "Read")).toBe(
48 "UploadsReadBucketAccessKey",
49 );
50 expect(bucketAccessKeyLogicalId(bucket, "Write")).toBe(
51 "UploadsWriteBucketAccessKey",
52 );
53 expect(bucketAccessKeyLogicalId(bucket, "ReadWrite")).toBe(
54 "UploadsReadWriteBucketAccessKey",
55 );
56 // Stable across calls: the deployed bundle has to derive the same id.
57 expect(bucketAccessKeyLogicalId(bucket, "Read")).toBe(
58 bucketAccessKeyLogicalId({ LogicalId: "Uploads" }, "Read"),
59 );
60 });
61 },
62);
63
64const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
65 providers: Prisma.providers(),
66});
67
68const wantsLive = process.env.ALCHEMY_RUN_LIVE_PRISMA_TESTS === "true";
69const hasLiveCredentials =
70 !!process.env.PRISMA_SERVICE_TOKEN?.trim() ||
71 !!process.env.PRISMA_API_TOKEN?.trim() ||
72 process.env.ALCHEMY_RUN_LIVE_PRISMA_WITH_PROFILE === "true";
73const runLive = wantsLive && hasLiveCredentials;
74
75// One Prisma Compute deploy alone can take the full 600s Compute.live.test.ts
76// budgets for it; this stack deploys three of them plus a project, a bucket
77// and its keys.
78const HOOK_TIMEOUT = 1_200_000;
79const TEST_TIMEOUT = 120_000;
80
81const logLevel = Effect.provideService(
82 MinimumLogLevel,
83 process.env.DEBUG ? "Debug" : "Info",
84);
85
86if (wantsLive && !hasLiveCredentials) {
87 test(
88 "requires Prisma credentials for the live bucket binding suite",
89 Effect.fail(
90 new Error(
91 [
92 "Live Prisma bucket binding suite requested but no credentials are configured.",
93 "Set PRISMA_SERVICE_TOKEN, set PRISMA_API_TOKEN, or run `alchemy profile` and add Prisma with `Service Token`,",
94 "then rerun this live test with ALCHEMY_RUN_LIVE_PRISMA_TESTS=true.",
95 ].join(" "),
96 ),
97 ),
98 { tags: ["provider:prisma", "provider:prisma:bucket", "live"] },
99 );
100}
101
102class AppNotReady extends Data.TaggedError("AppNotReady")<{
103 status: number;
104 body: string;
105}> {}
106
107// Bounded spaced schedule — caps total wait so a genuine failure surfaces
108// fast instead of an uncapped exponential blowing past the test timeout
109// while riding out cold-start propagation.
110const ready = Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(30)]);
111
112/** Retry an HTTP call until it returns 200 (rides out the app endpoint's deploy propagation). */
113const untilOk = <E, R>(
114 eff: Effect.Effect<HttpClientResponse.HttpClientResponse, E, R>,
115) =>
116 eff.pipe(
117 Effect.flatMap((res) =>
118 res.status === 200
119 ? Effect.succeed(res)
120 : res.text.pipe(
121 Effect.flatMap((body) =>
122 Effect.fail(new AppNotReady({ status: res.status, body })),
123 ),
124 ),
125 ),
126 Effect.retry({
127 while: (e): e is AppNotReady => e instanceof AppNotReady,
128 schedule: ready,
129 }),
130 );
131
132// Reads assert directly with no retry-until-match: Prisma Object Store is
133// Tigris-backed, and same-region requests are read-after-write consistent —
134// these apps run in their bucket's region, so a read after a 200 write
135// observes the write. `untilOk` above only rides out endpoint readiness.
136
137/** GET `${base}/get?key=` — the stored body plus `contentType` / `metadata`. */
138const getObject = (base: string, key: string) =>
139 untilOk(HttpClient.get(`${base}/get?key=${encodeURIComponent(key)}`)).pipe(
140 Effect.flatMap((res) => res.json),
141 Effect.map(
142 (body) =>
143 body as {
144 value: string | null;
145 contentType: string | null;
146 metadata: Record<string, string> | null;
147 },
148 ),
149 );
150
151/** HEAD-equivalent: `/head` returns `{ exists, size }` (metadata only, no body). */
152const headObject = (base: string, key: string) =>
153 untilOk(HttpClient.get(`${base}/head?key=${encodeURIComponent(key)}`)).pipe(
154 Effect.flatMap((res) => res.json),
155 Effect.map((body) => body as { exists: boolean; size: number | null }),
156 );
157
158/** `PutOptions` the `/put` route rebuilds from query params. */
159interface PutQuery {
160 contentType?: string;
161 metaKey?: string;
162 metaValue?: string;
163}
164
165const put = (base: string, key: string, value: string, options?: PutQuery) => {
166 const params = new URLSearchParams({ key });
167 if (options?.contentType) params.set("contentType", options.contentType);
168 if (options?.metaKey) {
169 params.set("metaKey", options.metaKey);
170 params.set("metaValue", options.metaValue ?? "");
171 }
172 return untilOk(
173 HttpClient.execute(
174 HttpClientRequest.put(`${base}/put?${params}`).pipe(
175 HttpClientRequest.bodyText(value),
176 ),
177 ),
178 );
179};
180
181const del = (base: string, key: string) =>
182 untilOk(
183 HttpClient.execute(
184 HttpClientRequest.make("DELETE")(
185 `${base}/del?key=${encodeURIComponent(key)}`,
186 ),
187 ),
188 );
189
190const delMany = (base: string, keys: string[]) =>
191 untilOk(
192 HttpClient.execute(
193 HttpClientRequest.make("DELETE")(
194 `${base}/del-many?keys=${encodeURIComponent(keys.join(","))}`,
195 ),
196 ),
197 );
198
199/** One page of `/list`, with the paging fields the client reports. */
200const listPage = (
201 base: string,
202 query: {
203 prefix: string;
204 delimiter?: string;
205 limit?: number;
206 cursor?: string;
207 },
208) => {
209 const params = new URLSearchParams({ prefix: query.prefix });
210 if (query.delimiter) params.set("delimiter", query.delimiter);
211 if (query.limit !== undefined) params.set("limit", String(query.limit));
212 if (query.cursor) params.set("cursor", query.cursor);
213 return untilOk(HttpClient.get(`${base}/list?${params}`)).pipe(
214 Effect.flatMap((res) => res.json),
215 Effect.map(
216 (body) =>
217 body as {
218 keys: string[];
219 delimitedPrefixes: string[];
220 truncated: boolean;
221 cursor: string | null;
222 },
223 ),
224 );
225};
226
227/** Ask the deployed app to mint a presigned URL and hand it back. */
228const presign = (
229 base: string,
230 route: "presign-get" | "presign-put",
231 key: string,
232 contentType?: string,
233) => {
234 const params = new URLSearchParams({ key });
235 if (contentType) params.set("contentType", contentType);
236 return untilOk(HttpClient.get(`${base}/${route}?${params}`)).pipe(
237 Effect.flatMap((res) => res.json),
238 Effect.map((body) => (body as { url: string }).url),
239 );
240};
241
242/**
243 * Drive every client method through `fetch`: `put` → `get` → `head` →
244 * `list` → `delete` (single) → `delete` (batch) → `put` with options →
245 * paged/delimited `list` → `presignPut`/`presignGet`, reading back through
246 * `readBase` and writing through `writeBase`. All hosts share one bucket, so
247 * keys are namespaced by `label` to keep the runs independent.
248 */
249const exercise = (label: string, writeBase: string, readBase: string) =>
250 Effect.gen(function* () {
251 const prefix = `${label}/`;
252 const k1 = `${prefix}k1`;
253 const v1 = `${label}-value`;
254
255 // put + get
256 expect((yield* put(writeBase, k1, v1)).status).toBe(200);
257 expect((yield* getObject(readBase, k1)).value).toBe(v1);
258
259 // head — metadata reflects the written object
260 const meta = yield* headObject(readBase, k1);
261 expect(meta.exists).toBe(true);
262 expect(meta.size).toBe(new TextEncoder().encode(v1).length);
263
264 // list — the key shows up under its prefix
265 expect((yield* listPage(readBase, { prefix })).keys).toContain(k1);
266
267 // delete (single) — head/get then report it gone
268 yield* del(writeBase, k1);
269 expect((yield* getObject(readBase, k1)).value).toBeNull();
270 expect((yield* headObject(readBase, k1)).exists).toBe(false);
271
272 // delete (batch) — write two, delete both in one call
273 const k2 = `${prefix}k2`;
274 const k3 = `${prefix}k3`;
275 yield* put(writeBase, k2, "v2");
276 yield* put(writeBase, k3, "v3");
277 expect((yield* getObject(readBase, k2)).value).toBe("v2");
278 yield* delMany(writeBase, [k2, k3]);
279 expect((yield* getObject(readBase, k2)).value).toBeNull();
280 expect((yield* getObject(readBase, k3)).value).toBeNull();
281
282 // put options — contentType and user metadata survive the round-trip
283 const ok = `${prefix}with-options`;
284 yield* put(writeBase, ok, '{"ok":true}', {
285 contentType: "application/json",
286 metaKey: "owner",
287 metaValue: "api",
288 });
289 const stored = yield* getObject(readBase, ok);
290 expect(stored.value).toBe('{"ok":true}');
291 expect(stored.contentType).toBe("application/json");
292 expect(stored.metadata).toEqual({ owner: "api" });
293
294 // list paging — a small `limit` truncates and hands back a cursor that
295 // continues the listing; `delimiter` rolls the nested keys up instead.
296 const page = `${prefix}page/`;
297 yield* put(writeBase, `${page}a`, "a");
298 yield* put(writeBase, `${page}b`, "b");
299 yield* put(writeBase, `${page}c`, "c");
300
301 const first = yield* listPage(readBase, { prefix: page, limit: 2 });
302 expect(first.keys.length).toBe(2);
303 expect(first.truncated).toBe(true);
304 expect(typeof first.cursor).toBe("string");
305 const second = yield* listPage(readBase, {
306 prefix: page,
307 cursor: first.cursor ?? undefined,
308 });
309 expect([...first.keys, ...second.keys]).toContain(`${page}c`);
310
311 const rolled = yield* listPage(readBase, { prefix, delimiter: "/" });
312 expect(rolled.delimitedPrefixes).toContain(page);
313
314 // presign — the app mints the URLs, the test uses them with no
315 // credentials of its own: upload through the PUT URL, read it back
316 // through the GET URL.
317 const pk = `${prefix}presigned`;
318 const payload = `${label}-presigned-payload`;
319 const putUrl = yield* presign(writeBase, "presign-put", pk, "text/plain");
320 const uploaded = yield* HttpClient.execute(
321 HttpClientRequest.put(putUrl).pipe(
322 HttpClientRequest.bodyText(payload, "text/plain"),
323 ),
324 );
325 expect(uploaded.status).toBe(200);
326
327 const getUrl = yield* presign(readBase, "presign-get", pk);
328 const downloaded = yield* HttpClient.get(getUrl);
329 expect(downloaded.status).toBe(200);
330 expect(yield* downloaded.text).toBe(payload);
331 });
332
333/**
334 * Deploys three Prisma Compute apps that all bind one shared Object Store
335 * bucket — read / write / read-write — via {@link Stack}, then drives the
336 * binding over `fetch`:
337 *
338 * - write through the Write app, read it back through the Read app
339 * (cross-app, proving both halves agree on the bucket);
340 * - round-trip a key through the ReadWrite app by itself.
341 *
342 * The stack lives in `fixtures/stack.ts` so it can also be inspected
343 * directly, e.g. `alchemy logs --tail --stage test --config ./test/Prisma/fixtures/stack.ts`.
344 */
345describe.skipIf(!runLive)(
346 "Prisma bucket binding over deployed hosts",
347 {
348 tags: [
349 "provider:prisma",
350 "provider:prisma:bucket",
351 "provider:prisma:compute",
352 "provider:prisma:project",
353 "live",
354 ],
355 },
356 () => {
357 const stack = beforeAll(deploy(Stack), { timeout: HOOK_TIMEOUT });
358 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), {
359 timeout: HOOK_TIMEOUT,
360 });
361
362 test(
363 "write + read across separate compute apps",
364 Effect.gen(function* () {
365 const out = yield* stack;
366 yield* exercise("bind", out.write, out.read);
367 }).pipe(logLevel),
368 { timeout: TEST_TIMEOUT },
369 );
370
371 test(
372 "read-write round-trip in one compute app",
373 Effect.gen(function* () {
374 const out = yield* stack;
375 yield* exercise("rw-bind", out.readWrite, out.readWrite);
376 }).pipe(logLevel),
377 { timeout: TEST_TIMEOUT },
378 );
379 },
380);