@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 382 lines 12.5 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } 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 { waitGlobalOperation } from "./operations.ts";
15
16 const MAX_NAME_LENGTH = 63;
17 const DEFAULT_SCOPE: compute.RolloutPlanLocationScopeEnum = "ZONAL";
18
19 export type RolloutPlanLocationScope = compute.RolloutPlanLocationScopeEnum | (string & {});
20 export type RolloutPlanWave = compute.RolloutPlanWave;
21
22 export type RolloutPlanProps = {
23 /**
24 * Rollout plan name (RFC1035, 1-63 characters). If omitted, a unique
25 * name is generated from the stack, stage, and logical id. Changing the
26 * name replaces the plan.
27 */
28 rolloutPlanName?: string;
29 /**
30 * Optional description. Compute rollout plans have no labels field, so
31 * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`)
32 * is stored in a `[alchemy …]` prefix for `list` / nuke.
33 */
34 description?: string;
35 /**
36 * Location scope of the plan (`ZONAL` or `REGIONAL`). Immutable —
37 * changing it replaces the plan.
38 * @default "ZONAL"
39 */
40 locationScope?: RolloutPlanLocationScope;
41 /**
42 * Waves that divide the rollout. The Compute API has no update method
43 * for rollout plans — changing waves replaces the plan.
44 */
45 waves?: ReadonlyArray<RolloutPlanWave>;
46 };
47
48 export type RolloutPlan = Resource<
49 "GCP.Compute.RolloutPlan",
50 RolloutPlanProps,
51 {
52 /** Rollout plan name. */
53 rolloutPlanName: string;
54 /** Server-assigned numeric id. */
55 rolloutPlanId: string | undefined;
56 /** Project id. */
57 project: string;
58 /** User description with the Alchemy ownership prefix stripped. */
59 description: string | undefined;
60 /** Location scope (`ZONAL` or `REGIONAL`). */
61 locationScope: string | undefined;
62 /** Waves in this plan. */
63 waves: ReadonlyArray<RolloutPlanWave>;
64 /** Compute Engine self-link. */
65 selfLink: string | undefined;
66 /** RFC3339 creation timestamp. */
67 creationTimestamp: string | undefined;
68 },
69 never,
70 Providers
71 >;
72
73 /**
74 * A project-global Compute Engine rollout plan.
75 *
76 * Rollout plans divide a large change (for example a global VM extension
77 * policy) into waves. Compute Engine has no labels and no update method on
78 * this resource, so Alchemy stamps ownership into the description and
79 * treats name, scope, description, and waves as replacement triggers.
80 *
81 * ### Creating a Rollout Plan
82 * **Example:** Single-wave zonal plan
83 * ```typescript
84 * const plan = yield* GCP.Compute.RolloutPlan("Fleet", {
85 * waves: [
86 * {
87 * displayName: "central",
88 * selectors: [
89 * {
90 * locationSelector: {
91 * includedLocations: ["us-central1-a"],
92 * },
93 * },
94 * ],
95 * validation: {
96 * type: "time",
97 * timeBasedValidationMetadata: { waitDuration: "0s" },
98 * },
99 * },
100 * ],
101 * });
102 * ```
103 *
104 * **Example:** Named plan with a description
105 * ```typescript
106 * const plan = yield* GCP.Compute.RolloutPlan("Fleet", {
107 * rolloutPlanName: "ops-agent-rollout",
108 * description: "ops-agent canary",
109 * locationScope: "ZONAL",
110 * waves: [
111 * {
112 * selectors: [
113 * {
114 * locationSelector: {
115 * includedLocations: ["us-central1-a", "us-central1-b"],
116 * },
117 * },
118 * ],
119 * validation: { type: "manual" },
120 * },
121 * ],
122 * });
123 * ```
124 *
125 * @resource
126 * @category Compute
127 */
128 export const RolloutPlan = Resource<RolloutPlan>("GCP.Compute.RolloutPlan");
129
130 export class RolloutPlanNotResolved extends Data.TaggedError("GCP.Compute.RolloutPlanNotResolved")<{
131 rolloutPlanName: string;
132 }> {}
133
134 export class RolloutPlanStillExists extends Data.TaggedError("GCP.Compute.RolloutPlanStillExists")<{
135 rolloutPlanName: string;
136 }> {}
137
138 const defaultWaves = (): compute.RolloutPlanWave[] => [
139 {
140 displayName: "default",
141 selectors: [
142 {
143 locationSelector: {
144 includedLocations: ["us-central1-a"],
145 },
146 },
147 ],
148 validation: {
149 type: "time",
150 timeBasedValidationMetadata: { waitDuration: "0s" },
151 },
152 },
153 ];
154
155 const toName = (id: string, name: string | undefined, existing?: string) =>
156 Effect.gen(function* () {
157 if (name !== undefined) return name;
158 if (existing !== undefined) return existing;
159 const generated = yield* createPhysicalName({
160 id,
161 maxLength: MAX_NAME_LENGTH,
162 lowercase: true,
163 });
164 return /^[a-z]/.test(generated) ? generated : `p${generated}`.slice(0, MAX_NAME_LENGTH);
165 });
166
167 const encodeDescription = (
168 labels: Record<string, string>,
169 description: string | undefined,
170 ): string => {
171 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
172 return description ? `${marker}\n${description}` : marker;
173 };
174
175 const parseDescription = (
176 description: string | undefined,
177 ): {
178 labels: Record<string, string>;
179 description: string | undefined;
180 } => {
181 if (!description?.startsWith("[alchemy ")) {
182 return { labels: {}, description };
183 }
184 const end = description.indexOf("]");
185 if (end < 0) return { labels: {}, description };
186 const labels: Record<string, string> = {};
187 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
188 const eq = part.indexOf("=");
189 if (eq > 0) {
190 labels[part.slice(0, eq)] = part.slice(eq + 1);
191 }
192 }
193 const rest = description.slice(end + 1).replace(/^\n/, "");
194 return { labels, description: rest.length > 0 ? rest : undefined };
195 };
196
197 const hasOwnershipMarker = (description: string | undefined) =>
198 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
199
200 const sameJson = (left: unknown, right: unknown) =>
201 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
202
203 const toBody = (
204 rolloutPlanName: string,
205 props: RolloutPlanProps,
206 ownership: Record<string, string>,
207 ): compute.RolloutPlan => ({
208 name: rolloutPlanName,
209 description: encodeDescription(ownership, props.description),
210 locationScope: props.locationScope ?? DEFAULT_SCOPE,
211 waves: [...(props.waves ?? defaultWaves())],
212 });
213
214 const toAttrs = (plan: compute.RolloutPlan, project: string): RolloutPlan["Attributes"] => {
215 const parsed = parseDescription(plan.description);
216 return {
217 rolloutPlanName: plan.name ?? plan.id ?? "",
218 rolloutPlanId: plan.id,
219 project,
220 description: parsed.description,
221 locationScope: plan.locationScope,
222 waves: plan.waves ?? [],
223 selfLink: plan.selfLink,
224 creationTimestamp: plan.creationTimestamp,
225 };
226 };
227
228 const getByName = (project: string, rolloutPlan: string) =>
229 compute
230 .getRolloutPlans({ project, rolloutPlan })
231 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
232
233 const waitPlanGone = (project: string, rolloutPlanName: string) =>
234 getByName(project, rolloutPlanName).pipe(
235 Effect.flatMap((plan) =>
236 plan === undefined
237 ? Effect.void
238 : Effect.fail(
239 new RolloutPlanStillExists({
240 rolloutPlanName,
241 }),
242 ),
243 ),
244 Effect.retry({
245 while: (error) => error instanceof RolloutPlanStillExists,
246 times: 10,
247 schedule: Schedule.spaced("2 seconds"),
248 }),
249 );
250
251 export const RolloutPlanProvider = () =>
252 Provider.succeed(RolloutPlan, {
253 stables: ["rolloutPlanName", "rolloutPlanId", "project", "selfLink", "creationTimestamp"],
254
255 diff: Effect.fn(function* ({ news, olds, output }) {
256 if (!isResolved(news)) return undefined;
257
258 const previousName = olds?.rolloutPlanName ?? output?.rolloutPlanName;
259 const nextName = news.rolloutPlanName ?? previousName;
260 const nameChanged =
261 previousName !== undefined && nextName !== undefined && previousName !== nextName;
262
263 const previousScope = olds?.locationScope ?? output?.locationScope ?? DEFAULT_SCOPE;
264 const nextScope = news.locationScope ?? DEFAULT_SCOPE;
265 const previousWaves = olds?.waves ?? output?.waves;
266 const nextWaves = news.waves;
267 const wavesChanged =
268 nextWaves !== undefined &&
269 previousWaves !== undefined &&
270 !sameJson(previousWaves, nextWaves);
271 const previousDescription = olds?.description ?? output?.description;
272 const descriptionChanged =
273 news.description !== undefined &&
274 previousDescription !== undefined &&
275 news.description !== previousDescription;
276
277 if (nameChanged || previousScope !== nextScope || wavesChanged) {
278 return {
279 action: "replace" as const,
280 deleteFirst: !nameChanged,
281 };
282 }
283 if (descriptionChanged) {
284 return { action: "replace" as const, deleteFirst: true };
285 }
286 return undefined;
287 }),
288
289 read: Effect.fn(function* ({ id, olds, output, previous }) {
290 const env = yield* GcpEnvironment.current;
291 const rolloutPlanName = yield* toName(id, olds?.rolloutPlanName, output?.rolloutPlanName);
292 const existing = yield* getByName(env.project, rolloutPlanName);
293 if (existing === undefined) return undefined;
294 const attrs = toAttrs(existing, env.project);
295 const { labels } = parseDescription(existing.description);
296 return (yield* hasAlchemyLabels(id, labels))
297 ? attrs
298 : unownedUnlessPrevious(attrs, previous, "rolloutPlanName");
299 }),
300
301 list: () =>
302 Effect.gen(function* () {
303 const env = yield* GcpEnvironment.current;
304 return yield* compute.listRolloutPlans
305 .items({
306 project: env.project,
307 maxResults: 500,
308 returnPartialSuccess: true,
309 })
310 .pipe(
311 Stream.filter((plan) => hasOwnershipMarker(plan.description)),
312 Stream.map((plan) => toAttrs(plan, env.project)),
313 Stream.runCollect,
314 Effect.map((chunk) => Array.from(chunk)),
315 Effect.catchTag("NotFound", () => Effect.succeed([])),
316 );
317 }),
318
319 reconcile: Effect.fn(function* ({ id, news, output }) {
320 const env = yield* GcpEnvironment.current;
321 const rolloutPlanName = yield* toName(id, news.rolloutPlanName, output?.rolloutPlanName);
322 const ownership = yield* createInternalLabels(id);
323 const desired = toBody(rolloutPlanName, news, ownership);
324
325 let current = yield* getByName(env.project, rolloutPlanName);
326
327 if (current === undefined) {
328 const inserted = yield* compute
329 .insertRolloutPlans({
330 project: env.project,
331 body: desired,
332 })
333 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
334 if (inserted !== undefined) {
335 yield* waitGlobalOperation(env.project, inserted, {
336 ignore: ["RESOURCE_ALREADY_EXISTS"],
337 });
338 }
339 current = yield* getByName(env.project, rolloutPlanName).pipe(
340 Effect.filterOrFail(
341 (plan): plan is compute.RolloutPlan => plan !== undefined,
342 () => new RolloutPlanNotResolved({ rolloutPlanName }),
343 ),
344 Effect.retry({
345 while: (error) => error._tag === "GCP.Compute.RolloutPlanNotResolved",
346 times: 8,
347 schedule: Schedule.spaced("1 second"),
348 }),
349 );
350 }
351
352 if (current === undefined) {
353 return yield* new RolloutPlanNotResolved({ rolloutPlanName });
354 }
355
356 return toAttrs(current, env.project);
357 }),
358
359 delete: Effect.fn(function* ({ output }) {
360 const env = yield* GcpEnvironment.current;
361 const project = output.project || env.project;
362 const deleted = yield* compute
363 .deleteRolloutPlans({
364 project,
365 rolloutPlan: output.rolloutPlanName,
366 })
367 .pipe(
368 Effect.catchTag("NotFound", () => Effect.undefined),
369 Effect.retry({
370 while: (error) => error._tag === "Conflict",
371 times: 8,
372 schedule: Schedule.spaced("2 seconds"),
373 }),
374 );
375 if (deleted !== undefined) {
376 yield* waitGlobalOperation(project, deleted, {
377 ignore: ["RESOURCE_NOT_FOUND"],
378 });
379 }
380 yield* waitPlanGone(project, output.rolloutPlanName);
381 }),
382 });