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

main
ts 474 lines 15.4 KB
Raw
1 import * as saasservicemgmt from "@distilled.cloud/gcp/saasservicemgmt_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 ResourceNotResolved,
14 collectPages,
15 expandName,
16 fieldMask,
17 fingerprint,
18 hasAlchemyLabelKeys,
19 lastSegment,
20 normalizeLocation,
21 parentOf,
22 parseName,
23 replaceOnIdentity,
24 resourceName,
25 sameRef,
26 toPhysicalId,
27 userAnnotations,
28 userLabels,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 const COLLECTION = "unitOperations";
33
34 export type UnitOperationVariable = {
35 type?: saasservicemgmt.UnitVariableTypeEnum | (string & {});
36 value?: string;
37 variable?: string;
38 };
39
40 export type UnitOperationProvision = {
41 /** Release to provision. Accepts a release id or full resource name. */
42 release?: string;
43 /** Input variables. Maximum 100. */
44 inputVariables?: UnitOperationVariable[];
45 };
46
47 export type UnitOperationFlagUpdate = {
48 /** Flag release to apply. */
49 flagRelease?: string;
50 };
51
52 export type UnitOperationSchedule = {
53 /** RFC3339 start time. If omitted, the next maintenance window is used. */
54 startTime?: string;
55 };
56
57 export type UnitOperationCondition = {
58 status: string | undefined;
59 type: string | undefined;
60 message: string | undefined;
61 reason: string | undefined;
62 lastTransitionTime: string | undefined;
63 };
64
65 export type UnitOperationProps = {
66 /**
67 * UnitOperation id (the `{unitOperation}` segment of
68 * `projects/{project}/locations/{location}/unitOperations/{unitOperation}`).
69 * If omitted, a unique RFC1035 name is generated. Immutable —
70 * changing it replaces the operation.
71 */
72 unitOperationId?: string;
73 /**
74 * Region of the operation (`us-central1`, …). Immutable — changing it
75 * replaces the operation. `US-CENTRAL1` is accepted and normalized to
76 * `us-central1`.
77 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
78 */
79 location?: string;
80 /**
81 * Unit this operation acts on. Accepts a unit id or a full resource
82 * name. Immutable — changing it replaces the operation.
83 */
84 unit: string;
85 /**
86 * Provision the unit. Mutually exclusive with `upgrade`,
87 * `deprovision`, and `flagUpdate`. Immutable.
88 */
89 provision?: UnitOperationProvision;
90 /**
91 * Upgrade a provisioned unit. Mutually exclusive with the other
92 * operation types. Immutable.
93 */
94 upgrade?: UnitOperationProvision;
95 /**
96 * Deprovision a provisioned unit. Mutually exclusive with the other
97 * operation types. Immutable.
98 */
99 deprovision?: boolean;
100 /**
101 * Push a flag release. Mutually exclusive with the other operation
102 * types. Immutable.
103 */
104 flagUpdate?: UnitOperationFlagUpdate;
105 /**
106 * Parent unit operation, for tracing child work.
107 */
108 parentUnitOperation?: string;
109 /**
110 * Rollout that created this operation. Filtering only.
111 */
112 rollout?: string;
113 /**
114 * When to run the operation.
115 */
116 schedule?: UnitOperationSchedule;
117 /**
118 * Request cancellation. May fail if the operation is already
119 * executing.
120 */
121 cancel?: boolean;
122 /**
123 * User labels. Alchemy ownership labels are merged in automatically.
124 */
125 labels?: Record<string, string>;
126 /**
127 * Unstructured annotations preserved across updates.
128 */
129 annotations?: Record<string, string>;
130 };
131
132 export type UnitOperation = Resource<
133 "GCP.SaasServiceManagement.UnitOperation",
134 UnitOperationProps,
135 {
136 /** Full resource name `projects/{project}/locations/{location}/unitOperations/{unitOperation}`. */
137 name: string;
138 /** UnitOperation id (last path segment). */
139 unitOperationId: string;
140 /** Project id. */
141 project: string;
142 /** Location id. */
143 location: string;
144 /** Unit resource name. */
145 unit: string | undefined;
146 /** Unit id (last path segment). */
147 unitId: string | undefined;
148 /** Provision payload, if this is a provision. */
149 provision: UnitOperationProvision | undefined;
150 /** Upgrade payload, if this is an upgrade. */
151 upgrade: UnitOperationProvision | undefined;
152 /** Whether this is a deprovision. */
153 deprovision: boolean;
154 /** Flag-update payload, if this is a flag update. */
155 flagUpdate: UnitOperationFlagUpdate | undefined;
156 /** Parent unit operation. */
157 parentUnitOperation: string | undefined;
158 /** Creating rollout. */
159 rollout: string | undefined;
160 /** Scheduled start. */
161 schedule: UnitOperationSchedule | undefined;
162 /** Cancellation requested. */
163 cancel: boolean;
164 /** Lifecycle state. */
165 state: string | undefined;
166 /** Engine state (opaque). */
167 engineState: string | undefined;
168 /** Error category. */
169 errorCategory: string | undefined;
170 /** Conditions. */
171 conditions: UnitOperationCondition[];
172 /** User labels (Alchemy ownership labels stripped). */
173 labels: Record<string, string>;
174 /** User annotations. */
175 annotations: Record<string, string>;
176 /** Server UUID. */
177 uid: string | undefined;
178 /** Server etag. */
179 etag: string | undefined;
180 /** RFC3339 creation timestamp. */
181 createTime: string | undefined;
182 /** RFC3339 last-update timestamp. */
183 updateTime: string | undefined;
184 },
185 never,
186 Providers
187 >;
188
189 /**
190 * An App Lifecycle Manager unit operation — one provision, upgrade,
191 * deprovision, or flag-update of a Unit.
192 *
193 * `unitOperationId`, `location`, `unit`, and the chosen operation type
194 * replace the resource. `cancel`, labels, and annotations update in
195 * place. Only one mutating unit operation runs on a unit at a time.
196 *
197 * ### Creating a UnitOperation
198 * **Example:** Provision a unit
199 * ```typescript
200 * const op = yield* GCP.SaasServiceManagement.UnitOperation("Provision", {
201 * unit: unit.name,
202 * provision: { release: release.name },
203 * labels: { env: "prod" },
204 * });
205 * ```
206 *
207 * **Example:** Deprovision
208 * ```typescript
209 * const op = yield* GCP.SaasServiceManagement.UnitOperation("Teardown", {
210 * unit: unit.name,
211 * deprovision: true,
212 * });
213 * ```
214 *
215 * ### Updating a UnitOperation
216 * **Example:** Cancel
217 * ```typescript
218 * const op = yield* GCP.SaasServiceManagement.UnitOperation("Provision", {
219 * unitOperationId: op.unitOperationId,
220 * unit: unit.name,
221 * provision: { release: release.name },
222 * cancel: true,
223 * });
224 * ```
225 *
226 * @resource
227 * @category SaasServiceManagement
228 */
229 export const UnitOperation = Resource<UnitOperation>("GCP.SaasServiceManagement.UnitOperation");
230
231 const operationKind = (props: {
232 provision?: UnitOperationProvision;
233 upgrade?: UnitOperationProvision;
234 deprovision?: boolean;
235 flagUpdate?: UnitOperationFlagUpdate;
236 }) => {
237 if (props.provision !== undefined) return "provision";
238 if (props.upgrade !== undefined) return "upgrade";
239 if (props.deprovision === true) return "deprovision";
240 if (props.flagUpdate !== undefined) return "flagUpdate";
241 return "";
242 };
243
244 const expandProvision = (
245 provision: UnitOperationProvision | undefined,
246 project: string,
247 location: string,
248 ): saasservicemgmt.Provision | undefined => {
249 if (provision === undefined) return undefined;
250 return {
251 release:
252 provision.release === undefined
253 ? undefined
254 : expandName(provision.release, project, location, "releases"),
255 inputVariables: provision.inputVariables,
256 };
257 };
258
259 const toAttrs = (item: saasservicemgmt.UnitOperation, project: string) => {
260 const name = item.name ?? "";
261 const parsed = parseName(name, COLLECTION);
262 return {
263 name,
264 unitOperationId: parsed.id,
265 project: parsed.project || project,
266 location: parsed.location,
267 unit: item.unit,
268 unitId: item.unit ? lastSegment(item.unit) : undefined,
269 provision: item.provision,
270 upgrade: item.upgrade,
271 deprovision: item.deprovision !== undefined,
272 flagUpdate: item.flagUpdate,
273 parentUnitOperation: item.parentUnitOperation,
274 rollout: item.rollout,
275 schedule: item.schedule,
276 cancel: item.cancel === true,
277 state: item.state,
278 engineState: item.engineState,
279 errorCategory: item.errorCategory,
280 conditions: (item.conditions ?? []).map((condition) => ({
281 status: condition.status,
282 type: condition.type,
283 message: condition.message,
284 reason: condition.reason,
285 lastTransitionTime: condition.lastTransitionTime,
286 })),
287 labels: userLabels(item.labels),
288 annotations: userAnnotations(item.annotations),
289 uid: item.uid,
290 etag: item.etag,
291 createTime: item.createTime,
292 updateTime: item.updateTime,
293 };
294 };
295
296 const getByName = (name: string) =>
297 name.length === 0
298 ? Effect.undefined
299 : saasservicemgmt
300 .getProjectsLocationsUnitOperations({ name })
301 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
302
303 const listOwned = (project: string, location: string) =>
304 collectPages(
305 saasservicemgmt.listProjectsLocationsUnitOperations.pages({
306 parent: parentOf(project, "-"),
307 pageSize: 1000,
308 }),
309 (page) => page.unitOperations,
310 ).pipe(
311 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
312 Effect.flatMap((items) =>
313 items.length > 0
314 ? Effect.succeed(items)
315 : collectPages(
316 saasservicemgmt.listProjectsLocationsUnitOperations.pages({
317 parent: parentOf(project, location),
318 pageSize: 1000,
319 }),
320 (page) => page.unitOperations,
321 ).pipe(
322 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
323 ),
324 ),
325 );
326
327 export const UnitOperationProvider = () =>
328 Provider.succeed(UnitOperation, {
329 stables: ["name", "unitOperationId", "project", "location", "unitId", "uid", "createTime"],
330
331 diff: Effect.fn(function* ({ news, olds, output }) {
332 if (!isResolved(news)) return undefined;
333 const env = yield* GcpEnvironment.current;
334 const previousKind = operationKind({
335 provision: olds?.provision ?? output?.provision,
336 upgrade: olds?.upgrade ?? output?.upgrade,
337 deprovision: olds?.deprovision ?? output?.deprovision,
338 flagUpdate: olds?.flagUpdate ?? output?.flagUpdate,
339 });
340 const nextKind = operationKind(news) || previousKind;
341 return replaceOnIdentity({
342 previousId: olds?.unitOperationId ?? output?.unitOperationId,
343 nextId: news.unitOperationId ?? olds?.unitOperationId ?? output?.unitOperationId,
344 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
345 nextLocation: normalizeLocation(
346 news.location ?? olds?.location ?? output?.location ?? env.region,
347 ),
348 extra:
349 !sameRef(olds?.unit ?? output?.unit, news.unit) ||
350 (previousKind.length > 0 && nextKind.length > 0 && previousKind !== nextKind),
351 });
352 }),
353
354 read: Effect.fn(function* ({ id, olds, output }) {
355 const env = yield* GcpEnvironment.current;
356 const unitOperationId = yield* toPhysicalId(
357 id,
358 olds?.unitOperationId,
359 output?.unitOperationId,
360 "uop",
361 );
362 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
363 const name = output?.name ?? resourceName(env.project, location, COLLECTION, unitOperationId);
364 const existing = yield* getByName(name);
365 if (existing === undefined) return undefined;
366 const attrs = toAttrs(existing, env.project);
367 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
368 }),
369
370 list: () =>
371 Effect.gen(function* () {
372 const env = yield* GcpEnvironment.current;
373 const items = yield* listOwned(env.project, env.region);
374 return items.map((item) => toAttrs(item, env.project));
375 }),
376
377 reconcile: Effect.fn(function* ({ id, news, output }) {
378 const env = yield* GcpEnvironment.current;
379 const unitOperationId = yield* toPhysicalId(
380 id,
381 news.unitOperationId,
382 output?.unitOperationId,
383 "uop",
384 );
385 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
386 const name = resourceName(env.project, location, COLLECTION, unitOperationId);
387 const desiredLabels = {
388 ...toLabels(news.labels),
389 ...(yield* createInternalLabels(id)),
390 };
391 const unit = expandName(news.unit, env.project, location, "units");
392 const provision = expandProvision(news.provision, env.project, location);
393 const upgrade = expandProvision(news.upgrade, env.project, location);
394 const parentUnitOperation =
395 news.parentUnitOperation === undefined
396 ? undefined
397 : expandName(news.parentUnitOperation, env.project, location, COLLECTION);
398 const annotations = news.annotations;
399
400 let current = yield* getByName(output?.name ?? name);
401
402 if (current === undefined) {
403 const created = yield* saasservicemgmt
404 .createProjectsLocationsUnitOperations({
405 parent: parentOf(env.project, location),
406 unitOperationId,
407 body: {
408 unit,
409 provision,
410 upgrade,
411 deprovision: news.deprovision === true ? {} : undefined,
412 flagUpdate: news.flagUpdate,
413 parentUnitOperation,
414 rollout: news.rollout,
415 schedule: news.schedule,
416 cancel: news.cancel,
417 labels: desiredLabels,
418 annotations,
419 },
420 })
421 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
422 current = created ?? undefined;
423 }
424
425 if (current === undefined) {
426 return yield* new ResourceNotResolved({ resourceName: name });
427 }
428
429 const observedLabels = tagRecord(current.labels);
430 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
431 const labelsChanged = upsert.length > 0 || removed.length > 0;
432 const annotationsChanged =
433 annotations !== undefined &&
434 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
435 const cancelChanged = news.cancel !== undefined && (current.cancel === true) !== news.cancel;
436 const scheduleChanged =
437 news.schedule !== undefined && fingerprint(current.schedule) !== fingerprint(news.schedule);
438 const mask = fieldMask([
439 labelsChanged && "labels",
440 annotationsChanged && "annotations",
441 cancelChanged && "cancel",
442 scheduleChanged && "schedule",
443 ]);
444
445 if (mask.length > 0) {
446 current = yield* saasservicemgmt.patchProjectsLocationsUnitOperations({
447 name: current.name ?? name,
448 updateMask: mask,
449 body: {
450 name: current.name ?? name,
451 etag: current.etag,
452 cancel: news.cancel,
453 schedule: news.schedule,
454 labels: desiredLabels,
455 annotations,
456 },
457 });
458 }
459
460 return toAttrs(current, env.project);
461 }),
462
463 delete: Effect.fn(function* ({ output }) {
464 yield* saasservicemgmt.deleteProjectsLocationsUnitOperations({ name: output.name }).pipe(
465 Effect.retry({
466 while: (error) => error._tag === "Conflict",
467 times: 8,
468 schedule: Schedule.spaced("2 seconds"),
469 }),
470 Effect.catchTag("NotFound", () => Effect.void),
471 );
472 yield* waitUntilGone(getByName(output.name), output.name);
473 }),
474 });