@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 437 lines 15.4 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitRegionOperation } from "./operations.ts";
15
16 export type RegionInstantSnapshotGroupProps = {
17 /**
18 * Instant snapshot group name (RFC1035, 1-63 characters). If omitted, a
19 * unique name is generated from the stack, stage, and logical id.
20 * Changing it replaces the group.
21 */
22 instantSnapshotGroupName?: string;
23 /**
24 * Region the group lives in (e.g. `us-central1`). Immutable — changing
25 * it replaces the group. `US-CENTRAL1` is accepted and normalized to
26 * `us-central1`.
27 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
28 */
29 region?: string;
30 /**
31 * Disk consistency-group resource policy used as the source. Accepts a
32 * ResourcePolicy self-link, a
33 * `projects/{project}/regions/{region}/resourcePolicies/{name}` path, or
34 * the policy name. Immutable — changing it replaces the group. Member
35 * disks must already be attached to the consistency group.
36 */
37 sourceConsistencyGroup: string;
38 /**
39 * Optional description. Instant snapshot groups have no labels field
40 * and no update API, so Alchemy ownership is stored in a `[alchemy …]`
41 * prefix and any description change replaces the group.
42 */
43 description?: string;
44 };
45
46 export type RegionInstantSnapshotGroup = Resource<
47 "GCP.Compute.RegionInstantSnapshotGroup",
48 RegionInstantSnapshotGroupProps,
49 {
50 /** Instant snapshot group name. */
51 instantSnapshotGroupName: string;
52 /** Server-assigned numeric id. */
53 instantSnapshotGroupId: string | undefined;
54 /** Project id. */
55 project: string;
56 /** Region short name (`us-central1`). */
57 region: string;
58 /** Source consistency-group resource policy URL. */
59 sourceConsistencyGroup: string | undefined;
60 /** User description with the Alchemy ownership prefix stripped. */
61 description: string | undefined;
62 /** Server-reported status (`READY`, `CREATING`, …). */
63 status: string | undefined;
64 /** Server-defined URL. */
65 selfLink: string | undefined;
66 /** Server-defined URL including the resource id. */
67 selfLinkWithId: string | undefined;
68 /** RFC3339 creation timestamp. */
69 creationTimestamp: string | undefined;
70 /** Resource kind. */
71 kind: string | undefined;
72 },
73 never,
74 Providers
75 >;
76
77 /**
78 * A regional Compute Engine instant snapshot group.
79 *
80 * An instant snapshot group is a crash-consistent set of instant snapshots
81 * taken from every disk in a disk consistency group (a ResourcePolicy
82 * with `diskConsistencyGroupPolicy`). There is no update API and no
83 * labels field — Alchemy stamps ownership into the description so nuke
84 * can find leaked groups, and every user-facing field change replaces
85 * the resource.
86 *
87 * ### Creating a Regional Instant Snapshot Group
88 * **Example:** Snapshot a consistency group
89 * ```typescript
90 * const policy = yield* GCP.Compute.ResourcePolicy("cg", {
91 * region: "us-central1",
92 * diskConsistencyGroupPolicy: {},
93 * });
94 * const group = yield* GCP.Compute.RegionInstantSnapshotGroup("ckpt", {
95 * region: "us-central1",
96 * sourceConsistencyGroup: policy.resourcePolicyName,
97 * });
98 * ```
99 *
100 * @resource
101 * @category Compute
102 */
103 export const RegionInstantSnapshotGroup = Resource<RegionInstantSnapshotGroup>(
104 "GCP.Compute.RegionInstantSnapshotGroup",
105 );
106
107 export class RegionInstantSnapshotGroupNotResolved extends Data.TaggedError(
108 "GCP.Compute.RegionInstantSnapshotGroupNotResolved",
109 )<{
110 instantSnapshotGroupName: string;
111 region: string;
112 }> {}
113
114 export class RegionInstantSnapshotGroupNotReady extends Data.TaggedError(
115 "GCP.Compute.RegionInstantSnapshotGroupNotReady",
116 )<{
117 instantSnapshotGroupName: string;
118 status: string;
119 }> {}
120
121 export class RegionInstantSnapshotGroupFailed extends Data.TaggedError(
122 "GCP.Compute.RegionInstantSnapshotGroupFailed",
123 )<{
124 instantSnapshotGroupName: string;
125 status: string;
126 }> {}
127
128 export class RegionInstantSnapshotGroupStillExists extends Data.TaggedError(
129 "GCP.Compute.RegionInstantSnapshotGroupStillExists",
130 )<{
131 instantSnapshotGroupName: string;
132 status: string;
133 }> {}
134
135 const lastSegment = (value: string | undefined): string => {
136 if (value === undefined || value.length === 0) return "";
137 const trimmed = value.replace(/\/+$/, "");
138 const parts = trimmed.split("/");
139 return parts[parts.length - 1] || trimmed;
140 };
141
142 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
143 lastSegment(region ?? defaultRegion).toLowerCase();
144
145 const toName = (id: string, name: string | undefined, existing?: string) =>
146 Effect.gen(function* () {
147 if (name !== undefined) return name;
148 if (existing !== undefined) return existing;
149 const generated = yield* createPhysicalName({
150 id,
151 maxLength: 63,
152 lowercase: true,
153 });
154 return /^[a-z]/.test(generated) ? generated : `g${generated}`.slice(0, 63);
155 });
156
157 const encodeDescription = (
158 labels: Record<string, string>,
159 description: string | undefined,
160 ): string => {
161 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
162 return description ? `${marker}\n${description}` : marker;
163 };
164
165 const parseDescription = (
166 description: string | undefined,
167 ): {
168 labels: Record<string, string>;
169 description: string | undefined;
170 } => {
171 if (!description?.startsWith("[alchemy ")) {
172 return { labels: {}, description };
173 }
174 const end = description.indexOf("]");
175 if (end < 0) return { labels: {}, description };
176 const labels: Record<string, string> = {};
177 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
178 const eq = part.indexOf("=");
179 if (eq > 0) {
180 labels[part.slice(0, eq)] = part.slice(eq + 1);
181 }
182 }
183 const rest = description.slice(end + 1).replace(/^\n/, "");
184 return { labels, description: rest.length > 0 ? rest : undefined };
185 };
186
187 const hasOwnershipMarker = (description: string | undefined) =>
188 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
189
190 const toPolicyRef = (project: string, region: string, policy: string): string => {
191 if (policy.includes("/")) return policy;
192 return `projects/${project}/regions/${region}/resourcePolicies/${policy}`;
193 };
194
195 const canonicalizePolicy = (value: string | undefined): string => {
196 if (value === undefined || value.length === 0) return "";
197 const cleaned = value.split("?")[0] ?? value;
198 const match = cleaned.match(/(regions\/[^/]+\/resourcePolicies\/[^/]+)$/);
199 if (match?.[1] !== undefined) return match[1];
200 return lastSegment(cleaned);
201 };
202
203 const toAttrs = (group: compute.InstantSnapshotGroup, project: string) => {
204 const parsed = parseDescription(group.description);
205 return {
206 instantSnapshotGroupName: group.name ?? group.id ?? "",
207 instantSnapshotGroupId: group.id,
208 project,
209 region: lastSegment(group.region).toLowerCase(),
210 sourceConsistencyGroup: group.sourceConsistencyGroup,
211 description: parsed.description,
212 status: group.status,
213 selfLink: group.selfLink,
214 selfLinkWithId: group.selfLinkWithId,
215 creationTimestamp: group.creationTimestamp,
216 kind: group.kind,
217 };
218 };
219
220 const getByName = (project: string, region: string, instantSnapshotGroup: string) =>
221 compute
222 .getRegionInstantSnapshotGroups({
223 project,
224 region,
225 instantSnapshotGroup,
226 })
227 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
228
229 const waitReady = (project: string, region: string, instantSnapshotGroupName: string) =>
230 getByName(project, region, instantSnapshotGroupName).pipe(
231 Effect.flatMap((group) =>
232 group?.status === "FAILED" || group?.status === "INVALID"
233 ? Effect.fail(
234 new RegionInstantSnapshotGroupFailed({
235 instantSnapshotGroupName,
236 status: group.status ?? "FAILED",
237 }),
238 )
239 : Effect.succeed(group),
240 ),
241 Effect.filterOrFail(
242 (group): group is compute.InstantSnapshotGroup =>
243 group !== undefined && group.status === "READY",
244 (group) =>
245 new RegionInstantSnapshotGroupNotReady({
246 instantSnapshotGroupName,
247 status: group?.status ?? "MISSING",
248 }),
249 ),
250 Effect.retry({
251 while: (error) => error._tag === "GCP.Compute.RegionInstantSnapshotGroupNotReady",
252 times: 10,
253 schedule: Schedule.spaced("2 seconds"),
254 }),
255 );
256
257 const waitGone = (project: string, region: string, instantSnapshotGroupName: string) =>
258 getByName(project, region, instantSnapshotGroupName).pipe(
259 Effect.flatMap((group) =>
260 group === undefined
261 ? Effect.void
262 : Effect.fail(
263 new RegionInstantSnapshotGroupStillExists({
264 instantSnapshotGroupName,
265 status: group.status ?? "UNKNOWN",
266 }),
267 ),
268 ),
269 Effect.retry({
270 while: (error) => error instanceof RegionInstantSnapshotGroupStillExists,
271 times: 10,
272 schedule: Schedule.spaced("2 seconds"),
273 }),
274 );
275
276 export const RegionInstantSnapshotGroupProvider = () =>
277 Provider.succeed(RegionInstantSnapshotGroup, {
278 stables: [
279 "instantSnapshotGroupName",
280 "instantSnapshotGroupId",
281 "project",
282 "region",
283 "sourceConsistencyGroup",
284 "selfLink",
285 "creationTimestamp",
286 ],
287
288 diff: Effect.fn(function* ({ news, olds, output }) {
289 if (!isResolved(news)) return undefined;
290 const env = yield* GcpEnvironment.current;
291
292 const previousName = olds?.instantSnapshotGroupName ?? output?.instantSnapshotGroupName;
293 const nextName = news.instantSnapshotGroupName ?? previousName;
294 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
295 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
296 const previousSource = canonicalizePolicy(
297 olds?.sourceConsistencyGroup ?? output?.sourceConsistencyGroup,
298 );
299 const nextSource = canonicalizePolicy(news.sourceConsistencyGroup);
300 const previousDescription = olds?.description ?? output?.description ?? "";
301 const nextDescription = news.description ?? "";
302
303 const replace =
304 previousRegion !== nextRegion ||
305 (previousName !== undefined && nextName !== undefined && previousName !== nextName) ||
306 (nextSource.length > 0 && previousSource.length > 0 && previousSource !== nextSource) ||
307 previousDescription !== nextDescription;
308
309 if (!replace) return undefined;
310 return {
311 action: "replace" as const,
312 deleteFirst:
313 previousRegion === nextRegion &&
314 previousName !== undefined &&
315 nextName !== undefined &&
316 previousName === nextName,
317 };
318 }),
319
320 read: Effect.fn(function* ({ id, olds, output }) {
321 const env = yield* GcpEnvironment.current;
322 const instantSnapshotGroupName = yield* toName(
323 id,
324 olds?.instantSnapshotGroupName,
325 output?.instantSnapshotGroupName,
326 );
327 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
328 const existing = yield* getByName(env.project, region, instantSnapshotGroupName);
329 if (existing === undefined) return undefined;
330 const attrs = toAttrs(existing, env.project);
331 const { labels } = parseDescription(existing.description);
332 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
333 }),
334
335 list: () =>
336 Effect.gen(function* () {
337 const env = yield* GcpEnvironment.current;
338 return yield* compute.listRegionInstantSnapshotGroups
339 .items({
340 project: env.project,
341 region: env.region,
342 maxResults: 500,
343 returnPartialSuccess: true,
344 })
345 .pipe(
346 Stream.filter((group) => hasOwnershipMarker(group.description)),
347 Stream.map((group) => toAttrs(group, env.project)),
348 Stream.runCollect,
349 Effect.map((chunk) => Array.from(chunk)),
350 );
351 }),
352
353 reconcile: Effect.fn(function* ({ id, news, output }) {
354 const env = yield* GcpEnvironment.current;
355 const instantSnapshotGroupName = yield* toName(
356 id,
357 news.instantSnapshotGroupName,
358 output?.instantSnapshotGroupName,
359 );
360 const region = normalizeRegion(news.region ?? output?.region, env.region);
361 const ownership = yield* createInternalLabels(id);
362 const desiredDescription = encodeDescription(ownership, news.description);
363 const desiredSource = toPolicyRef(env.project, region, news.sourceConsistencyGroup);
364
365 let current = yield* getByName(env.project, region, instantSnapshotGroupName);
366 if (current?.status === "DELETING") {
367 yield* waitGone(env.project, region, instantSnapshotGroupName);
368 current = undefined;
369 }
370
371 if (current === undefined) {
372 const inserted = yield* compute
373 .insertRegionInstantSnapshotGroups({
374 project: env.project,
375 region,
376 sourceConsistencyGroup: desiredSource,
377 body: {
378 name: instantSnapshotGroupName,
379 description: desiredDescription,
380 sourceConsistencyGroup: desiredSource,
381 },
382 })
383 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
384 if (inserted !== undefined) {
385 yield* waitRegionOperation(env.project, region, inserted, {
386 ignore: ["RESOURCE_ALREADY_EXISTS"],
387 });
388 }
389 current = yield* waitReady(env.project, region, instantSnapshotGroupName);
390 }
391
392 if (current === undefined) {
393 return yield* new RegionInstantSnapshotGroupNotResolved({
394 instantSnapshotGroupName,
395 region,
396 });
397 }
398
399 if (current.status !== "READY") {
400 current = yield* waitReady(env.project, region, instantSnapshotGroupName);
401 }
402
403 if (current === undefined) {
404 return yield* new RegionInstantSnapshotGroupNotResolved({
405 instantSnapshotGroupName,
406 region,
407 });
408 }
409
410 return toAttrs(current, env.project);
411 }),
412
413 delete: Effect.fn(function* ({ output }) {
414 const env = yield* GcpEnvironment.current;
415 const region = normalizeRegion(output.region, env.region);
416 const deleted = yield* compute
417 .deleteRegionInstantSnapshotGroups({
418 project: output.project,
419 region,
420 instantSnapshotGroup: output.instantSnapshotGroupName,
421 })
422 .pipe(
423 Effect.catchTag("NotFound", () => Effect.undefined),
424 Effect.retry({
425 while: (error) => error._tag === "Conflict",
426 times: 8,
427 schedule: Schedule.spaced("2 seconds"),
428 }),
429 );
430 if (deleted !== undefined) {
431 yield* waitRegionOperation(output.project, region, deleted, {
432 ignore: ["RESOURCE_NOT_FOUND"],
433 });
434 }
435 yield* waitGone(output.project, region, output.instantSnapshotGroupName);
436 }),
437 });