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

main
ts 178 lines 6.46 KB
Raw
1 import {
2 getService,
3 createServicePromote,
4 createServiceRollback,
5 } from "@distilled.cloud/prisma/management";
6 import * as Data from "effect/Data";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Result from "effect/Result";
11
12 export class AppPromotionInvalidProps extends Data.TaggedError("AppPromotionInvalidProps")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface AppDeploymentTargetObservationOptions {
18 readonly timeoutSeconds?: number;
19 readonly pollIntervalMs?: number;
20 }
21
22 const DEFAULT_TIMEOUT_SECONDS = 60;
23 const DEFAULT_POLL_INTERVAL_MS = 1_000;
24
25 export const waitForAppDeploymentTarget = Effect.fn(function* (
26 appId: string,
27 deploymentId: string,
28 options: AppDeploymentTargetObservationOptions = {},
29 ) {
30 const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
31 const intervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
32 if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
33 return yield* new AppPromotionInvalidProps({
34 message: "timeoutSeconds must be a positive finite number.",
35 });
36 }
37 if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
38 return yield* new AppPromotionInvalidProps({
39 message: "pollIntervalMs must be a positive finite number.",
40 });
41 }
42
43 const timeoutMs = timeoutSeconds * 1_000;
44 const deadline = yield* Effect.sync(() => Date.now() + timeoutMs);
45 let lastLatestDeploymentId: string | null | undefined;
46 let lastError: unknown;
47
48 while (true) {
49 const remainingBeforeObservation = yield* Effect.sync(() => deadline - Date.now());
50 if (remainingBeforeObservation <= 0) break;
51
52 const observationOption = yield* getService({ serviceId: appId }).pipe(
53 Effect.map((response) => response.data),
54 Effect.result,
55 Effect.timeoutOption(Duration.millis(remainingBeforeObservation)),
56 );
57 if (Option.isNone(observationOption)) break;
58 const observation = observationOption.value;
59 if (Result.isSuccess(observation)) {
60 lastLatestDeploymentId = observation.success.latestDeploymentId;
61 lastError = undefined;
62 if (lastLatestDeploymentId === deploymentId) {
63 return observation.success;
64 }
65 } else {
66 lastError = observation.failure;
67 }
68
69 const remainingAfterObservation = yield* Effect.sync(() => deadline - Date.now());
70 if (remainingAfterObservation <= 0) break;
71 yield* Effect.sleep(Duration.millis(Math.min(intervalMs, remainingAfterObservation)));
72 }
73
74 return yield* Effect.fail(
75 new AggregateError(
76 lastError === undefined ? [] : [lastError],
77 `Timed out waiting for Prisma App '${appId}' to report deployment '${deploymentId}' as latest (last observed latest deployment: '${lastLatestDeploymentId ?? "none"}').`,
78 ),
79 );
80 });
81
82 /**
83 * Promote an App and recover response loss by observing the canonical App.
84 * Every successful mutation is followed by bounded observation of the App
85 * row before callers may probe stable readiness or delete another deployment.
86 * If the promotion response is lost, the canonical rollback primitive heals
87 * an already-flipped Foundry endpoint or safely completes the target
88 * promotion. Any non-converged result is ambiguous and must never trigger
89 * target deletion.
90 */
91 export const promoteAppObserved = Effect.fn(function* (
92 appId: string,
93 deploymentId: string,
94 options: AppDeploymentTargetObservationOptions = {},
95 ) {
96 const promoted = yield* createServicePromote({
97 serviceId: appId,
98 deploymentId,
99 }).pipe(
100 Effect.map((response) => response.data),
101 Effect.result,
102 );
103 if (Result.isSuccess(promoted)) {
104 const observation = yield* waitForAppDeploymentTarget(appId, deploymentId, options).pipe(
105 Effect.result,
106 );
107 if (Result.isFailure(observation)) {
108 return yield* Effect.fail(
109 new AggregateError(
110 [observation.failure],
111 `Prisma App '${appId}' promotion returned success for deployment '${deploymentId}', but the App did not converge to that target. The deployment was preserved because promotion commit state is ambiguous.`,
112 ),
113 );
114 }
115 return {
116 ...promoted.success,
117 appEndpointDomain: observation.success.appEndpointDomain,
118 };
119 }
120
121 const observation = yield* getService({ serviceId: appId }).pipe(
122 Effect.map((response) => response.data),
123 Effect.result,
124 );
125 if (Result.isSuccess(observation) && observation.success.latestDeploymentId === deploymentId) {
126 return {
127 appEndpointDomain: observation.success.appEndpointDomain,
128 reassignedDomains: 0,
129 };
130 }
131 const repaired = yield* createServiceRollback({
132 serviceId: appId,
133 deploymentId,
134 }).pipe(
135 Effect.map((response) => response.data),
136 Effect.result,
137 );
138 const observeRepaired: Effect.Effect<
139 Effect.Success<ReturnType<typeof waitForAppDeploymentTarget>>,
140 | Effect.Error<ReturnType<typeof waitForAppDeploymentTarget>>
141 | Effect.Error<ReturnType<typeof getService>>,
142 Effect.Services<ReturnType<typeof waitForAppDeploymentTarget>>
143 > = Result.isSuccess(repaired)
144 ? waitForAppDeploymentTarget(appId, deploymentId, options)
145 : getService({ serviceId: appId }).pipe(Effect.map((response) => response.data));
146 const repairedObservation = yield* Effect.result(observeRepaired);
147 if (
148 Result.isSuccess(repairedObservation) &&
149 repairedObservation.success.latestDeploymentId === deploymentId
150 ) {
151 return Result.isSuccess(repaired)
152 ? {
153 ...repaired.success,
154 appEndpointDomain: repairedObservation.success.appEndpointDomain,
155 }
156 : {
157 appEndpointDomain: repairedObservation.success.appEndpointDomain,
158 reassignedDomains: 0,
159 };
160 }
161 return yield* Effect.fail(
162 new AggregateError(
163 [
164 promoted.failure,
165 ...(Result.isFailure(observation) ? [observation.failure] : []),
166 ...(Result.isFailure(repaired) ? [repaired.failure] : []),
167 ...(Result.isFailure(repairedObservation)
168 ? [repairedObservation.failure]
169 : [
170 new Error(
171 `Prisma App '${appId}' still reports deployment '${repairedObservation.success.latestDeploymentId ?? "none"}' as latest after canonical recovery targeted '${deploymentId}'.`,
172 ),
173 ]),
174 ],
175 `Prisma App '${appId}' promotion of deployment '${deploymentId}' failed and canonical recovery also failed. The deployment was not deleted because endpoint commit state is ambiguous.`,
176 ),
177 );
178 });