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

main
ts 412 lines 13.8 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 = "rollouts";
33
34 export type RolloutControlAction = saasservicemgmt.RolloutControlActionEnum | (string & {});
35
36 export type RolloutControl = {
37 action?: RolloutControlAction;
38 runParams?: { retryFailedOperations?: boolean };
39 };
40
41 export type RolloutStats = {
42 operationsByState?: Array<{ count?: number; group?: string }>;
43 estimatedTotalUnitCount?: string;
44 };
45
46 export type RolloutProps = {
47 /**
48 * Rollout id (the `{rollout_id}` segment of
49 * `projects/{project}/locations/{location}/rollouts/{rollout_id}`). If
50 * omitted, a unique RFC1035 name is generated. Immutable — changing
51 * it replaces the rollout.
52 */
53 rolloutId?: string;
54 /**
55 * Region of the rollout (`us-central1`, …). Immutable — changing it
56 * replaces the rollout. `US-CENTRAL1` is accepted and normalized to
57 * `us-central1`.
58 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
59 */
60 location?: string;
61 /**
62 * RolloutKind this rollout follows. Accepts a rollout kind id or a
63 * full resource name. Immutable — changing it replaces the rollout.
64 */
65 rolloutKind?: string;
66 /**
67 * Release rolled out to target units. Mutually exclusive with
68 * `flagRelease`. Immutable — changing it replaces the rollout.
69 */
70 release?: string;
71 /**
72 * Flag release rolled out to target units. Mutually exclusive with
73 * `release`. Immutable — changing it replaces the rollout.
74 */
75 flagRelease?: string;
76 /**
77 * CEL filter reducing the eligible unit population for this rollout.
78 */
79 unitFilter?: string;
80 /**
81 * Orchestration strategy override. If omitted, the RolloutKind
82 * strategy is used.
83 */
84 rolloutOrchestrationStrategy?: string;
85 /**
86 * Requested execution change (`ROLLOUT_ACTION_RUN`,
87 * `ROLLOUT_ACTION_PAUSE`, `ROLLOUT_ACTION_CANCEL`).
88 */
89 control?: RolloutControl;
90 /**
91 * User labels. Alchemy ownership labels are merged in automatically.
92 */
93 labels?: Record<string, string>;
94 /**
95 * Unstructured annotations preserved across updates.
96 */
97 annotations?: Record<string, string>;
98 };
99
100 export type Rollout = Resource<
101 "GCP.SaasServiceManagement.Rollout",
102 RolloutProps,
103 {
104 /** Full resource name `projects/{project}/locations/{location}/rollouts/{rollout_id}`. */
105 name: string;
106 /** Rollout id (last path segment). */
107 rolloutId: string;
108 /** Project id. */
109 project: string;
110 /** Location id. */
111 location: string;
112 /** RolloutKind resource name. */
113 rolloutKind: string | undefined;
114 /** RolloutKind id (last path segment). */
115 rolloutKindId: string | undefined;
116 /** Release resource name. */
117 release: string | undefined;
118 /** Release id (last path segment). */
119 releaseId: string | undefined;
120 /** Flag release resource name. */
121 flagRelease: string | undefined;
122 /** CEL unit filter. */
123 unitFilter: string | undefined;
124 /** Effective unit filter snapshotted at start. */
125 effectiveUnitFilter: string | undefined;
126 /** Orchestration strategy. */
127 rolloutOrchestrationStrategy: string | undefined;
128 /** Requested control action. */
129 control: RolloutControl | undefined;
130 /** Lifecycle state. */
131 state: string | undefined;
132 /** Human-readable last-transition message. */
133 stateMessage: string | undefined;
134 /** Progress stats. */
135 stats: RolloutStats | undefined;
136 /** Root rollout this one stems from. */
137 rootRollout: string | undefined;
138 /** Direct parent rollout. */
139 parentRollout: string | undefined;
140 /** User labels (Alchemy ownership labels stripped). */
141 labels: Record<string, string>;
142 /** User annotations. */
143 annotations: Record<string, string>;
144 /** Server UUID. */
145 uid: string | undefined;
146 /** Server etag. */
147 etag: string | undefined;
148 /** RFC3339 creation timestamp. */
149 createTime: string | undefined;
150 /** RFC3339 last-update timestamp. */
151 updateTime: string | undefined;
152 /** RFC3339 start timestamp. */
153 startTime: string | undefined;
154 /** RFC3339 end timestamp. */
155 endTime: string | undefined;
156 },
157 never,
158 Providers
159 >;
160
161 /**
162 * An App Lifecycle Manager rollout — one execution of a RolloutKind
163 * against a Release (or FlagRelease).
164 *
165 * `rolloutId`, `location`, `rolloutKind`, `release`, and `flagRelease`
166 * replace the rollout. Unit filter, strategy override, control action,
167 * labels, and annotations update in place. Requests to pause or cancel
168 * are only accepted while the rollout is non-terminal.
169 *
170 * ### Creating a Rollout
171 * **Example:** Roll a release
172 * ```typescript
173 * const rollout = yield* GCP.SaasServiceManagement.Rollout("Wave1", {
174 * rolloutKind: kind.name,
175 * release: release.name,
176 * labels: { env: "prod" },
177 * });
178 * ```
179 *
180 * ### Updating a Rollout
181 * **Example:** Pause
182 * ```typescript
183 * const rollout = yield* GCP.SaasServiceManagement.Rollout("Wave1", {
184 * rolloutId: rollout.rolloutId,
185 * rolloutKind: kind.name,
186 * release: release.name,
187 * control: { action: "ROLLOUT_ACTION_PAUSE" },
188 * });
189 * ```
190 *
191 * @resource
192 * @category SaasServiceManagement
193 */
194 export const Rollout = Resource<Rollout>("GCP.SaasServiceManagement.Rollout");
195
196 const toAttrs = (item: saasservicemgmt.Rollout, project: string) => {
197 const name = item.name ?? "";
198 const parsed = parseName(name, COLLECTION);
199 return {
200 name,
201 rolloutId: parsed.id,
202 project: parsed.project || project,
203 location: parsed.location,
204 rolloutKind: item.rolloutKind,
205 rolloutKindId: item.rolloutKind ? lastSegment(item.rolloutKind) : undefined,
206 release: item.release,
207 releaseId: item.release ? lastSegment(item.release) : undefined,
208 flagRelease: item.flagRelease,
209 unitFilter: item.unitFilter,
210 effectiveUnitFilter: item.effectiveUnitFilter,
211 rolloutOrchestrationStrategy: item.rolloutOrchestrationStrategy,
212 control: item.control
213 ? {
214 action: item.control.action,
215 runParams: item.control.runParams,
216 }
217 : undefined,
218 state: item.state,
219 stateMessage: item.stateMessage,
220 stats: item.stats,
221 rootRollout: item.rootRollout,
222 parentRollout: item.parentRollout,
223 labels: userLabels(item.labels),
224 annotations: userAnnotations(item.annotations),
225 uid: item.uid,
226 etag: item.etag,
227 createTime: item.createTime,
228 updateTime: item.updateTime,
229 startTime: item.startTime,
230 endTime: item.endTime,
231 };
232 };
233
234 const getByName = (name: string) =>
235 name.length === 0
236 ? Effect.undefined
237 : saasservicemgmt
238 .getProjectsLocationsRollouts({ name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 const listOwned = (project: string, location: string) =>
242 collectPages(
243 saasservicemgmt.listProjectsLocationsRollouts.pages({
244 parent: parentOf(project, "-"),
245 pageSize: 1000,
246 }),
247 (page) => page.rollouts,
248 ).pipe(
249 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
250 Effect.flatMap((items) =>
251 items.length > 0
252 ? Effect.succeed(items)
253 : collectPages(
254 saasservicemgmt.listProjectsLocationsRollouts.pages({
255 parent: parentOf(project, location),
256 pageSize: 1000,
257 }),
258 (page) => page.rollouts,
259 ).pipe(
260 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
261 ),
262 ),
263 );
264
265 export const RolloutProvider = () =>
266 Provider.succeed(Rollout, {
267 stables: [
268 "name",
269 "rolloutId",
270 "project",
271 "location",
272 "rolloutKindId",
273 "releaseId",
274 "uid",
275 "createTime",
276 ],
277
278 diff: Effect.fn(function* ({ news, olds, output }) {
279 if (!isResolved(news)) return undefined;
280 const env = yield* GcpEnvironment.current;
281 return replaceOnIdentity({
282 previousId: olds?.rolloutId ?? output?.rolloutId,
283 nextId: news.rolloutId ?? olds?.rolloutId ?? output?.rolloutId,
284 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
285 nextLocation: normalizeLocation(
286 news.location ?? olds?.location ?? output?.location ?? env.region,
287 ),
288 extra:
289 (news.rolloutKind !== undefined &&
290 !sameRef(olds?.rolloutKind ?? output?.rolloutKind, news.rolloutKind)) ||
291 (news.release !== undefined &&
292 !sameRef(olds?.release ?? output?.release, news.release)) ||
293 (news.flagRelease !== undefined &&
294 (olds?.flagRelease ?? output?.flagRelease ?? "") !== news.flagRelease),
295 });
296 }),
297
298 read: Effect.fn(function* ({ id, olds, output }) {
299 const env = yield* GcpEnvironment.current;
300 const rolloutId = yield* toPhysicalId(id, olds?.rolloutId, output?.rolloutId, "rlo");
301 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
302 const name = output?.name ?? resourceName(env.project, location, COLLECTION, rolloutId);
303 const existing = yield* getByName(name);
304 if (existing === undefined) return undefined;
305 const attrs = toAttrs(existing, env.project);
306 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
307 }),
308
309 list: () =>
310 Effect.gen(function* () {
311 const env = yield* GcpEnvironment.current;
312 const items = yield* listOwned(env.project, env.region);
313 return items.map((item) => toAttrs(item, env.project));
314 }),
315
316 reconcile: Effect.fn(function* ({ id, news, output }) {
317 const env = yield* GcpEnvironment.current;
318 const rolloutId = yield* toPhysicalId(id, news.rolloutId, output?.rolloutId, "rlo");
319 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
320 const name = resourceName(env.project, location, COLLECTION, rolloutId);
321 const desiredLabels = {
322 ...toLabels(news.labels),
323 ...(yield* createInternalLabels(id)),
324 };
325 const rolloutKind =
326 news.rolloutKind === undefined
327 ? undefined
328 : expandName(news.rolloutKind, env.project, location, "rolloutKinds");
329 const release =
330 news.release === undefined
331 ? undefined
332 : expandName(news.release, env.project, location, "releases");
333 const annotations = news.annotations;
334
335 let current = yield* getByName(output?.name ?? name);
336
337 if (current === undefined) {
338 const created = yield* saasservicemgmt
339 .createProjectsLocationsRollouts({
340 parent: parentOf(env.project, location),
341 rolloutId,
342 body: {
343 rolloutKind,
344 release,
345 flagRelease: news.flagRelease,
346 unitFilter: news.unitFilter,
347 rolloutOrchestrationStrategy: news.rolloutOrchestrationStrategy,
348 control: news.control,
349 labels: desiredLabels,
350 annotations,
351 },
352 })
353 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
354 current = created ?? undefined;
355 }
356
357 if (current === undefined) {
358 return yield* new ResourceNotResolved({ resourceName: name });
359 }
360
361 const observedLabels = tagRecord(current.labels);
362 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
363 const labelsChanged = upsert.length > 0 || removed.length > 0;
364 const annotationsChanged =
365 annotations !== undefined &&
366 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
367 const filterChanged =
368 news.unitFilter !== undefined && (current.unitFilter ?? "") !== news.unitFilter;
369 const strategyChanged =
370 news.rolloutOrchestrationStrategy !== undefined &&
371 (current.rolloutOrchestrationStrategy ?? "") !== news.rolloutOrchestrationStrategy;
372 const controlChanged =
373 news.control !== undefined && fingerprint(current.control) !== fingerprint(news.control);
374 const mask = fieldMask([
375 labelsChanged && "labels",
376 annotationsChanged && "annotations",
377 filterChanged && "unitFilter",
378 strategyChanged && "rolloutOrchestrationStrategy",
379 controlChanged && "control",
380 ]);
381
382 if (mask.length > 0) {
383 current = yield* saasservicemgmt.patchProjectsLocationsRollouts({
384 name: current.name ?? name,
385 updateMask: mask,
386 body: {
387 name: current.name ?? name,
388 etag: current.etag,
389 unitFilter: news.unitFilter,
390 rolloutOrchestrationStrategy: news.rolloutOrchestrationStrategy,
391 control: news.control,
392 labels: desiredLabels,
393 annotations,
394 },
395 });
396 }
397
398 return toAttrs(current, env.project);
399 }),
400
401 delete: Effect.fn(function* ({ output }) {
402 yield* saasservicemgmt.deleteProjectsLocationsRollouts({ name: output.name }).pipe(
403 Effect.retry({
404 while: (error) => error._tag === "Conflict",
405 times: 8,
406 schedule: Schedule.spaced("2 seconds"),
407 }),
408 Effect.catchTag("NotFound", () => Effect.void),
409 );
410 yield* waitUntilGone(getByName(output.name), output.name);
411 }),
412 });