@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 486 lines 15.7 KB
Raw
1 import * as clouddeploy from "@distilled.cloud/gcp/clouddeploy_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 expandParent,
14 fieldMask,
15 fingerprint,
16 listAtNested,
17 listLabeledPages,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sameBool,
23 sameText,
24 stringMap,
25 stripAutomationRules,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 export type TargetAttribute = {
34 /**
35 * Target id, the last segment of a Target name, or `*` for all
36 * targets in the location.
37 */
38 id?: string;
39 /** Target labels that must match. */
40 labels?: Record<string, string>;
41 };
42
43 export type AutomationResourceSelector = {
44 /** Target attributes the automation applies to. */
45 targets?: TargetAttribute[];
46 };
47
48 export type AdvanceRolloutRule = {
49 /** Unique rule id within the Automation. */
50 id?: string;
51 /** How long to wait after a rollout finishes. */
52 wait?: string;
53 /** Source phases that must match before advancing. */
54 sourcePhases?: string[];
55 };
56
57 export type PromoteReleaseRule = {
58 /** Unique rule id within the Automation. */
59 id?: string;
60 /**
61 * Destination stage id, or `@next` for the next stage in the
62 * promotion flow.
63 */
64 destinationTargetId?: string;
65 /** Starting phase of the created rollout. */
66 destinationPhase?: string;
67 /** How long to wait before promoting. */
68 wait?: string;
69 };
70
71 export type RepairRolloutRule = {
72 /** Unique rule id within the Automation. */
73 id?: string;
74 /** Phases whose failed jobs are repaired. */
75 phases?: string[];
76 /** Repair phases (retry and/or rollback). */
77 repairPhases?: clouddeploy.RepairPhaseConfig[];
78 /** Job names to repair. Empty means all jobs. */
79 jobs?: string[];
80 };
81
82 export type TimedPromoteReleaseRule = {
83 /** Unique rule id within the Automation. */
84 id?: string;
85 /** Crontab schedule (for example `0 9 * * 1`). */
86 schedule?: string;
87 /** Destination stage id, or `@next`. */
88 destinationTargetId?: string;
89 /** Starting phase of the created rollout. */
90 destinationPhase?: string;
91 /** IANA time zone (for example `America/New_York`). */
92 timeZone?: string;
93 };
94
95 export type AutomationRule = {
96 /** Automatically advance a successful rollout. */
97 advanceRolloutRule?: AdvanceRolloutRule;
98 /** Automatically promote a release to the next (or specified) target. */
99 promoteReleaseRule?: PromoteReleaseRule;
100 /** Automatically repair a failed rollout. */
101 repairRolloutRule?: RepairRolloutRule;
102 /** Promote on a cron schedule. */
103 timedPromoteReleaseRule?: TimedPromoteReleaseRule;
104 };
105
106 export type DeliveryPipelinesAutomationProps = {
107 /**
108 * Parent delivery pipeline. Full name
109 * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}`
110 * or the pipeline id (combined with `location`). Immutable — changing
111 * it replaces the automation.
112 */
113 deliveryPipeline: string;
114 /**
115 * Region used when `deliveryPipeline` is a bare id.
116 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
117 */
118 location?: string;
119 /**
120 * Automation id (the `{automation}` segment). If omitted, a unique
121 * RFC1035 name is generated from the stack, stage, and logical id.
122 * Immutable — changing it replaces the automation.
123 */
124 automationId?: string;
125 /**
126 * Email of the user-managed IAM service account that creates Cloud
127 * Deploy release and rollout resources.
128 */
129 serviceAccount: string;
130 /**
131 * Resources the automation applies to.
132 */
133 selector: AutomationResourceSelector;
134 /**
135 * Automation rules. At least one is required.
136 */
137 rules: AutomationRule[];
138 /**
139 * Human-readable description. Max length 255 characters.
140 */
141 description?: string;
142 /**
143 * When true, the automation is deactivated.
144 * @default false
145 */
146 suspended?: boolean;
147 /**
148 * User annotations (not used by Cloud Deploy).
149 */
150 annotations?: Record<string, string>;
151 /**
152 * User labels. Alchemy ownership labels are merged in automatically.
153 */
154 labels?: Record<string, string>;
155 };
156
157 export type DeliveryPipelinesAutomation = Resource<
158 "GCP.CloudDeploy.DeliveryPipelinesAutomation",
159 DeliveryPipelinesAutomationProps,
160 {
161 /** Full resource name. */
162 name: string;
163 /** Automation id (last path segment). */
164 automationId: string;
165 /** Parent delivery pipeline name. */
166 deliveryPipeline: string;
167 /** Project id. */
168 project: string;
169 /** Location id. */
170 location: string;
171 /** Service account email. */
172 serviceAccount: string | undefined;
173 /** Resource selector. */
174 selector: AutomationResourceSelector | undefined;
175 /** Automation rules (output-only conditions stripped). */
176 rules: AutomationRule[];
177 /** Human-readable description. */
178 description: string | undefined;
179 /** Whether the automation is suspended. */
180 suspended: boolean;
181 /** User annotations. */
182 annotations: Record<string, string>;
183 /** User labels (Alchemy ownership labels stripped). */
184 labels: Record<string, string>;
185 /** Server-generated resource uid. */
186 uid: string | undefined;
187 /** RFC3339 creation timestamp. */
188 createTime: string | undefined;
189 /** RFC3339 last-update timestamp. */
190 updateTime: string | undefined;
191 /** Server-computed etag. */
192 etag: string | undefined;
193 },
194 never,
195 Providers
196 >;
197
198 /**
199 * A Cloud Deploy automation attached to a delivery pipeline. Automations
200 * promote releases, repair failed rollouts, and advance rollout phases
201 * without a human in the loop.
202 *
203 * Changing `automationId`, `location`, or `deliveryPipeline` replaces
204 * the automation. Rules, selector, service account, description, labels,
205 * annotations, and `suspended` update in place.
206 *
207 * ### Creating an Automation
208 * **Example:** Promote to the next stage
209 * ```typescript
210 * const automation = yield* GCP.CloudDeploy.DeliveryPipelinesAutomation("Promote", {
211 * deliveryPipeline: pipeline.name,
212 * serviceAccount: "deployer@my-project.iam.gserviceaccount.com",
213 * selector: { targets: [{ id: "*" }] },
214 * rules: [{ promoteReleaseRule: { id: "promote-release" } }],
215 * });
216 * ```
217 *
218 * **Example:** Timed promote
219 * ```typescript
220 * const automation = yield* GCP.CloudDeploy.DeliveryPipelinesAutomation("Nightly", {
221 * deliveryPipeline: pipeline.name,
222 * serviceAccount: "deployer@my-project.iam.gserviceaccount.com",
223 * selector: { targets: [{ id: "staging" }] },
224 * rules: [{
225 * timedPromoteReleaseRule: {
226 * id: "weekday-promote",
227 * schedule: "0 9 * * 1-5",
228 * timeZone: "America/New_York",
229 * },
230 * }],
231 * labels: { env: "prod" },
232 * });
233 * ```
234 *
235 * ### Updating an Automation
236 * Re-declare the same logical id with changed props; the engine keeps the
237 * physical resource and updates it in place.
238 *
239 * **Example:** Description and labels
240 * ```typescript
241 * const automation = yield* GCP.CloudDeploy.DeliveryPipelinesAutomation("Promote", {
242 * deliveryPipeline: pipeline.name,
243 * serviceAccount: "deployer@my-project.iam.gserviceaccount.com",
244 * selector: { targets: [{ id: "*" }] },
245 * rules: [{ promoteReleaseRule: { id: "promote-release" } }],
246 * description: "promote v2",
247 * labels: { env: "prod", team: "platform" },
248 * });
249 * ```
250 *
251 * @resource
252 * @category CloudDeploy
253 */
254 export const DeliveryPipelinesAutomation = Resource<DeliveryPipelinesAutomation>(
255 "GCP.CloudDeploy.DeliveryPipelinesAutomation",
256 );
257
258 const resourceName = (deliveryPipeline: string, automationId: string) =>
259 `${deliveryPipeline}/automations/${automationId}`;
260
261 const toSelector = (
262 value: clouddeploy.AutomationResourceSelector | undefined,
263 ): AutomationResourceSelector | undefined =>
264 value === undefined
265 ? undefined
266 : {
267 targets: value.targets?.map((target) => ({
268 id: target.id,
269 labels: stringMap(target.labels),
270 })),
271 };
272
273 const toAttrs = (item: clouddeploy.Automation, project: string) => {
274 const name = item.name ?? "";
275 const parsed = parseName(name, "automations");
276 return {
277 name,
278 automationId: parsed.id,
279 deliveryPipeline: parsed.parent,
280 project: parsed.project || project,
281 location: parsed.location,
282 serviceAccount: item.serviceAccount,
283 selector: toSelector(item.selector),
284 rules: stripAutomationRules(item.rules),
285 description: item.description,
286 suspended: item.suspended === true,
287 annotations: stringMap(item.annotations),
288 labels: userLabels(item.labels),
289 uid: item.uid,
290 createTime: item.createTime,
291 updateTime: item.updateTime,
292 etag: item.etag,
293 };
294 };
295
296 const getByName = (name: string) =>
297 clouddeploy
298 .getProjectsLocationsDeliveryPipelinesAutomations({ name })
299 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
300
301 const listOwned = (project: string, region: string) =>
302 listAtNested(project, region, "deliveryPipelines/-", (parent) =>
303 listLabeledPages(
304 clouddeploy.listProjectsLocationsDeliveryPipelinesAutomations.pages({
305 parent,
306 pageSize: 1000,
307 }),
308 (page) => page.automations,
309 (item) => item.labels,
310 ),
311 );
312
313 export const DeliveryPipelinesAutomationProvider = () =>
314 Provider.succeed(DeliveryPipelinesAutomation, {
315 stables: [
316 "name",
317 "automationId",
318 "deliveryPipeline",
319 "project",
320 "location",
321 "uid",
322 "createTime",
323 ],
324
325 diff: Effect.fn(function* ({ news, olds, output }) {
326 if (!isResolved(news)) return undefined;
327 const env = yield* GcpEnvironment.current;
328 const location = normalizeLocation(
329 news.location ?? olds?.location ?? output?.location ?? env.region,
330 );
331 const previousParent = olds?.deliveryPipeline ?? output?.deliveryPipeline;
332 const nextParent = expandParent(
333 news.deliveryPipeline,
334 env.project,
335 location,
336 "deliveryPipelines",
337 );
338 return replaceOnIdentity({
339 previousId: olds?.automationId ?? output?.automationId,
340 nextId: news.automationId ?? olds?.automationId ?? output?.automationId,
341 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
342 nextLocation: location,
343 previousParent,
344 nextParent,
345 });
346 }),
347
348 read: Effect.fn(function* ({ id, olds, output }) {
349 const env = yield* GcpEnvironment.current;
350 const automationId = yield* toPhysicalId(
351 id,
352 olds?.automationId,
353 output?.automationId,
354 "automation",
355 );
356 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
357 const deliveryPipeline =
358 output?.deliveryPipeline ??
359 (olds?.deliveryPipeline
360 ? expandParent(olds.deliveryPipeline, env.project, location, "deliveryPipelines")
361 : undefined);
362 const name =
363 output?.name ??
364 (deliveryPipeline ? resourceName(deliveryPipeline, automationId) : undefined);
365 if (name === undefined) return undefined;
366 const existing = yield* getByName(name);
367 if (existing === undefined) return undefined;
368 const attrs = toAttrs(existing, env.project);
369 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
370 }),
371
372 list: () =>
373 Effect.gen(function* () {
374 const env = yield* GcpEnvironment.current;
375 const items = yield* listOwned(env.project, env.region);
376 return items.map((item) => toAttrs(item, env.project));
377 }),
378
379 reconcile: Effect.fn(function* ({ id, news, output }) {
380 const env = yield* GcpEnvironment.current;
381 const automationId = yield* toPhysicalId(
382 id,
383 news.automationId,
384 output?.automationId,
385 "automation",
386 );
387 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
388 const deliveryPipeline = expandParent(
389 news.deliveryPipeline,
390 env.project,
391 location,
392 "deliveryPipelines",
393 );
394 const name = resourceName(deliveryPipeline, automationId);
395 const desiredLabels = {
396 ...toLabels(news.labels),
397 ...(yield* createInternalLabels(id)),
398 };
399 const desiredAnnotations = news.annotations ?? {};
400 const desiredSuspended = news.suspended === true;
401 const desiredRules = stripAutomationRules(news.rules);
402 const desiredSelector = news.selector;
403
404 let current = yield* getByName(output?.name ?? name);
405
406 if (current === undefined) {
407 const created = yield* clouddeploy
408 .createProjectsLocationsDeliveryPipelinesAutomations({
409 parent: deliveryPipeline,
410 automationId,
411 body: {
412 serviceAccount: news.serviceAccount,
413 selector: desiredSelector,
414 rules: desiredRules,
415 description: news.description,
416 suspended: desiredSuspended,
417 annotations: desiredAnnotations,
418 labels: desiredLabels,
419 },
420 })
421 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
422 if (created !== undefined) {
423 yield* waitForOperation(created);
424 }
425 current = yield* waitUntilExists(getByName(name), name);
426 }
427
428 if (current === undefined) {
429 return yield* new ResourceNotResolved({ resourceName: name });
430 }
431
432 const observedLabels = tagRecord(current.labels);
433 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
434 const mask = fieldMask([
435 (upsert.length > 0 || removed.length > 0) && "labels",
436 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
437 "annotations",
438 !sameText(current.description, news.description) && "description",
439 !sameBool(current.suspended, desiredSuspended) && "suspended",
440 !sameText(current.serviceAccount, news.serviceAccount) && "serviceAccount",
441 fingerprint(toSelector(current.selector)) !== fingerprint(desiredSelector) && "selector",
442 fingerprint(stripAutomationRules(current.rules)) !== fingerprint(desiredRules) && "rules",
443 ]);
444
445 if (mask.length > 0) {
446 const operation = yield* clouddeploy.patchProjectsLocationsDeliveryPipelinesAutomations({
447 name: current.name ?? name,
448 updateMask: mask,
449 body: {
450 etag: current.etag,
451 serviceAccount: news.serviceAccount,
452 selector: desiredSelector,
453 rules: desiredRules,
454 description: news.description,
455 suspended: desiredSuspended,
456 annotations: desiredAnnotations,
457 labels: desiredLabels,
458 },
459 });
460 yield* waitForOperation(operation);
461 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
462 }
463
464 return toAttrs(current, env.project);
465 }),
466
467 delete: Effect.fn(function* ({ output }) {
468 const operation = yield* clouddeploy
469 .deleteProjectsLocationsDeliveryPipelinesAutomations({
470 name: output.name,
471 allowMissing: true,
472 })
473 .pipe(
474 Effect.retry({
475 while: (error) => error._tag === "Conflict",
476 times: 8,
477 schedule: Schedule.spaced("2 seconds"),
478 }),
479 Effect.catchTag("NotFound", () => Effect.undefined),
480 );
481 if (operation !== undefined) {
482 yield* waitForOperation(operation, { notFoundOk: true });
483 }
484 yield* waitUntilGone(getByName(output.name), output.name);
485 }),
486 });