The best way to control Claude Code, Codex and more from any computer or phone

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