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

main
ts 496 lines 15.6 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 fieldMask,
14 fingerprint,
15 listAtLocation,
16 listLabeledPages,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sameBool,
23 sameText,
24 stringMap,
25 toPhysicalId,
26 userLabels,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 export type DeliveryPipelineAttribute = {
33 /**
34 * Delivery pipeline id, the last segment of a pipeline name, or `*`
35 * for all pipelines in the location.
36 */
37 id?: string;
38 /** Pipeline labels that must match. */
39 labels?: Record<string, string>;
40 };
41
42 export type DeployPolicyTargetAttribute = {
43 /**
44 * Target id, the last segment of a Target name, or `*` for all
45 * targets in the location.
46 */
47 id?: string;
48 /** Target labels that must match. */
49 labels?: Record<string, string>;
50 };
51
52 export type DeployPolicyResourceSelector = {
53 /** Delivery pipeline attributes that must match. */
54 deliveryPipeline?: DeliveryPipelineAttribute;
55 /** Target attributes that must match. */
56 target?: DeployPolicyTargetAttribute;
57 };
58
59 export type TimeOfDay = {
60 /** Hours of day in 24-hour format (`0`–`23`, or `24` for end of day). */
61 hours?: number;
62 /** Minutes of hour (`0`–`59`). */
63 minutes?: number;
64 /** Seconds of minute (`0`–`59`). */
65 seconds?: number;
66 /** Fractional seconds, in nanoseconds. */
67 nanos?: number;
68 };
69
70 export type CalendarDate = {
71 /** Year (`1`–`9999`), or `0` to omit. */
72 year?: number;
73 /** Month (`1`–`12`), or `0` to omit. */
74 month?: number;
75 /** Day (`1`–`31`), or `0` to omit. */
76 day?: number;
77 };
78
79 export type OneTimeWindow = {
80 /** Inclusive start date. */
81 startDate?: CalendarDate;
82 /** Inclusive end date. */
83 endDate?: CalendarDate;
84 /** Inclusive start time. Use `00:00` for the beginning of the day. */
85 startTime?: TimeOfDay;
86 /** Exclusive end time. Use `24:00` for the end of the day. */
87 endTime?: TimeOfDay;
88 };
89
90 export type WeeklyWindow = {
91 /**
92 * Days of week. Empty means every day.
93 */
94 daysOfWeek?: Array<clouddeploy.WeeklyWindowDaysOfWeekItemEnum | (string & {})>;
95 /** Inclusive start time. Must be set with `endTime`. */
96 startTime?: TimeOfDay;
97 /** Exclusive end time. Must be set with `startTime`. */
98 endTime?: TimeOfDay;
99 };
100
101 export type TimeWindows = {
102 /** IANA time zone (for example `America/Los_Angeles`). */
103 timeZone?: string;
104 /** Recurring weekly restriction windows. */
105 weeklyWindows?: WeeklyWindow[];
106 /** One-time restriction windows. */
107 oneTimeWindows?: OneTimeWindow[];
108 };
109
110 export type RolloutRestriction = {
111 /** Unique restriction id within the policy. */
112 id?: string;
113 /**
114 * Restricted invokers (`USER`, `DEPLOY_AUTOMATION`). Empty means all
115 * invokers.
116 */
117 invokers?: Array<clouddeploy.RolloutRestrictionInvokersItemEnum | (string & {})>;
118 /**
119 * Restricted rollout actions (`ADVANCE`, `APPROVE`, `CANCEL`,
120 * `CREATE`, `IGNORE_JOB`, `RETRY_JOB`, `ROLLBACK`,
121 * `TERMINATE_JOBRUN`). Empty means all actions.
122 */
123 actions?: Array<clouddeploy.RolloutRestrictionActionsItemEnum | (string & {})>;
124 /** Time windows during which actions are restricted. */
125 timeWindows?: TimeWindows;
126 };
127
128 export type PolicyRule = {
129 /** Rollout restriction for this rule. */
130 rolloutRestriction?: RolloutRestriction;
131 };
132
133 export type DeployPolicyProps = {
134 /**
135 * Deploy policy id (the `{deployPolicy}` segment of
136 * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`).
137 * If omitted, a unique RFC1035 name is generated from the stack, stage,
138 * and logical id. Immutable — changing it replaces the policy.
139 */
140 deployPolicyId?: string;
141 /**
142 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
143 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
144 * `us-central1`.
145 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
146 */
147 location?: string;
148 /**
149 * Resources the policy applies to. At least one selector is required.
150 */
151 selectors: DeployPolicyResourceSelector[];
152 /**
153 * Policy rules. At least one rule is required.
154 */
155 rules: PolicyRule[];
156 /**
157 * Human-readable description. Max length 255 characters.
158 */
159 description?: string;
160 /**
161 * When true, the policy does not block actions even if they violate it.
162 * @default false
163 */
164 suspended?: boolean;
165 /**
166 * User annotations (not used by Cloud Deploy).
167 */
168 annotations?: Record<string, string>;
169 /**
170 * User labels. Alchemy ownership labels are merged in automatically.
171 */
172 labels?: Record<string, string>;
173 };
174
175 export type DeployPolicy = Resource<
176 "GCP.CloudDeploy.DeployPolicy",
177 DeployPolicyProps,
178 {
179 /** Full resource name. */
180 name: string;
181 /** Deploy policy id (last path segment). */
182 deployPolicyId: string;
183 /** Project id. */
184 project: string;
185 /** Location id. */
186 location: string;
187 /** Resource selectors. */
188 selectors: DeployPolicyResourceSelector[];
189 /** Policy rules. */
190 rules: PolicyRule[];
191 /** Human-readable description. */
192 description: string | undefined;
193 /** Whether the policy is suspended. */
194 suspended: boolean;
195 /** User annotations. */
196 annotations: Record<string, string>;
197 /** User labels (Alchemy ownership labels stripped). */
198 labels: Record<string, string>;
199 /** Server-generated resource uid. */
200 uid: string | undefined;
201 /** RFC3339 creation timestamp. */
202 createTime: string | undefined;
203 /** RFC3339 last-update timestamp. */
204 updateTime: string | undefined;
205 /** Server-computed etag. */
206 etag: string | undefined;
207 },
208 never,
209 Providers
210 >;
211
212 /**
213 * A Cloud Deploy policy that restricts rollout actions on selected
214 * delivery pipelines and targets (for example a weekend freeze).
215 *
216 * Changing `deployPolicyId` or `location` replaces the policy.
217 * Selectors, rules, description, labels, annotations, and `suspended`
218 * update in place.
219 *
220 * ### Creating a Deploy Policy
221 * **Example:** Weekend freeze
222 * ```typescript
223 * const policy = yield* GCP.CloudDeploy.DeployPolicy("Freeze", {
224 * selectors: [{ target: { id: "*" } }],
225 * rules: [{
226 * rolloutRestriction: {
227 * id: "weekends",
228 * timeWindows: {
229 * timeZone: "America/Los_Angeles",
230 * weeklyWindows: [{ daysOfWeek: ["SATURDAY", "SUNDAY"] }],
231 * },
232 * },
233 * }],
234 * });
235 * ```
236 *
237 * **Example:** Business-hours only
238 * ```typescript
239 * const policy = yield* GCP.CloudDeploy.DeployPolicy("Freeze", {
240 * selectors: [{ deliveryPipeline: { id: "prod" } }],
241 * rules: [{
242 * rolloutRestriction: {
243 * id: "after-hours",
244 * actions: ["CREATE", "APPROVE"],
245 * timeWindows: {
246 * timeZone: "America/New_York",
247 * weeklyWindows: [{
248 * daysOfWeek: ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"],
249 * startTime: { hours: 17 },
250 * endTime: { hours: 24 },
251 * }],
252 * },
253 * },
254 * }],
255 * labels: { env: "prod" },
256 * });
257 * ```
258 *
259 * ### Updating a Deploy Policy
260 * Re-declare the same logical id with changed props; the engine keeps the
261 * physical resource and updates it in place.
262 *
263 * **Example:** Description and labels
264 * ```typescript
265 * const policy = yield* GCP.CloudDeploy.DeployPolicy("Freeze", {
266 * selectors: [{ target: { id: "*" } }],
267 * rules: [{
268 * rolloutRestriction: {
269 * id: "weekends",
270 * timeWindows: {
271 * timeZone: "America/Los_Angeles",
272 * weeklyWindows: [{ daysOfWeek: ["SATURDAY", "SUNDAY"] }],
273 * },
274 * },
275 * }],
276 * description: "weekend freeze v2",
277 * labels: { env: "prod", team: "platform" },
278 * });
279 * ```
280 *
281 * @resource
282 * @category CloudDeploy
283 */
284 export const DeployPolicy = Resource<DeployPolicy>("GCP.CloudDeploy.DeployPolicy");
285
286 const resourceName = (project: string, location: string, deployPolicyId: string) =>
287 `projects/${project}/locations/${location}/deployPolicies/${deployPolicyId}`;
288
289 const toSelectors = (
290 value: clouddeploy.DeployPolicyResourceSelectorList | undefined,
291 ): DeployPolicyResourceSelector[] =>
292 (value ?? []).map((selector) => ({
293 deliveryPipeline:
294 selector.deliveryPipeline === undefined
295 ? undefined
296 : {
297 id: selector.deliveryPipeline.id,
298 labels: stringMap(selector.deliveryPipeline.labels),
299 },
300 target:
301 selector.target === undefined
302 ? undefined
303 : {
304 id: selector.target.id,
305 labels: stringMap(selector.target.labels),
306 },
307 }));
308
309 const toRules = (value: clouddeploy.PolicyRuleList | undefined): PolicyRule[] =>
310 (value ?? []).map((rule) => ({
311 rolloutRestriction:
312 rule.rolloutRestriction === undefined
313 ? undefined
314 : {
315 id: rule.rolloutRestriction.id,
316 invokers: rule.rolloutRestriction.invokers,
317 actions: rule.rolloutRestriction.actions,
318 timeWindows: rule.rolloutRestriction.timeWindows,
319 },
320 }));
321
322 const toAttrs = (item: clouddeploy.DeployPolicy, project: string) => {
323 const name = item.name ?? "";
324 const parsed = parseName(name, "deployPolicies");
325 return {
326 name,
327 deployPolicyId: parsed.id,
328 project: parsed.project || project,
329 location: parsed.location,
330 selectors: toSelectors(item.selectors),
331 rules: toRules(item.rules),
332 description: item.description,
333 suspended: item.suspended === true,
334 annotations: stringMap(item.annotations),
335 labels: userLabels(item.labels),
336 uid: item.uid,
337 createTime: item.createTime,
338 updateTime: item.updateTime,
339 etag: item.etag,
340 };
341 };
342
343 const getByName = (name: string) =>
344 clouddeploy
345 .getProjectsLocationsDeployPolicies({ name })
346 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
347
348 const listOwned = (project: string, region: string) =>
349 listAtLocation(project, region, (parent) =>
350 listLabeledPages(
351 clouddeploy.listProjectsLocationsDeployPolicies.pages({
352 parent,
353 pageSize: 1000,
354 }),
355 (page) => page.deployPolicies,
356 (item) => item.labels,
357 ),
358 );
359
360 export const DeployPolicyProvider = () =>
361 Provider.succeed(DeployPolicy, {
362 stables: ["name", "deployPolicyId", "project", "location", "uid", "createTime"],
363
364 diff: Effect.fn(function* ({ news, olds, output }) {
365 if (!isResolved(news)) return undefined;
366 const env = yield* GcpEnvironment.current;
367 return replaceOnIdentity({
368 previousId: olds?.deployPolicyId ?? output?.deployPolicyId,
369 nextId: news.deployPolicyId ?? olds?.deployPolicyId ?? output?.deployPolicyId,
370 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
371 nextLocation: normalizeLocation(
372 news.location ?? olds?.location ?? output?.location ?? env.region,
373 ),
374 });
375 }),
376
377 read: Effect.fn(function* ({ id, olds, output }) {
378 const env = yield* GcpEnvironment.current;
379 const deployPolicyId = yield* toPhysicalId(
380 id,
381 olds?.deployPolicyId,
382 output?.deployPolicyId,
383 "deploypolicy",
384 );
385 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
386 const name = output?.name ?? resourceName(env.project, location, deployPolicyId);
387 const existing = yield* getByName(name);
388 if (existing === undefined) return undefined;
389 const attrs = toAttrs(existing, env.project);
390 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
391 }),
392
393 list: () =>
394 Effect.gen(function* () {
395 const env = yield* GcpEnvironment.current;
396 const items = yield* listOwned(env.project, env.region);
397 return items.map((item) => toAttrs(item, env.project));
398 }),
399
400 reconcile: Effect.fn(function* ({ id, news, output }) {
401 const env = yield* GcpEnvironment.current;
402 const deployPolicyId = yield* toPhysicalId(
403 id,
404 news.deployPolicyId,
405 output?.deployPolicyId,
406 "deploypolicy",
407 );
408 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
409 const name = resourceName(env.project, location, deployPolicyId);
410 const desiredLabels = {
411 ...toLabels(news.labels),
412 ...(yield* createInternalLabels(id)),
413 };
414 const desiredAnnotations = news.annotations ?? {};
415 const desiredSuspended = news.suspended === true;
416
417 let current = yield* getByName(output?.name ?? name);
418
419 if (current === undefined) {
420 const created = yield* clouddeploy
421 .createProjectsLocationsDeployPolicies({
422 parent: parentOf(env.project, location),
423 deployPolicyId,
424 body: {
425 selectors: news.selectors,
426 rules: news.rules,
427 description: news.description,
428 suspended: desiredSuspended,
429 annotations: desiredAnnotations,
430 labels: desiredLabels,
431 },
432 })
433 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
434 if (created !== undefined) {
435 yield* waitForOperation(created);
436 }
437 current = yield* waitUntilExists(getByName(name), name);
438 }
439
440 if (current === undefined) {
441 return yield* new ResourceNotResolved({ resourceName: name });
442 }
443
444 const observedLabels = tagRecord(current.labels);
445 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
446 const mask = fieldMask([
447 (upsert.length > 0 || removed.length > 0) && "labels",
448 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
449 "annotations",
450 !sameText(current.description, news.description) && "description",
451 !sameBool(current.suspended, desiredSuspended) && "suspended",
452 fingerprint(toSelectors(current.selectors)) !== fingerprint(news.selectors) && "selectors",
453 fingerprint(toRules(current.rules)) !== fingerprint(news.rules) && "rules",
454 ]);
455
456 if (mask.length > 0) {
457 const operation = yield* clouddeploy.patchProjectsLocationsDeployPolicies({
458 name: current.name ?? name,
459 updateMask: mask,
460 body: {
461 etag: current.etag,
462 selectors: news.selectors,
463 rules: news.rules,
464 description: news.description,
465 suspended: desiredSuspended,
466 annotations: desiredAnnotations,
467 labels: desiredLabels,
468 },
469 });
470 yield* waitForOperation(operation);
471 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
472 }
473
474 return toAttrs(current, env.project);
475 }),
476
477 delete: Effect.fn(function* ({ output }) {
478 const operation = yield* clouddeploy
479 .deleteProjectsLocationsDeployPolicies({
480 name: output.name,
481 allowMissing: true,
482 })
483 .pipe(
484 Effect.retry({
485 while: (error) => error._tag === "Conflict",
486 times: 8,
487 schedule: Schedule.spaced("2 seconds"),
488 }),
489 Effect.catchTag("NotFound", () => Effect.undefined),
490 );
491 if (operation !== undefined) {
492 yield* waitForOperation(operation, { notFoundOk: true });
493 }
494 yield* waitUntilGone(getByName(output.name), output.name);
495 }),
496 });