@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, 06:00 UTC

main
ts 254 lines 8.33 KB
Raw
1 import * as deploymentmanager from "@distilled.cloud/gcp/deploymentmanager_v2";
2 import type { GcpOpContext } from "@distilled.cloud/gcp/Protocol";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import { tagRecord } from "alchemy/Tags";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { stripInternalLabels } from "../Labels.ts";
10 import { waitForOperation as waitForLongRunningOperation } from "../Operation.ts";
11
12 export const MAX_NAME_LENGTH = 63;
13
14 export class ResourceNotResolved extends Data.TaggedError(
15 "GCP.DeploymentManager.ResourceNotResolved",
16 )<{
17 resourceName: string;
18 }> {}
19
20 export class ResourceStillExists extends Data.TaggedError(
21 "GCP.DeploymentManager.ResourceStillExists",
22 )<{
23 resourceName: string;
24 }> {}
25
26 export const lastSegment = (value: string) => {
27 const trimmed = value.replace(/\/+$/, "");
28 const parts = trimmed.split("/");
29 return parts[parts.length - 1] || trimmed;
30 };
31
32 export const rfc1035 = (name: string, fallback = "deployment"): string => {
33 let next = name
34 .toLowerCase()
35 .replace(/[^a-z0-9-]/g, "-")
36 .replace(/-+/g, "-")
37 .replace(/^-+|-+$/g, "");
38 if (!/^[a-z]/.test(next)) next = `d${next}`;
39 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
40 if (next.length === 0) return fallback;
41 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
42 return next.slice(0, MAX_NAME_LENGTH);
43 };
44
45 export const toPhysicalId = (
46 id: string,
47 explicit: string | undefined,
48 existing: string | undefined,
49 ) =>
50 Effect.gen(function* () {
51 if (explicit !== undefined) return rfc1035(explicit);
52 if (existing !== undefined) return existing;
53 return rfc1035(
54 yield* createPhysicalName({
55 id,
56 maxLength: MAX_NAME_LENGTH,
57 lowercase: true,
58 }),
59 );
60 });
61
62 export const userLabels = (
63 labels: Record<string, string | undefined> | null | undefined,
64 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
65
66 export const labelsToRecord = (
67 labels: readonly deploymentmanager.DeploymentLabelEntry[] | undefined,
68 ): Record<string, string> =>
69 Object.fromEntries(
70 (labels ?? [])
71 .filter(
72 (entry): entry is { key: string; value: string } =>
73 typeof entry.key === "string" && entry.key.length > 0 && typeof entry.value === "string",
74 )
75 .map((entry) => [entry.key, entry.value]),
76 );
77
78 export const recordToLabels = (
79 labels: Record<string, string>,
80 ): deploymentmanager.DeploymentLabelEntry[] =>
81 Object.entries(labels).map(([key, value]) => ({ key, value }));
82
83 export const sameText = (left: string | undefined, right: string | undefined) =>
84 (left ?? "") === (right ?? "");
85
86 export const canonical = (value: unknown): unknown => {
87 if (value === undefined || value === null) return undefined;
88 if (typeof value === "boolean" || typeof value === "number") return value;
89 if (typeof value === "string") {
90 const trimmed = value.trim();
91 return trimmed.length === 0 ? undefined : trimmed;
92 }
93 if (Array.isArray(value)) {
94 const items = value.map(canonical).filter((item) => item !== undefined);
95 return items.length === 0 ? undefined : items;
96 }
97 if (typeof value === "object") {
98 const entries = Object.entries(value as Record<string, unknown>)
99 .map(([key, item]) => [key, canonical(item)] as const)
100 .filter(([, item]) => item !== undefined)
101 .sort(([left], [right]) => left.localeCompare(right));
102 if (entries.length === 0) return undefined;
103 return Object.fromEntries(entries);
104 }
105 return undefined;
106 };
107
108 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
109
110 /**
111 * Wait on a Deployment Manager operation (Compute-style `status: "DONE"`).
112 * Deployments of a handful of resources finish in a minute or two.
113 * `*ALREADY_EXISTS` counts as success; so does a not-found error when
114 * `notFoundOk` (deletes). Returns the final operation.
115 */
116 export const waitForOperation = (
117 project: string,
118 operation: deploymentmanager.Operation,
119 options?: { notFoundOk?: boolean },
120 ) =>
121 Effect.suspend(() => {
122 let latest = operation;
123 return waitForLongRunningOperation(
124 operation,
125 (name) => {
126 const get = deploymentmanager.getOperations({ project, operation: lastSegment(name) }).pipe(
127 Effect.tap((current) =>
128 Effect.sync(() => {
129 latest = current;
130 }),
131 ),
132 );
133 const observe: Effect.Effect<
134 deploymentmanager.Operation,
135 deploymentmanager.GetOperationsError,
136 GcpOpContext
137 > =
138 options?.notFoundOk === true
139 ? get.pipe(
140 Effect.catchTag("NotFound", () =>
141 Effect.succeed<deploymentmanager.Operation>({
142 name,
143 status: "DONE",
144 }),
145 ),
146 )
147 : get.pipe(
148 // A just-returned operation can briefly 404 on read.
149 Effect.retry({
150 while: (error) => error._tag === "NotFound",
151 times: 5,
152 schedule: Schedule.exponential("250 millis"),
153 }),
154 );
155 return observe;
156 },
157 { budget: "20 minutes" },
158 ).pipe(
159 Effect.map(() => latest),
160 Effect.catchTag("GCP.OperationFailed", (error) => {
161 const reason = (error.reason ?? "").toUpperCase();
162 return reason.endsWith("ALREADY_EXISTS") ||
163 (options?.notFoundOk === true &&
164 (reason === "NOT_FOUND" || reason === "RESOURCE_NOT_FOUND"))
165 ? Effect.succeed(latest)
166 : Effect.fail(error);
167 }),
168 );
169 });
170
171 export const waitUntilExists = <A, E extends { readonly _tag: string }, R>(
172 get: Effect.Effect<A | undefined, E, R>,
173 name: string,
174 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
175 get.pipe(
176 Effect.filterOrFail(
177 (value): value is NonNullable<A> => value != null,
178 () => new ResourceNotResolved({ resourceName: name }),
179 ),
180 Effect.retry({
181 while: (error) => error._tag === "GCP.DeploymentManager.ResourceNotResolved",
182 times: 8,
183 schedule: Schedule.spaced("1 second"),
184 }),
185 );
186
187 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
188 get: Effect.Effect<A | undefined, E, R>,
189 name: string,
190 ): Effect.Effect<void, E | ResourceStillExists, R> =>
191 get.pipe(
192 Effect.filterOrFail(
193 (value) => value === undefined,
194 () => new ResourceStillExists({ resourceName: name }),
195 ),
196 Effect.retry({
197 while: (error) => error._tag === "GCP.DeploymentManager.ResourceStillExists",
198 times: 10,
199 schedule: Schedule.spaced("2 seconds"),
200 }),
201 Effect.asVoid,
202 );
203
204 export const collectPages = <Page, A, E, R>(
205 pages: Stream.Stream<Page, E, R>,
206 items: (page: Page) => readonly A[] | undefined,
207 ) =>
208 pages.pipe(
209 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
210 Stream.runCollect,
211 Effect.map((chunk) => Array.from(chunk)),
212 );
213
214 export const getDeployment = (project: string, deployment: string) =>
215 deploymentmanager
216 .getDeployments({ project, deployment })
217 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
218
219 export const listOwnedDeployments = (project: string) =>
220 collectPages(
221 deploymentmanager.listDeployments.pages({
222 project,
223 maxResults: 500,
224 }),
225 (page) => page.deployments,
226 ).pipe(
227 Effect.map((items) =>
228 items.filter((item) =>
229 Object.keys(labelsToRecord(item.labels)).some((key) => key.startsWith("alchemy-")),
230 ),
231 ),
232 Effect.catchTag("NotFound", () => Effect.succeed([] as deploymentmanager.Deployment[])),
233 );
234
235 export const getManifest = (project: string, deployment: string, manifest: string | undefined) => {
236 if (manifest === undefined || manifest.length === 0) {
237 return Effect.undefined;
238 }
239 return deploymentmanager
240 .getManifests({
241 project,
242 deployment,
243 manifest: lastSegment(manifest),
244 })
245 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
246 };
247
248 export const settleDeployment = (project: string, item: deploymentmanager.Deployment) =>
249 Effect.gen(function* () {
250 const operation = item.operation;
251 if (operation !== undefined && operation.status !== "DONE") {
252 yield* waitForOperation(project, operation, { notFoundOk: true });
253 }
254 });