@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 389 lines 12.4 KB
Raw
1 import * as Category from "@distilled.cloud/core/category";
2 import {
3 type GetServicesResponse,
4 deleteService,
5 deleteDeployment,
6 deleteProject,
7 getServices,
8 } from "@distilled.cloud/prisma/management";
9 import * as Data from "effect/Data";
10 import * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import * as Option from "effect/Option";
13 import { stopDeploymentIdempotent } from "./internal/DeploymentActions.ts";
14 import { observeDeployment } from "./internal/DeploymentObserve.ts";
15 import type { ObservedDeployment } from "./internal/Observed.ts";
16 import { PrismaPaginationError } from "./internal/Pagination.ts";
17 export { isConflict } from "./Client.ts";
18
19 /**
20 * A wait exceeded its `timeoutSeconds` budget before the deployment reached
21 * the requested status.
22 */
23 export class PrismaDeploymentWaitTimeout extends Data.TaggedError("PrismaDeploymentWaitTimeout")<{
24 message: string;
25 }> {}
26
27 /** `waitForDeploymentStatus` was called with a non-positive timeout or poll interval. */
28 export class PrismaDeploymentWaitInvalidOptions extends Data.TaggedError(
29 "PrismaDeploymentWaitInvalidOptions",
30 )<{
31 message: string;
32 }> {}
33
34 /** The deployment reached the terminal `failed` status while being waited on. */
35 export class PrismaDeploymentFailed extends Data.TaggedError("PrismaDeploymentFailed")<{
36 message: string;
37 }> {}
38
39 export interface WaitForDeploymentStatusOptions {
40 /**
41 * Maximum time to wait for a deployment to reach the requested status.
42 */
43 timeoutSeconds?: number;
44 /**
45 * Poll interval used while waiting for Prisma deployment status changes.
46 */
47 pollIntervalMs?: number;
48 }
49
50 /**
51 * Result returned after attempting to stop and delete a Prisma deployment.
52 */
53 export interface DestroyDeploymentResult {
54 /**
55 * Prisma deployment ID that was targeted.
56 */
57 deploymentId: string;
58 /**
59 * Status observed before cleanup started, or undefined if the deployment was gone.
60 */
61 previousStatus: string | undefined;
62 /**
63 * True when Alchemy requested a stop before deletion.
64 */
65 stopped: boolean;
66 /**
67 * True when the delete call completed or the deployment vanished during cleanup.
68 */
69 deleted: boolean;
70 }
71
72 /** Result returned after deleting a Prisma App. */
73 export interface DestroyAppResult {
74 /** Prisma App ID that was targeted. */
75 appId: string;
76 /** True when App deletion completed or the app was already gone. */
77 appDeleted: boolean;
78 }
79
80 /**
81 * Result returned after deleting Apps under a Prisma project.
82 */
83 export interface DestroyProjectAppsResult {
84 /**
85 * Prisma project ID that was targeted.
86 */
87 projectId: string;
88 /**
89 * App IDs deleted by this cleanup pass.
90 */
91 deletedAppIds: string[];
92 /**
93 * True when the project delete call completed or the project vanished.
94 */
95 projectDeleted: boolean;
96 }
97
98 const DEFAULT_TIMEOUT_SECONDS = 120;
99 const DEFAULT_POLL_INTERVAL_MS = 1_000;
100 const DELETE_CONFLICT_RETRY_ATTEMPTS = 5;
101
102 const deleteRetryDelay = (attempt: number) => Effect.sleep(Duration.millis(250 * 2 ** attempt));
103
104 const ensureError = (error: unknown): Error =>
105 error instanceof Error
106 ? error
107 : new Error("Prisma deployment lifecycle operation failed.", {
108 cause: error,
109 });
110
111 const deploymentDeleteFailed = (
112 deploymentId: string,
113 statusAtDelete: string | undefined,
114 error: unknown,
115 ) => {
116 const format = (error: unknown) => (error instanceof Error ? error.message : String(error));
117 const detail = format(error);
118 const isKnownStoppedDeleteFailure =
119 statusAtDelete === "stopped" && Category.hasCategory(error, "ServerError");
120 return new Error(
121 [
122 `Failed to delete Prisma deployment '${deploymentId}' while it was in status '${statusAtDelete ?? "unknown"}'.`,
123 detail,
124 isKnownStoppedDeleteFailure
125 ? "Stopped Prisma deployments are expected to be deletable; the Management API returned a server error."
126 : undefined,
127 "The deployment may need platform cleanup before the App or project can be deleted.",
128 `Manual check: GET /v1/deployments/${deploymentId}; manual retry: DELETE /v1/deployments/${deploymentId}.`,
129 ]
130 .filter((line): line is string => line !== undefined)
131 .join(" "),
132 { cause: error },
133 );
134 };
135
136 const deploymentWaitTimedOut = (
137 deploymentId: string,
138 targetStatus: "running" | "stopped",
139 lastStatus: string | undefined,
140 ) =>
141 new PrismaDeploymentWaitTimeout({
142 message: `Timed out waiting for Prisma deployment '${deploymentId}' to reach '${targetStatus}' (last status: '${lastStatus ?? "unknown"}')`,
143 });
144
145 export const waitForDeploymentStatus = Effect.fn(function* (
146 deploymentId: string,
147 targetStatus: "running" | "stopped",
148 options: WaitForDeploymentStatusOptions = {},
149 ) {
150 const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
151 const intervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
152 if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
153 return yield* new PrismaDeploymentWaitInvalidOptions({
154 message: "timeoutSeconds must be a positive finite number.",
155 });
156 }
157 if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
158 return yield* new PrismaDeploymentWaitInvalidOptions({
159 message: "pollIntervalMs must be a positive finite number.",
160 });
161 }
162 const timeoutMs = timeoutSeconds * 1_000;
163 const startedAt = yield* Effect.sync(() => Date.now());
164 const deadline = startedAt + timeoutMs;
165 let lastStatus: string | undefined;
166
167 while (true) {
168 const remainingBeforeObservation = yield* Effect.sync(() => deadline - Date.now());
169 if (remainingBeforeObservation <= 0) {
170 return yield* deploymentWaitTimedOut(deploymentId, targetStatus, lastStatus);
171 }
172 const deploymentOption = yield* observeDeployment(deploymentId).pipe(
173 Effect.timeoutOption(Duration.millis(remainingBeforeObservation)),
174 );
175 if (Option.isNone(deploymentOption)) {
176 return yield* deploymentWaitTimedOut(deploymentId, targetStatus, lastStatus);
177 }
178 const deployment = deploymentOption.value;
179 lastStatus = deployment.status;
180 if (deployment.status === targetStatus) {
181 return deployment satisfies ObservedDeployment;
182 }
183 if (deployment.status === "failed") {
184 return yield* new PrismaDeploymentFailed({
185 message: `Prisma deployment '${deploymentId}' failed`,
186 });
187 }
188
189 const elapsed = yield* Effect.sync(() => Date.now() - startedAt);
190 if (elapsed >= timeoutMs) {
191 return yield* deploymentWaitTimedOut(deploymentId, targetStatus, lastStatus);
192 }
193
194 yield* Effect.sleep(Duration.millis(Math.min(intervalMs, timeoutMs - elapsed)));
195 }
196 });
197
198 /**
199 * Stops a running or provisioning deployment (or waits out a stop in progress), then deletes it.
200 *
201 * Uses the canonical deployment lifecycle routes. Errors include the observed
202 * status and exact manual route for cleanup.
203 */
204 export const destroyDeployment = Effect.fn(function* (
205 deploymentId: string,
206 options: WaitForDeploymentStatusOptions = {},
207 ) {
208 const deployment = yield* observeDeployment(deploymentId).pipe(
209 Effect.catchTag("NotFound", () => Effect.undefined),
210 );
211 if (!deployment) {
212 return {
213 deploymentId,
214 previousStatus: undefined,
215 stopped: false,
216 // The postcondition is already satisfied. Report this consistently
217 // with delete calls whose 404 is observed after cleanup starts.
218 deleted: true,
219 } satisfies DestroyDeploymentResult;
220 }
221
222 const previousStatus = deployment.status;
223 let statusAtDelete = previousStatus;
224 let stopped = false;
225 if (
226 deployment.status === "running" ||
227 deployment.status === "provisioning" ||
228 deployment.status === "stopping"
229 ) {
230 if (deployment.status !== "stopping") {
231 yield* stopDeploymentIdempotent(deploymentId).pipe(
232 Effect.catchTag("NotFound", () => Effect.void),
233 Effect.mapError(ensureError),
234 );
235 stopped = true;
236 }
237 // Only a stopped deployment can be deleted.
238 const stoppedVersion = yield* waitForDeploymentStatus(deploymentId, "stopped", options).pipe(
239 Effect.catchTag("NotFound", () => Effect.undefined),
240 );
241 statusAtDelete = stoppedVersion?.status ?? "stopped";
242 }
243
244 yield* deleteDeployment({ deploymentId }).pipe(
245 Effect.catchTag("NotFound", () => Effect.void),
246 Effect.mapError((error) => deploymentDeleteFailed(deploymentId, statusAtDelete, error)),
247 );
248
249 return {
250 deploymentId,
251 previousStatus,
252 stopped,
253 deleted: true,
254 } satisfies DestroyDeploymentResult;
255 });
256
257 /**
258 * Deletes an App. The canonical App delete endpoint cascades its deployments.
259 */
260 export const destroyApp = Effect.fn(function* (
261 appId: string,
262 options: WaitForDeploymentStatusOptions & {
263 keepApp?: boolean;
264 } = {},
265 ) {
266 let appDeleted = false;
267 if (!options.keepApp) {
268 for (let attempt = 0; attempt < DELETE_CONFLICT_RETRY_ATTEMPTS; attempt++) {
269 const deleted = yield* deleteService({ serviceId: appId }).pipe(
270 Effect.as(true),
271 Effect.catchTags({
272 NotFound: () => Effect.succeed(true),
273 Conflict: (error) =>
274 attempt + 1 < DELETE_CONFLICT_RETRY_ATTEMPTS
275 ? deleteRetryDelay(attempt).pipe(Effect.as(false))
276 : Effect.fail(error),
277 }),
278 );
279 if (deleted) {
280 appDeleted = true;
281 break;
282 }
283 }
284 }
285
286 return {
287 appId,
288 appDeleted,
289 } satisfies DestroyAppResult;
290 });
291
292 /**
293 * Deletes every App under a project, then deletes the project.
294 *
295 * Callers can start from the project ID and let Alchemy discover the App IDs.
296 */
297 export const destroyProjectApps = Effect.fn(function* (
298 projectId: string,
299 options: WaitForDeploymentStatusOptions & {
300 keepProject?: boolean;
301 keepApp?: boolean;
302 } = {},
303 ) {
304 const deletedAppIds = new Set<string>();
305
306 const cleanupApps = Effect.fn(function* () {
307 // Distilled emits the cursor-paginated list operations as plain ops, so
308 // callers walk `pagination` themselves (see `src/Neon/Project.ts`). A 404
309 // from the project-filtered listing means the project is already gone.
310 const apps = yield* Effect.gen(function* () {
311 const items: GetServicesResponse["data"][number][] = [];
312 let cursor: string | undefined;
313 while (true) {
314 const page = yield* getServices(
315 cursor === undefined ? { projectId, limit: 100 } : { projectId, limit: 100, cursor },
316 );
317 items.push(...page.data);
318 const nextCursor = page.pagination.nextCursor;
319 if (!page.pagination.hasMore) break;
320 if (nextCursor === null) {
321 return yield* new PrismaPaginationError({
322 message:
323 "Invalid Prisma Management API pagination response from getServices: hasMore was true without a non-empty nextCursor",
324 });
325 }
326 cursor = nextCursor;
327 }
328 return items;
329 }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
330 if (!apps) return false;
331 for (const app of apps) {
332 const result = yield* destroyApp(app.id, options);
333 if (result.appDeleted) deletedAppIds.add(app.id);
334 }
335 return true;
336 });
337
338 yield* cleanupApps();
339
340 let projectDeleted = false;
341 if (!options.keepProject) {
342 for (let attempt = 0; attempt < DELETE_CONFLICT_RETRY_ATTEMPTS; attempt++) {
343 // A 409, or the API's 400 on a still-populated project, means the
344 // delete is blocked on remaining member resources: re-clean and retry.
345 const deleted = yield* deleteProject({ id: projectId }).pipe(
346 Effect.as(true),
347 Effect.catchTags({
348 NotFound: () => Effect.succeed(true),
349 Conflict: (error) =>
350 Effect.gen(function* () {
351 if (attempt + 1 >= DELETE_CONFLICT_RETRY_ATTEMPTS) {
352 return yield* error;
353 }
354 yield* cleanupApps();
355 yield* deleteRetryDelay(attempt);
356 return false;
357 }),
358 }),
359 Effect.catchTag("BadRequest", (error) =>
360 Effect.gen(function* () {
361 if (attempt + 1 >= DELETE_CONFLICT_RETRY_ATTEMPTS) {
362 return yield* error;
363 }
364 yield* cleanupApps();
365 yield* deleteRetryDelay(attempt);
366 return false;
367 }),
368 ),
369 );
370 if (deleted) {
371 projectDeleted = true;
372 break;
373 }
374 }
375 }
376
377 return {
378 projectId,
379 deletedAppIds: Array.from(deletedAppIds),
380 projectDeleted,
381 } satisfies DestroyProjectAppsResult;
382 });
383
384 export const toDeploymentUrl = (domain: string | null | undefined) =>
385 domain
386 ? domain.startsWith("http://") || domain.startsWith("https://")
387 ? domain
388 : `https://${domain}`
389 : undefined;