@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 552 lines 20.1 KB
Raw
1 import { PrismaApiError, type PrismaManagementClient } from "@alchemy.run/prisma/Client";
2 import {
3 destroyApp,
4 destroyDeployment,
5 destroyProjectApps,
6 waitForDeploymentStatus,
7 } from "@alchemy.run/prisma/ComputeLifecycle";
8 import { describe, expect, it } from "@alchemy.run/test";
9 import { Retry, fromApiToken } from "@distilled.cloud/prisma";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
12 import * as HttpClient from "effect/http/HttpClient";
13 import * as Layer from "effect/Layer";
14 import * as Redacted from "effect/Redacted";
15 import * as TestClock from "effect/testing/TestClock";
16 import { PrismaPaginationError } from "../../../prisma/src/internal/Pagination.ts";
17 import {
18 type Captured,
19 data,
20 dispatchTo,
21 FAKE_API_BASE_URL,
22 makeFakeManagementApi,
23 page,
24 unhandled,
25 } from "./fixtures/FakeManagementApi.ts";
26
27 const apiError = (method: "GET" | "POST" | "DELETE", path: string, status: number) =>
28 new PrismaApiError({ method, path, status, message: `HTTP ${status}` });
29
30 const deployment = (id: string, status: string) => ({
31 id,
32 type: "deployment" as const,
33 serviceId: "app-1",
34 url: `https://api.prisma.test/v1/deployments/${id}`,
35 foundryVersionId: `foundry-${id}`,
36 status,
37 previewDomain: `${id}.preview.prisma.build`,
38 createdAt: "2026-01-01T00:00:00Z",
39 });
40
41 const appItem = (id: string) => ({
42 id,
43 type: "app" as const,
44 url: `https://api.prisma.test/v1/services/${id}`,
45 name: id,
46 region: { id: "us-east-1", name: "US East" },
47 projectId: "project-1",
48 branchId: null,
49 latestDeploymentId: null,
50 appEndpointDomain: `${id}.prisma.build`,
51 createdAt: "2026-01-01T00:00:00Z",
52 });
53
54 /**
55 * Serve the Management API from the same hermetic client-shaped handlers
56 * these tests declare, for the lifecycle routes now reached through distilled
57 * operations. `dispatchTo` maps each handler's result onto the wire (see the
58 * fixture).
59 */
60 const clientBackedApi = (client: any) =>
61 makeFakeManagementApi((request: Captured) => {
62 // segments[0] is the "v1" prefix.
63 const [head, id, tail] = request.pathname
64 .split("/")
65 .filter((segment) => segment.length > 0)
66 .slice(1);
67 const query = Object.fromEntries(new URLSearchParams(request.search));
68 const { call, callVoid, list } = dispatchTo(request);
69
70 if (head === "deployments" && id !== undefined) {
71 if (tail === "stop") return callVoid(client.stopDeployment, [id]);
72 if (request.method === "GET") return call(client.getDeployment, [id]);
73 if (request.method === "DELETE") {
74 return callVoid(client.deleteDeployment, [id]);
75 }
76 }
77 if (head === "services") {
78 if (id === undefined && request.method === "GET") {
79 return call(client.listApps, [query], list);
80 }
81 if (id !== undefined && tail === "deployments") {
82 return call(client.listAppDeployments, [id, query], list);
83 }
84 if (id !== undefined && request.method === "DELETE") {
85 return callVoid(client.deleteApp, [id]);
86 }
87 }
88 if (head === "projects" && id !== undefined && request.method === "DELETE") {
89 return callVoid(client.deleteProject, [id]);
90 }
91 return unhandled(request);
92 });
93
94 const provide = (client: unknown) => Effect.provide(clientBackedApi(client).layer);
95
96 describe(
97 "Prisma canonical Compute lifecycle",
98 { tags: ["unit", "provider:prisma", "provider:prisma:compute", "local"] },
99 () => {
100 it.live("waits for a deployment to reach its target status", () => {
101 let observed = 0;
102 const client = {
103 getDeployment: (id: string) =>
104 Effect.sync(() => deployment(id, observed++ === 0 ? "provisioning" : "running")),
105 } as unknown as PrismaManagementClient;
106
107 return Effect.gen(function* () {
108 const result = yield* waitForDeploymentStatus("deployment-1", "running", {
109 pollIntervalMs: 1,
110 timeoutSeconds: 10,
111 });
112 expect(result.status).toBe("running");
113 expect(observed).toBe(2);
114 }).pipe(provide(client));
115 });
116
117 it.effect("fails immediately for a failed deployment", () => {
118 const client = {
119 getDeployment: (id: string) => Effect.succeed(deployment(id, "failed")),
120 } as unknown as PrismaManagementClient;
121
122 return Effect.gen(function* () {
123 const error = yield* waitForDeploymentStatus("deployment-1", "running").pipe(Effect.flip);
124 expect(error.message).toContain("deployment-1");
125 expect(error.message).toContain("failed");
126 }).pipe(provide(client));
127 });
128
129 it.live("times out with the last observed deployment status", () => {
130 const client = {
131 getDeployment: (id: string) => Effect.succeed(deployment(id, "provisioning")),
132 } as unknown as PrismaManagementClient;
133
134 return Effect.gen(function* () {
135 const error = yield* waitForDeploymentStatus("deployment-1", "running", {
136 timeoutSeconds: 0.01,
137 pollIntervalMs: 1,
138 }).pipe(Effect.flip);
139 expect(error.message).toContain("Timed out");
140 expect(error.message).toContain("provisioning");
141 }).pipe(provide(client));
142 });
143
144 it.live("caps a hung deployment observation at the polling deadline", () => {
145 // A handler cannot hang inside the synchronous dispatch fake, so the hang
146 // is modeled at the transport: an HTTP client that never answers.
147 const hungTransport = Layer.mergeAll(
148 Layer.succeed(
149 HttpClient.HttpClient,
150 HttpClient.make(() => Effect.never),
151 ),
152 fromApiToken({
153 apiToken: Redacted.make("fake-service-token"),
154 apiBaseUrl: FAKE_API_BASE_URL,
155 }),
156 );
157
158 return Effect.gen(function* () {
159 const startedAt = Date.now();
160 const error = yield* waitForDeploymentStatus("deployment-hung", "running", {
161 timeoutSeconds: 0.05,
162 pollIntervalMs: 1,
163 }).pipe(Effect.flip);
164 const elapsed = Date.now() - startedAt;
165
166 expect(error.message).toContain("Timed out");
167 expect(error.message).toContain("last status: 'unknown'");
168 expect(elapsed).toBeLessThan(500);
169 }).pipe(Effect.provide(hungTransport));
170 });
171
172 it.effect("rejects invalid deployment polling timings", () => {
173 const client = {
174 getDeployment: () => Effect.die("invalid options must fail first"),
175 } as unknown as PrismaManagementClient;
176
177 return Effect.gen(function* () {
178 const timeoutError = yield* waitForDeploymentStatus("deployment-1", "running", {
179 timeoutSeconds: 0,
180 }).pipe(Effect.flip);
181 const intervalError = yield* waitForDeploymentStatus("deployment-1", "running", {
182 pollIntervalMs: Number.NaN,
183 }).pipe(Effect.flip);
184
185 expect(timeoutError.message).toContain("timeoutSeconds");
186 expect(intervalError.message).toContain("pollIntervalMs");
187 }).pipe(provide(client));
188 });
189
190 it.effect("preserves a not-found observation while waiting", () => {
191 const client = {
192 getDeployment: () => Effect.fail(apiError("GET", "/v1/deployments/deployment-1", 404)),
193 } as unknown as PrismaManagementClient;
194
195 return Effect.gen(function* () {
196 const error = yield* waitForDeploymentStatus("deployment-1", "running").pipe(Effect.flip);
197 // Over the wire the injected 404 decodes into the typed error.
198 expect(error._tag).toBe("NotFound");
199 expect(error.message).toBe("HTTP 404");
200 }).pipe(provide(client));
201 });
202
203 it.effect("treats an already deleted deployment as deleted", () => {
204 const client = {
205 getDeployment: (id: string) => Effect.fail(apiError("GET", `/v1/deployments/${id}`, 404)),
206 } as unknown as PrismaManagementClient;
207
208 return Effect.gen(function* () {
209 const result = yield* destroyDeployment("deployment-missing");
210 expect(result).toEqual({
211 deploymentId: "deployment-missing",
212 previousStatus: undefined,
213 stopped: false,
214 deleted: true,
215 });
216 }).pipe(provide(client));
217 });
218
219 it.effect("stops a running deployment before deleting it", () => {
220 const calls: string[] = [];
221 let status = "running";
222 const client = {
223 getDeployment: (id: string) =>
224 Effect.sync(() => {
225 calls.push(`get:${id}`);
226 return deployment(id, status);
227 }),
228 stopDeployment: (id: string) =>
229 Effect.sync(() => {
230 calls.push(`stop:${id}`);
231 status = "stopped";
232 }),
233 deleteDeployment: (id: string) =>
234 Effect.sync(() => {
235 calls.push(`delete:${id}`);
236 }),
237 } as unknown as PrismaManagementClient;
238
239 return Effect.gen(function* () {
240 const result = yield* destroyDeployment("deployment-1");
241 expect(result).toMatchObject({
242 deploymentId: "deployment-1",
243 previousStatus: "running",
244 stopped: true,
245 deleted: true,
246 });
247 expect(calls).toEqual([
248 "get:deployment-1",
249 "stop:deployment-1",
250 "get:deployment-1",
251 "delete:deployment-1",
252 ]);
253 }).pipe(provide(client));
254 });
255
256 it.live("waits for a deployment that is already stopping before deleting it", () => {
257 const calls: string[] = [];
258 let observed = 0;
259 const client = {
260 getDeployment: (id: string) =>
261 Effect.sync(() => {
262 calls.push(`get:${id}`);
263 return deployment(id, observed++ < 2 ? "stopping" : "stopped");
264 }),
265 deleteDeployment: (id: string) =>
266 Effect.sync(() => {
267 calls.push(`delete:${id}`);
268 }),
269 } as unknown as PrismaManagementClient;
270
271 return Effect.gen(function* () {
272 const result = yield* destroyDeployment("deployment-1", {
273 pollIntervalMs: 1,
274 });
275 expect(result).toMatchObject({
276 previousStatus: "stopping",
277 stopped: false,
278 deleted: true,
279 });
280 expect(calls).toEqual([
281 "get:deployment-1",
282 "get:deployment-1",
283 "get:deployment-1",
284 "delete:deployment-1",
285 ]);
286 }).pipe(provide(client));
287 });
288
289 it.effect("reports only the canonical deployment cleanup route", () => {
290 const client = {
291 getDeployment: () => Effect.succeed(deployment("deployment-1", "stopped")),
292 deleteDeployment: (id: string) =>
293 Effect.fail(apiError("DELETE", `/v1/deployments/${id}`, 400)),
294 } as unknown as PrismaManagementClient;
295
296 return Effect.gen(function* () {
297 const error = yield* destroyDeployment("deployment-1").pipe(Effect.flip);
298 expect(error.message).toContain("DELETE /v1/deployments/deployment-1");
299 }).pipe(provide(client));
300 });
301
302 it.effect("explains a stopped deployment whose delete fails with a server error", () => {
303 const client = {
304 getDeployment: () => Effect.succeed(deployment("deployment-1", "stopped")),
305 deleteDeployment: (id: string) =>
306 // An unmapped status decodes into the catch-all error, which
307 // carries the ServerError category the diagnostic branch reads.
308 Effect.fail(apiError("DELETE", `/v1/deployments/${id}`, 507)),
309 } as unknown as PrismaManagementClient;
310
311 return Effect.gen(function* () {
312 const error = yield* destroyDeployment("deployment-1").pipe(Effect.flip);
313 expect(error.message).toContain("Stopped Prisma deployments are expected to be deletable");
314 expect(error.message).toContain("DELETE /v1/deployments/deployment-1");
315 }).pipe(
316 provide(client),
317 // Server-category errors are replayed by the default policy; this
318 // test examines the terminal diagnostic, so retries are disabled.
319 Effect.provide(Layer.succeed(Retry.Retry, { while: () => false })),
320 );
321 });
322
323 it.effect("uses the App delete cascade without enumerating deployments", () => {
324 const calls: string[] = [];
325 const client = {
326 listAppDeployments: () => Effect.die("must not enumerate deployments"),
327 deleteApp: (id: string) =>
328 Effect.sync(() => {
329 calls.push(`delete-app:${id}`);
330 }),
331 } as unknown as PrismaManagementClient;
332
333 return Effect.gen(function* () {
334 const result = yield* destroyApp("app-1");
335 expect(result).toEqual({ appId: "app-1", appDeleted: true });
336 expect(calls).toEqual(["delete-app:app-1"]);
337 }).pipe(provide(client));
338 });
339
340 it.live("retries a bounded App deletion conflict", () => {
341 let attempts = 0;
342 const client = {
343 deleteApp: (id: string) =>
344 Effect.suspend(() => {
345 attempts += 1;
346 return attempts < 3
347 ? Effect.fail(apiError("DELETE", `/v1/services/${id}`, 409))
348 : Effect.void;
349 }),
350 } as unknown as PrismaManagementClient;
351
352 return Effect.gen(function* () {
353 const result = yield* destroyApp("app-1");
354 expect(result.appDeleted).toBe(true);
355 expect(attempts).toBe(3);
356 }).pipe(provide(client));
357 });
358
359 it.effect("treats an already deleted App as deleted", () => {
360 const client = {
361 deleteApp: (id: string) => Effect.fail(apiError("DELETE", `/v1/services/${id}`, 404)),
362 } as unknown as PrismaManagementClient;
363
364 return Effect.gen(function* () {
365 expect(yield* destroyApp("app-missing")).toEqual({
366 appId: "app-missing",
367 appDeleted: true,
368 });
369 }).pipe(provide(client));
370 });
371
372 it.effect("surfaces the final App deletion conflict", () => {
373 let attempts = 0;
374 const conflict = apiError("DELETE", "/v1/services/app-1", 409);
375 const client = {
376 deleteApp: () =>
377 Effect.sync(() => {
378 attempts += 1;
379 }).pipe(Effect.flatMap(() => Effect.fail(conflict))),
380 } as unknown as PrismaManagementClient;
381
382 return Effect.gen(function* () {
383 const fiber = yield* destroyApp("app-1").pipe(Effect.flip, Effect.forkChild);
384 yield* TestClock.adjust("30 seconds");
385 const error = yield* Fiber.join(fiber);
386 // Over the wire the injected 409 decodes into the typed error.
387 expect(error._tag).toBe("Conflict");
388 expect(error.message).toBe("HTTP 409");
389 expect(attempts).toBe(5);
390 }).pipe(provide(client));
391 });
392
393 it.effect("deletes project Apps before deleting the project", () => {
394 const calls: string[] = [];
395 const client = {
396 listApps: (query: unknown) =>
397 Effect.sync(() => {
398 calls.push(`list:${JSON.stringify(query)}`);
399 return [appItem("app-1"), appItem("app-2")];
400 }),
401 deleteApp: (id: string) =>
402 Effect.sync(() => {
403 calls.push(`delete-app:${id}`);
404 }),
405 deleteProject: (id: string) =>
406 Effect.sync(() => {
407 calls.push(`delete-project:${id}`);
408 }),
409 } as unknown as PrismaManagementClient;
410
411 return Effect.gen(function* () {
412 const result = yield* destroyProjectApps("project-1");
413 expect(result).toEqual({
414 projectId: "project-1",
415 deletedAppIds: ["app-1", "app-2"],
416 projectDeleted: true,
417 });
418 expect(calls).toEqual([
419 // Over the wire, query params arrive as strings.
420 'list:{"limit":"100","projectId":"project-1"}',
421 "delete-app:app-1",
422 "delete-app:app-2",
423 "delete-project:project-1",
424 ]);
425 }).pipe(provide(client));
426 });
427
428 it.effect("treats an already deleted project as deleted", () => {
429 const client = {
430 listApps: () => Effect.fail(apiError("GET", "/v1/services?projectId=project-1", 404)),
431 deleteProject: (id: string) => Effect.fail(apiError("DELETE", `/v1/projects/${id}`, 404)),
432 } as unknown as PrismaManagementClient;
433
434 return Effect.gen(function* () {
435 expect(yield* destroyProjectApps("project-1")).toEqual({
436 projectId: "project-1",
437 deletedAppIds: [],
438 projectDeleted: true,
439 });
440 }).pipe(provide(client));
441 });
442
443 it.live("re-cleans Apps after a blocked project deletion", () => {
444 const calls: string[] = [];
445 let lists = 0;
446 let deletes = 0;
447 const client = {
448 listApps: () =>
449 Effect.sync(() => {
450 lists += 1;
451 calls.push(`list:${lists}`);
452 return lists === 1 ? [appItem("app-1")] : [];
453 }),
454 deleteApp: (id: string) => Effect.sync(() => calls.push(`delete-app:${id}`)),
455 deleteProject: (id: string) =>
456 Effect.suspend(() => {
457 deletes += 1;
458 calls.push(`delete-project:${id}:${deletes}`);
459 return deletes === 1
460 ? Effect.fail(apiError("DELETE", `/v1/projects/${id}`, 409))
461 : Effect.void;
462 }),
463 } as unknown as PrismaManagementClient;
464
465 return Effect.gen(function* () {
466 const result = yield* destroyProjectApps("project-1");
467 expect(result).toEqual({
468 projectId: "project-1",
469 deletedAppIds: ["app-1"],
470 projectDeleted: true,
471 });
472 expect(calls).toEqual([
473 "list:1",
474 "delete-app:app-1",
475 "delete-project:project-1:1",
476 "list:2",
477 "delete-project:project-1:2",
478 ]);
479 }).pipe(provide(client));
480 });
481
482 it.effect("supports keeping the project after deleting its Apps", () => {
483 const calls: string[] = [];
484 const client = {
485 listApps: () => Effect.succeed([appItem("app-1")]),
486 deleteApp: (id: string) => Effect.sync(() => calls.push(`delete-app:${id}`)),
487 deleteProject: () => Effect.die("must not delete project"),
488 } as unknown as PrismaManagementClient;
489
490 return Effect.gen(function* () {
491 const result = yield* destroyProjectApps("project-1", { keepProject: true });
492 expect(result.projectDeleted).toBe(false);
493 expect(result.deletedAppIds).toEqual(["app-1"]);
494 expect(calls).toEqual(["delete-app:app-1"]);
495 }).pipe(provide(client));
496 });
497
498 it.effect("cleans every App returned across canonical pagination", () => {
499 const apps = Array.from({ length: 101 }, (_, index) => appItem(`app-${index}`));
500 const deleted: string[] = [];
501 const client = {
502 // The fake serves the full set in one page; the inline walk stops when
503 // the pagination envelope reports no more pages.
504 listApps: () => Effect.succeed(apps),
505 deleteApp: (id: string) =>
506 Effect.sync(() => {
507 deleted.push(id);
508 }),
509 } as unknown as PrismaManagementClient;
510
511 return Effect.gen(function* () {
512 const result = yield* destroyProjectApps("project-1", { keepProject: true });
513 expect(result.deletedAppIds).toHaveLength(101);
514 expect(deleted).toHaveLength(101);
515 }).pipe(provide(client));
516 });
517
518 it.effect("supports keeping Apps during project-scoped inspection", () => {
519 const client = {
520 listApps: () => Effect.succeed([appItem("app-1")]),
521 deleteApp: () => Effect.die("must not delete App"),
522 deleteProject: () => Effect.die("must not delete project"),
523 } as unknown as PrismaManagementClient;
524
525 return Effect.gen(function* () {
526 const result = yield* destroyProjectApps("project-1", { keepApp: true, keepProject: true });
527 expect(result).toEqual({
528 projectId: "project-1",
529 deletedAppIds: [],
530 projectDeleted: false,
531 });
532 }).pipe(provide(client));
533 });
534
535 it.effect("refuses a truncated App listing that promises another page", () => {
536 // `hasMore: true` with no cursor is a malformed page. Reading it as the
537 // end of the list would let the cleanup miss live Apps, so the walk fails
538 // loudly instead.
539 const fake = makeFakeManagementApi((request: Captured) =>
540 request.pathname === "/v1/services" && request.method === "GET"
541 ? page([appItem("app-1")], true, null)
542 : unhandled(request),
543 );
544
545 return Effect.gen(function* () {
546 const error = yield* destroyProjectApps("project-1").pipe(Effect.flip);
547 expect(error).toBeInstanceOf(PrismaPaginationError);
548 expect(error.message).toContain("hasMore was true without a non-empty nextCursor");
549 }).pipe(Effect.provide(fake.layer));
550 });
551 },
552 );