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

main
ts 392 lines 13.6 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 = "rolloutKinds";
33
34 export type RolloutKindUpdateUnitKindStrategy =
35 | saasservicemgmt.RolloutKindUpdateUnitKindStrategyEnum
36 | (string & {});
37
38 export type RolloutKindErrorBudget = {
39 /** Max percent of units in a location allowed to fail without pausing. */
40 allowedPercentage?: number;
41 /** Max number of failed units in a location without pausing. */
42 allowedCount?: number;
43 };
44
45 export type RolloutKindUnitUpdatePacing = {
46 /** Max percent of units that may be in-flight in a region. */
47 maxConcurrentOperationsPercent?: { value?: string };
48 /** Absolute cap on concurrent unit operations. */
49 maxConcurrentOperationsCount?: number;
50 };
51
52 export type RolloutKindProps = {
53 /**
54 * RolloutKind id (the `{rollout_kind_id}` segment of
55 * `projects/{project}/locations/{location}/rolloutKinds/{rollout_kind_id}`).
56 * If omitted, a unique RFC1035 name is generated. Immutable —
57 * changing it replaces the rollout kind.
58 */
59 rolloutKindId?: string;
60 /**
61 * Region of the rollout kind (`us-central1`, …). Immutable — changing
62 * it replaces the rollout kind. `US-CENTRAL1` is accepted and
63 * normalized to `us-central1`.
64 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
65 */
66 location?: string;
67 /**
68 * UnitKind whose units this rollout kind targets. Accepts a unit kind
69 * id or a full resource name. Immutable — changing it replaces the
70 * rollout kind.
71 */
72 unitKind: string;
73 /**
74 * Orchestration strategy, e.g. `Google.Cloud.Simple.AllAtOnce` or
75 * `Google.Cloud.Simple.OneLocationAtATime`.
76 */
77 rolloutOrchestrationStrategy?: string;
78 /**
79 * When to update the unit kind (`UPDATE_UNIT_KIND_STRATEGY_ON_START`
80 * or `UPDATE_UNIT_KIND_STRATEGY_NEVER`).
81 */
82 updateUnitKindStrategy?: RolloutKindUpdateUnitKindStrategy;
83 /**
84 * Pause the rollout if failures exceed this budget.
85 */
86 errorBudget?: RolloutKindErrorBudget;
87 /**
88 * CEL filter reducing the eligible unit population.
89 */
90 unitFilter?: string;
91 /**
92 * Cap on concurrent unit operations per region.
93 */
94 unitUpdatePacing?: RolloutKindUnitUpdatePacing;
95 /**
96 * User labels. Alchemy ownership labels are merged in automatically.
97 */
98 labels?: Record<string, string>;
99 /**
100 * Unstructured annotations preserved across updates.
101 */
102 annotations?: Record<string, string>;
103 };
104
105 export type RolloutKind = Resource<
106 "GCP.SaasServiceManagement.RolloutKind",
107 RolloutKindProps,
108 {
109 /** Full resource name `projects/{project}/locations/{location}/rolloutKinds/{rollout_kind_id}`. */
110 name: string;
111 /** RolloutKind id (last path segment). */
112 rolloutKindId: string;
113 /** Project id. */
114 project: string;
115 /** Location id. */
116 location: string;
117 /** UnitKind resource name. */
118 unitKind: string | undefined;
119 /** UnitKind id (last path segment). */
120 unitKindId: string | undefined;
121 /** Orchestration strategy. */
122 rolloutOrchestrationStrategy: string | undefined;
123 /** Unit-kind update strategy. */
124 updateUnitKindStrategy: string | undefined;
125 /** Error budget. */
126 errorBudget: RolloutKindErrorBudget | undefined;
127 /** CEL unit filter. */
128 unitFilter: string | undefined;
129 /** Concurrent-operation pacing. */
130 unitUpdatePacing: RolloutKindUnitUpdatePacing | undefined;
131 /** User labels (Alchemy ownership labels stripped). */
132 labels: Record<string, string>;
133 /** User annotations. */
134 annotations: Record<string, string>;
135 /** Server UUID. */
136 uid: string | undefined;
137 /** Server etag. */
138 etag: string | undefined;
139 /** RFC3339 creation timestamp. */
140 createTime: string | undefined;
141 /** RFC3339 last-update timestamp. */
142 updateTime: string | undefined;
143 },
144 never,
145 Providers
146 >;
147
148 /**
149 * An App Lifecycle Manager rollout kind — the policy a Rollout follows
150 * when upgrading units of a UnitKind.
151 *
152 * `rolloutKindId`, `location`, and `unitKind` replace the rollout kind.
153 * Strategy, error budget, unit filter, pacing, labels, and annotations
154 * update in place.
155 *
156 * ### Creating a RolloutKind
157 * **Example:** All-at-once
158 * ```typescript
159 * const kind = yield* GCP.SaasServiceManagement.RolloutKind("Wave", {
160 * unitKind: storeKind.name,
161 * rolloutOrchestrationStrategy: "Google.Cloud.Simple.AllAtOnce",
162 * labels: { env: "prod" },
163 * });
164 * ```
165 *
166 * ### Updating a RolloutKind
167 * **Example:** Tighten the error budget
168 * ```typescript
169 * const kind = yield* GCP.SaasServiceManagement.RolloutKind("Wave", {
170 * rolloutKindId: kind.rolloutKindId,
171 * unitKind: storeKind.name,
172 * errorBudget: { allowedCount: 1, allowedPercentage: 5 },
173 * });
174 * ```
175 *
176 * @resource
177 * @category SaasServiceManagement
178 */
179 export const RolloutKind = Resource<RolloutKind>("GCP.SaasServiceManagement.RolloutKind");
180
181 const toAttrs = (item: saasservicemgmt.RolloutKind, project: string) => {
182 const name = item.name ?? "";
183 const parsed = parseName(name, COLLECTION);
184 return {
185 name,
186 rolloutKindId: parsed.id,
187 project: parsed.project || project,
188 location: parsed.location,
189 unitKind: item.unitKind,
190 unitKindId: item.unitKind ? lastSegment(item.unitKind) : undefined,
191 rolloutOrchestrationStrategy: item.rolloutOrchestrationStrategy,
192 updateUnitKindStrategy: item.updateUnitKindStrategy,
193 errorBudget: item.errorBudget
194 ? {
195 allowedPercentage: item.errorBudget.allowedPercentage,
196 allowedCount: item.errorBudget.allowedCount,
197 }
198 : undefined,
199 unitFilter: item.unitFilter,
200 unitUpdatePacing: item.unitUpdatePacing
201 ? {
202 maxConcurrentOperationsPercent: item.unitUpdatePacing.maxConcurrentOperationsPercent,
203 maxConcurrentOperationsCount: item.unitUpdatePacing.maxConcurrentOperationsCount,
204 }
205 : undefined,
206 labels: userLabels(item.labels),
207 annotations: userAnnotations(item.annotations),
208 uid: item.uid,
209 etag: item.etag,
210 createTime: item.createTime,
211 updateTime: item.updateTime,
212 };
213 };
214
215 const getByName = (name: string) =>
216 name.length === 0
217 ? Effect.undefined
218 : saasservicemgmt
219 .getProjectsLocationsRolloutKinds({ name })
220 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
221
222 const listOwned = (project: string, location: string) =>
223 collectPages(
224 saasservicemgmt.listProjectsLocationsRolloutKinds.pages({
225 parent: parentOf(project, "-"),
226 pageSize: 1000,
227 }),
228 (page) => page.rolloutKinds,
229 ).pipe(
230 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
231 Effect.flatMap((items) =>
232 items.length > 0
233 ? Effect.succeed(items)
234 : collectPages(
235 saasservicemgmt.listProjectsLocationsRolloutKinds.pages({
236 parent: parentOf(project, location),
237 pageSize: 1000,
238 }),
239 (page) => page.rolloutKinds,
240 ).pipe(
241 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
242 ),
243 ),
244 );
245
246 export const RolloutKindProvider = () =>
247 Provider.succeed(RolloutKind, {
248 stables: ["name", "rolloutKindId", "project", "location", "unitKindId", "uid", "createTime"],
249
250 diff: Effect.fn(function* ({ news, olds, output }) {
251 if (!isResolved(news)) return undefined;
252 const env = yield* GcpEnvironment.current;
253 return replaceOnIdentity({
254 previousId: olds?.rolloutKindId ?? output?.rolloutKindId,
255 nextId: news.rolloutKindId ?? olds?.rolloutKindId ?? output?.rolloutKindId,
256 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
257 nextLocation: normalizeLocation(
258 news.location ?? olds?.location ?? output?.location ?? env.region,
259 ),
260 extra: !sameRef(olds?.unitKind ?? output?.unitKind, news.unitKind),
261 });
262 }),
263
264 read: Effect.fn(function* ({ id, olds, output }) {
265 const env = yield* GcpEnvironment.current;
266 const rolloutKindId = yield* toPhysicalId(
267 id,
268 olds?.rolloutKindId,
269 output?.rolloutKindId,
270 "rk",
271 );
272 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
273 const name = output?.name ?? resourceName(env.project, location, COLLECTION, rolloutKindId);
274 const existing = yield* getByName(name);
275 if (existing === undefined) return undefined;
276 const attrs = toAttrs(existing, env.project);
277 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
278 }),
279
280 list: () =>
281 Effect.gen(function* () {
282 const env = yield* GcpEnvironment.current;
283 const items = yield* listOwned(env.project, env.region);
284 return items.map((item) => toAttrs(item, env.project));
285 }),
286
287 reconcile: Effect.fn(function* ({ id, news, output }) {
288 const env = yield* GcpEnvironment.current;
289 const rolloutKindId = yield* toPhysicalId(
290 id,
291 news.rolloutKindId,
292 output?.rolloutKindId,
293 "rk",
294 );
295 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
296 const name = resourceName(env.project, location, COLLECTION, rolloutKindId);
297 const desiredLabels = {
298 ...toLabels(news.labels),
299 ...(yield* createInternalLabels(id)),
300 };
301 const unitKind = expandName(news.unitKind, env.project, location, "unitKinds");
302 const annotations = news.annotations;
303
304 let current = yield* getByName(output?.name ?? name);
305
306 if (current === undefined) {
307 const created = yield* saasservicemgmt
308 .createProjectsLocationsRolloutKinds({
309 parent: parentOf(env.project, location),
310 rolloutKindId,
311 body: {
312 unitKind,
313 rolloutOrchestrationStrategy: news.rolloutOrchestrationStrategy,
314 updateUnitKindStrategy: news.updateUnitKindStrategy,
315 errorBudget: news.errorBudget,
316 unitFilter: news.unitFilter,
317 unitUpdatePacing: news.unitUpdatePacing,
318 labels: desiredLabels,
319 annotations,
320 },
321 })
322 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
323 current = created ?? undefined;
324 }
325
326 if (current === undefined) {
327 return yield* new ResourceNotResolved({ resourceName: name });
328 }
329
330 const observedLabels = tagRecord(current.labels);
331 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
332 const labelsChanged = upsert.length > 0 || removed.length > 0;
333 const annotationsChanged =
334 annotations !== undefined &&
335 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
336 const strategyChanged =
337 news.rolloutOrchestrationStrategy !== undefined &&
338 (current.rolloutOrchestrationStrategy ?? "") !== news.rolloutOrchestrationStrategy;
339 const updateStrategyChanged =
340 news.updateUnitKindStrategy !== undefined &&
341 (current.updateUnitKindStrategy ?? "") !== news.updateUnitKindStrategy;
342 const budgetChanged =
343 news.errorBudget !== undefined &&
344 fingerprint(current.errorBudget) !== fingerprint(news.errorBudget);
345 const filterChanged =
346 news.unitFilter !== undefined && (current.unitFilter ?? "") !== news.unitFilter;
347 const pacingChanged =
348 news.unitUpdatePacing !== undefined &&
349 fingerprint(current.unitUpdatePacing) !== fingerprint(news.unitUpdatePacing);
350 const mask = fieldMask([
351 labelsChanged && "labels",
352 annotationsChanged && "annotations",
353 strategyChanged && "rolloutOrchestrationStrategy",
354 updateStrategyChanged && "updateUnitKindStrategy",
355 budgetChanged && "errorBudget",
356 filterChanged && "unitFilter",
357 pacingChanged && "unitUpdatePacing",
358 ]);
359
360 if (mask.length > 0) {
361 current = yield* saasservicemgmt.patchProjectsLocationsRolloutKinds({
362 name: current.name ?? name,
363 updateMask: mask,
364 body: {
365 name: current.name ?? name,
366 etag: current.etag,
367 rolloutOrchestrationStrategy: news.rolloutOrchestrationStrategy,
368 updateUnitKindStrategy: news.updateUnitKindStrategy,
369 errorBudget: news.errorBudget,
370 unitFilter: news.unitFilter,
371 unitUpdatePacing: news.unitUpdatePacing,
372 labels: desiredLabels,
373 annotations,
374 },
375 });
376 }
377
378 return toAttrs(current, env.project);
379 }),
380
381 delete: Effect.fn(function* ({ output }) {
382 yield* saasservicemgmt.deleteProjectsLocationsRolloutKinds({ name: output.name }).pipe(
383 Effect.retry({
384 while: (error) => error._tag === "Conflict",
385 times: 8,
386 schedule: Schedule.spaced("2 seconds"),
387 }),
388 Effect.catchTag("NotFound", () => Effect.void),
389 );
390 yield* waitUntilGone(getByName(output.name), output.name);
391 }),
392 });