@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, 04:45 UTC

main
ts 662 lines 23 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitRegionOperation } from "./operations.ts";
15
16 const MAX_NAME_LENGTH = 63;
17
18 export type SnapshotSchedulePolicy = compute.ResourcePolicySnapshotSchedulePolicy;
19 export type InstanceSchedulePolicy = compute.ResourcePolicyInstanceSchedulePolicy;
20 export type GroupPlacementPolicy = compute.ResourcePolicyGroupPlacementPolicy;
21 export type WorkloadPolicy = compute.ResourcePolicyWorkloadPolicy;
22 export type DiskConsistencyGroupPolicy = compute.ResourcePolicyDiskConsistencyGroupPolicy;
23
24 export type ResourcePolicyProps = {
25 /**
26 * Resource policy name (RFC1035, 1-63 characters). If omitted, a unique
27 * name is generated from the stack, stage, and logical id. Changing the
28 * name replaces the policy.
29 */
30 resourcePolicyName?: string;
31 /**
32 * Region the policy lives in (e.g. `us-central1`). Immutable — changing
33 * it replaces the policy. `US-CENTRAL1` is accepted and normalized to
34 * `us-central1`.
35 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
36 */
37 region?: string;
38 /**
39 * Optional description. Compute resource policies have no labels field,
40 * so Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`)
41 * is stored in a `[alchemy …]` prefix for `list` / nuke.
42 */
43 description?: string;
44 /**
45 * Snapshot schedule attached to persistent disks. Mutable in place via
46 * `resourcePolicies.patch`. Mutually exclusive with the other policy
47 * kinds — switching kind replaces the resource.
48 */
49 snapshotSchedulePolicy?: SnapshotSchedulePolicy;
50 /**
51 * Start/stop schedule for VM instances. Mutable in place. Mutually
52 * exclusive with the other policy kinds.
53 */
54 instanceSchedulePolicy?: InstanceSchedulePolicy;
55 /**
56 * Compact / collocated placement for instances. Immutable — changing it
57 * replaces the policy.
58 */
59 groupPlacementPolicy?: GroupPlacementPolicy;
60 /**
61 * Workload placement for managed instance groups. Immutable — changing
62 * it replaces the policy.
63 */
64 workloadPolicy?: WorkloadPolicy;
65 /**
66 * Disk consistency-group policy. Immutable — changing it replaces the
67 * policy.
68 */
69 diskConsistencyGroupPolicy?: DiskConsistencyGroupPolicy;
70 };
71
72 export type ResourcePolicy = Resource<
73 "GCP.Compute.ResourcePolicy",
74 ResourcePolicyProps,
75 {
76 /** Resource policy name. */
77 resourcePolicyName: string;
78 /** Server-assigned numeric id. */
79 resourcePolicyId: string | undefined;
80 /** Project id. */
81 project: string;
82 /** Region short name (`us-central1`). */
83 region: string;
84 /** User description with the Alchemy ownership prefix stripped. */
85 description: string | undefined;
86 /** Server-reported status (`READY`, `CREATING`, `DELETING`, …). */
87 status: string | undefined;
88 /** Snapshot schedule, if this is a snapshot policy. */
89 snapshotSchedulePolicy: SnapshotSchedulePolicy | undefined;
90 /** Instance start/stop schedule, if this is an instance-schedule policy. */
91 instanceSchedulePolicy: InstanceSchedulePolicy | undefined;
92 /** Group placement policy, if any. */
93 groupPlacementPolicy: GroupPlacementPolicy | undefined;
94 /** Workload policy, if any. */
95 workloadPolicy: WorkloadPolicy | undefined;
96 /** Disk consistency-group policy, if any. */
97 diskConsistencyGroupPolicy: DiskConsistencyGroupPolicy | undefined;
98 /** Output-only system status (e.g. next instance-schedule run). */
99 resourceStatus: compute.ResourcePolicyResourceStatus | undefined;
100 /** Compute Engine self-link. */
101 selfLink: string | undefined;
102 /** RFC3339 creation timestamp. */
103 creationTimestamp: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A regional Compute Engine resource policy.
111 *
112 * Resource policies schedule snapshots, start/stop VMs, or describe
113 * placement. Compute Engine has no labels on this resource, so Alchemy
114 * stamps ownership into the description (`[alchemy alchemy-stack=…
115 * alchemy-stage=… alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find
116 * them.
117 *
118 * Name, region, and policy kind (`snapshotSchedulePolicy` vs
119 * `instanceSchedulePolicy` vs placement/workload/consistency) are
120 * immutable — changing them replaces the policy. Description and the
121 * nested snapshot / instance schedules update in place via
122 * `resourcePolicies.patch`.
123 *
124 * ### Creating a Resource Policy
125 * **Example:** Daily snapshot schedule
126 * ```typescript
127 * const nightly = yield* GCP.Compute.ResourcePolicy("Nightly", {
128 * snapshotSchedulePolicy: {
129 * schedule: {
130 * dailySchedule: { daysInCycle: 1, startTime: "04:00" },
131 * },
132 * retentionPolicy: { maxRetentionDays: 7 },
133 * },
134 * });
135 * ```
136 *
137 * **Example:** Named policy with labels in the snapshot properties
138 * ```typescript
139 * const backups = yield* GCP.Compute.ResourcePolicy("Backups", {
140 * resourcePolicyName: "app-disk-nightly",
141 * region: "us-central1",
142 * description: "nightly disk snapshots",
143 * snapshotSchedulePolicy: {
144 * schedule: {
145 * dailySchedule: { daysInCycle: 1, startTime: "04:00" },
146 * },
147 * retentionPolicy: {
148 * maxRetentionDays: 14,
149 * onSourceDiskDelete: "KEEP_AUTO_SNAPSHOTS",
150 * },
151 * snapshotProperties: {
152 * storageLocations: ["us"],
153 * labels: { env: "prod" },
154 * },
155 * },
156 * });
157 * ```
158 *
159 * ### Instance Schedules
160 * **Example:** Start and stop VMs on weekdays
161 * ```typescript
162 * const hours = yield* GCP.Compute.ResourcePolicy("OfficeHours", {
163 * instanceSchedulePolicy: {
164 * timeZone: "America/Chicago",
165 * vmStartSchedule: { schedule: "0 8 * * 1-5" },
166 * vmStopSchedule: { schedule: "0 18 * * 1-5" },
167 * },
168 * });
169 * ```
170 *
171 * @resource
172 * @category Compute
173 */
174 export const ResourcePolicy = Resource<ResourcePolicy>("GCP.Compute.ResourcePolicy");
175
176 export class ResourcePolicyNotResolved extends Data.TaggedError(
177 "GCP.Compute.ResourcePolicyNotResolved",
178 )<{
179 resourcePolicyName: string;
180 region: string;
181 }> {}
182
183 export class ResourcePolicyNotReady extends Data.TaggedError("GCP.Compute.ResourcePolicyNotReady")<{
184 resourcePolicyName: string;
185 status: string;
186 }> {}
187
188 export class ResourcePolicyFailed extends Data.TaggedError("GCP.Compute.ResourcePolicyFailed")<{
189 resourcePolicyName: string;
190 status: string;
191 }> {}
192
193 export class ResourcePolicyStillExists extends Data.TaggedError(
194 "GCP.Compute.ResourcePolicyStillExists",
195 )<{
196 resourcePolicyName: string;
197 status: string;
198 }> {}
199
200 type PolicyKind = "snapshot" | "instance" | "placement" | "workload" | "consistency" | "none";
201
202 const lastSegment = (value: string | undefined): string => {
203 if (value === undefined || value.length === 0) return "";
204 const trimmed = value.replace(/\/+$/, "");
205 const parts = trimmed.split("/");
206 return parts[parts.length - 1] || trimmed;
207 };
208
209 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
210 lastSegment(region ?? defaultRegion).toLowerCase();
211
212 const toName = (id: string, name: string | undefined, existing?: string) =>
213 Effect.gen(function* () {
214 if (name !== undefined) return name;
215 if (existing !== undefined) return existing;
216 const generated = yield* createPhysicalName({
217 id,
218 maxLength: MAX_NAME_LENGTH,
219 lowercase: true,
220 });
221 return /^[a-z]/.test(generated) ? generated : `p${generated}`.slice(0, MAX_NAME_LENGTH);
222 });
223
224 const encodeDescription = (
225 labels: Record<string, string>,
226 description: string | undefined,
227 ): string => {
228 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
229 return description ? `${marker}\n${description}` : marker;
230 };
231
232 const parseDescription = (
233 description: string | undefined,
234 ): {
235 labels: Record<string, string>;
236 description: string | undefined;
237 } => {
238 if (!description?.startsWith("[alchemy ")) {
239 return { labels: {}, description };
240 }
241 const end = description.indexOf("]");
242 if (end < 0) return { labels: {}, description };
243 const labels: Record<string, string> = {};
244 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
245 const eq = part.indexOf("=");
246 if (eq > 0) {
247 labels[part.slice(0, eq)] = part.slice(eq + 1);
248 }
249 }
250 const rest = description.slice(end + 1).replace(/^\n/, "");
251 return { labels, description: rest.length > 0 ? rest : undefined };
252 };
253
254 const hasOwnershipMarker = (description: string | undefined) =>
255 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
256
257 const policyKindOf = (props: {
258 snapshotSchedulePolicy?: unknown;
259 instanceSchedulePolicy?: unknown;
260 groupPlacementPolicy?: unknown;
261 workloadPolicy?: unknown;
262 diskConsistencyGroupPolicy?: unknown;
263 }): PolicyKind => {
264 if (props.snapshotSchedulePolicy !== undefined) return "snapshot";
265 if (props.instanceSchedulePolicy !== undefined) return "instance";
266 if (props.groupPlacementPolicy !== undefined) return "placement";
267 if (props.workloadPolicy !== undefined) return "workload";
268 if (props.diskConsistencyGroupPolicy !== undefined) return "consistency";
269 return "none";
270 };
271
272 const toBody = (
273 resourcePolicyName: string,
274 props: ResourcePolicyProps,
275 ownership: Record<string, string>,
276 ): compute.ResourcePolicy => ({
277 name: resourcePolicyName,
278 description: encodeDescription(ownership, props.description),
279 snapshotSchedulePolicy: props.snapshotSchedulePolicy,
280 instanceSchedulePolicy: props.instanceSchedulePolicy,
281 groupPlacementPolicy: props.groupPlacementPolicy,
282 workloadPolicy: props.workloadPolicy,
283 diskConsistencyGroupPolicy: props.diskConsistencyGroupPolicy,
284 });
285
286 const toAttrs = (policy: compute.ResourcePolicy, project: string) => {
287 const parsed = parseDescription(policy.description);
288 return {
289 resourcePolicyName: policy.name ?? policy.id ?? "",
290 resourcePolicyId: policy.id,
291 project,
292 region: lastSegment(policy.region).toLowerCase(),
293 description: parsed.description,
294 status: policy.status,
295 snapshotSchedulePolicy: policy.snapshotSchedulePolicy,
296 instanceSchedulePolicy: policy.instanceSchedulePolicy,
297 groupPlacementPolicy: policy.groupPlacementPolicy,
298 workloadPolicy: policy.workloadPolicy,
299 diskConsistencyGroupPolicy: policy.diskConsistencyGroupPolicy,
300 resourceStatus: policy.resourceStatus,
301 selfLink: policy.selfLink,
302 creationTimestamp: policy.creationTimestamp,
303 };
304 };
305
306 const normalizeTime = (value: string | undefined) => {
307 if (value === undefined || value.length === 0) return undefined;
308 const match = value.match(/^(\d{1,2}):(\d{2})/);
309 if (!match) return value;
310 return `${match[1]!.padStart(2, "0")}:${match[2]}`;
311 };
312
313 const sorted = (values: readonly string[] | undefined) =>
314 [...(values ?? [])].map((value) => value.toLowerCase()).sort();
315
316 const canonSnapshot = (policy: SnapshotSchedulePolicy | undefined) => {
317 if (policy === undefined) return undefined;
318 const weekly = [...(policy.schedule?.weeklySchedule?.dayOfWeeks ?? [])]
319 .map((day) => ({
320 day: day.day,
321 startTime: normalizeTime(day.startTime),
322 }))
323 .sort((left, right) => (left.day ?? "").localeCompare(right.day ?? ""));
324 return {
325 retention: policy.retentionPolicy
326 ? {
327 maxRetentionDays: policy.retentionPolicy.maxRetentionDays,
328 onSourceDiskDelete: policy.retentionPolicy.onSourceDiskDelete,
329 }
330 : undefined,
331 properties: policy.snapshotProperties
332 ? {
333 storageLocations: sorted(policy.snapshotProperties.storageLocations),
334 guestFlush: policy.snapshotProperties.guestFlush === true,
335 chainName: policy.snapshotProperties.chainName ?? "",
336 labels: policy.snapshotProperties.labels ?? {},
337 }
338 : undefined,
339 daily: policy.schedule?.dailySchedule
340 ? {
341 daysInCycle: policy.schedule.dailySchedule.daysInCycle,
342 startTime: normalizeTime(policy.schedule.dailySchedule.startTime),
343 }
344 : undefined,
345 weekly: weekly.length > 0 ? weekly : undefined,
346 hourly: policy.schedule?.hourlySchedule
347 ? {
348 hoursInCycle: policy.schedule.hourlySchedule.hoursInCycle,
349 startTime: normalizeTime(policy.schedule.hourlySchedule.startTime),
350 }
351 : undefined,
352 };
353 };
354
355 const canonInstance = (policy: InstanceSchedulePolicy | undefined) => {
356 if (policy === undefined) return undefined;
357 return {
358 timeZone: policy.timeZone,
359 startTime: policy.startTime,
360 expirationTime: policy.expirationTime,
361 vmStart: policy.vmStartSchedule?.schedule,
362 vmStop: policy.vmStopSchedule?.schedule,
363 };
364 };
365
366 const subsetEqual = (observed: unknown, desired: unknown): boolean => {
367 if (desired === undefined) return true;
368 if (typeof desired !== typeof observed) return false;
369 if (desired === null || observed === null) return desired === observed;
370 if (Array.isArray(desired)) {
371 if (!Array.isArray(observed) || desired.length !== observed.length) {
372 return false;
373 }
374 return desired.every((item, index) => subsetEqual(observed[index], item));
375 }
376 if (typeof desired === "object") {
377 if (typeof observed !== "object") return false;
378 const current = observed as Record<string, unknown>;
379 return Object.entries(desired as Record<string, unknown>).every(
380 ([key, value]) => value === undefined || subsetEqual(current[key], value),
381 );
382 }
383 return observed === desired;
384 };
385
386 const sameJson = (left: unknown, right: unknown) =>
387 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
388
389 const snapshotChanged = (
390 observed: SnapshotSchedulePolicy | undefined,
391 desired: SnapshotSchedulePolicy | undefined,
392 ) => {
393 if (desired === undefined) return false;
394 return !subsetEqual(canonSnapshot(observed), canonSnapshot(desired));
395 };
396
397 const instanceChanged = (
398 observed: InstanceSchedulePolicy | undefined,
399 desired: InstanceSchedulePolicy | undefined,
400 ) => {
401 if (desired === undefined) return false;
402 return !subsetEqual(canonInstance(observed), canonInstance(desired));
403 };
404
405 const immutablePolicyChanged = (
406 news: ResourcePolicyProps,
407 olds: Partial<ResourcePolicyProps> | undefined,
408 output: ResourcePolicy["Attributes"] | undefined,
409 ) => {
410 const previousKind = policyKindOf(olds ?? output ?? {});
411 const nextKind = policyKindOf(news);
412 if (nextKind !== "none" && previousKind !== "none" && previousKind !== nextKind) {
413 return true;
414 }
415 if (nextKind === "placement") {
416 return !sameJson(
417 news.groupPlacementPolicy,
418 olds?.groupPlacementPolicy ?? output?.groupPlacementPolicy,
419 );
420 }
421 if (nextKind === "workload") {
422 return !sameJson(news.workloadPolicy, olds?.workloadPolicy ?? output?.workloadPolicy);
423 }
424 if (nextKind === "consistency") {
425 const previous = olds?.diskConsistencyGroupPolicy ?? output?.diskConsistencyGroupPolicy;
426 const next = news.diskConsistencyGroupPolicy;
427 return (previous === undefined) !== (next === undefined);
428 }
429 return false;
430 };
431
432 const getByName = (project: string, region: string, resourcePolicy: string) =>
433 compute
434 .getResourcePolicies({ project, region, resourcePolicy })
435 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
436
437 const waitPolicyReady = (project: string, region: string, resourcePolicyName: string) =>
438 getByName(project, region, resourcePolicyName).pipe(
439 Effect.flatMap((policy) =>
440 policy?.status === "INVALID"
441 ? Effect.fail(
442 new ResourcePolicyFailed({
443 resourcePolicyName,
444 status: "INVALID",
445 }),
446 )
447 : Effect.succeed(policy),
448 ),
449 Effect.filterOrFail(
450 (policy): policy is compute.ResourcePolicy =>
451 policy !== undefined && policy.status === "READY",
452 (policy) =>
453 new ResourcePolicyNotReady({
454 resourcePolicyName,
455 status: policy?.status ?? "MISSING",
456 }),
457 ),
458 Effect.retry({
459 while: (error) => error._tag === "GCP.Compute.ResourcePolicyNotReady",
460 times: 10,
461 schedule: Schedule.spaced("2 seconds"),
462 }),
463 );
464
465 const waitPolicyGone = (project: string, region: string, resourcePolicyName: string) =>
466 getByName(project, region, resourcePolicyName).pipe(
467 Effect.flatMap((policy) =>
468 policy === undefined
469 ? Effect.void
470 : Effect.fail(
471 new ResourcePolicyStillExists({
472 resourcePolicyName,
473 status: policy.status ?? "UNKNOWN",
474 }),
475 ),
476 ),
477 Effect.retry({
478 while: (error) => error instanceof ResourcePolicyStillExists,
479 times: 10,
480 schedule: Schedule.spaced("2 seconds"),
481 }),
482 );
483
484 export const ResourcePolicyProvider = () =>
485 Provider.succeed(ResourcePolicy, {
486 stables: [
487 "resourcePolicyName",
488 "resourcePolicyId",
489 "project",
490 "region",
491 "selfLink",
492 "creationTimestamp",
493 ],
494
495 diff: Effect.fn(function* ({ news, olds, output }) {
496 if (!isResolved(news)) return undefined;
497 const env = yield* GcpEnvironment.current;
498
499 const previousName = olds?.resourcePolicyName ?? output?.resourcePolicyName;
500 const nextName = news.resourcePolicyName ?? previousName;
501 const nameChanged =
502 previousName !== undefined && nextName !== undefined && previousName !== nextName;
503
504 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
505 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
506 const regionChanged = previousRegion !== nextRegion;
507
508 if (nameChanged || regionChanged) {
509 return { action: "replace" as const, deleteFirst: false };
510 }
511 if (immutablePolicyChanged(news, olds, output)) {
512 return { action: "replace" as const, deleteFirst: true };
513 }
514 return undefined;
515 }),
516
517 read: Effect.fn(function* ({ id, olds, output, previous }) {
518 const env = yield* GcpEnvironment.current;
519 const resourcePolicyName = yield* toName(
520 id,
521 olds?.resourcePolicyName,
522 output?.resourcePolicyName,
523 );
524 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
525 const existing = yield* getByName(env.project, region, resourcePolicyName);
526 if (existing === undefined) return undefined;
527 const attrs = toAttrs(existing, env.project);
528 const { labels } = parseDescription(existing.description);
529 return (yield* hasAlchemyLabels(id, labels))
530 ? attrs
531 : unownedUnlessPrevious(attrs, previous, "resourcePolicyName");
532 }),
533
534 list: () =>
535 Effect.gen(function* () {
536 const env = yield* GcpEnvironment.current;
537 const pages = yield* compute.aggregatedListResourcePolicies
538 .pages({
539 project: env.project,
540 returnPartialSuccess: true,
541 maxResults: 500,
542 })
543 .pipe(Stream.runCollect);
544 return Array.from(pages).flatMap((page) =>
545 Object.values(page.items ?? {}).flatMap((scoped) =>
546 (scoped?.resourcePolicies ?? [])
547 .filter((policy) => hasOwnershipMarker(policy.description))
548 .map((policy) => toAttrs(policy, env.project)),
549 ),
550 );
551 }),
552
553 reconcile: Effect.fn(function* ({ id, news, output }) {
554 const env = yield* GcpEnvironment.current;
555 const resourcePolicyName = yield* toName(
556 id,
557 news.resourcePolicyName,
558 output?.resourcePolicyName,
559 );
560 const region = normalizeRegion(news.region ?? output?.region, env.region);
561 const ownership = yield* createInternalLabels(id);
562 const desired = toBody(resourcePolicyName, news, ownership);
563
564 let current = yield* getByName(env.project, region, resourcePolicyName);
565 if (current?.status === "DELETING") {
566 yield* waitPolicyGone(env.project, region, resourcePolicyName);
567 current = undefined;
568 }
569
570 if (current === undefined) {
571 const inserted = yield* compute
572 .insertResourcePolicies({
573 project: env.project,
574 region,
575 body: desired,
576 })
577 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
578 if (inserted !== undefined) {
579 yield* waitRegionOperation(env.project, region, inserted, {
580 ignore: ["RESOURCE_ALREADY_EXISTS"],
581 });
582 }
583 current = yield* waitPolicyReady(env.project, region, resourcePolicyName);
584 }
585
586 if (current === undefined) {
587 return yield* new ResourcePolicyNotResolved({
588 resourcePolicyName,
589 region,
590 });
591 }
592
593 if (current.status === "CREATING") {
594 current = yield* waitPolicyReady(env.project, region, resourcePolicyName);
595 }
596
597 if (current === undefined) {
598 return yield* new ResourcePolicyNotResolved({
599 resourcePolicyName,
600 region,
601 });
602 }
603
604 const descriptionChanged = (current.description ?? "") !== (desired.description ?? "");
605 const snapshotNeedsPatch = snapshotChanged(
606 current.snapshotSchedulePolicy,
607 news.snapshotSchedulePolicy,
608 );
609 const instanceNeedsPatch = instanceChanged(
610 current.instanceSchedulePolicy,
611 news.instanceSchedulePolicy,
612 );
613
614 if (descriptionChanged || snapshotNeedsPatch || instanceNeedsPatch) {
615 const patched = yield* compute.patchResourcePolicies({
616 project: env.project,
617 region,
618 resourcePolicy: resourcePolicyName,
619 body: desired,
620 });
621 yield* waitRegionOperation(env.project, region, patched);
622 current =
623 (yield* getByName(env.project, region, resourcePolicyName)) ??
624 (yield* waitPolicyReady(env.project, region, resourcePolicyName));
625 }
626
627 if (current === undefined) {
628 return yield* new ResourcePolicyNotResolved({
629 resourcePolicyName,
630 region,
631 });
632 }
633
634 return toAttrs(current, env.project);
635 }),
636
637 delete: Effect.fn(function* ({ output }) {
638 const env = yield* GcpEnvironment.current;
639 const project = output.project || env.project;
640 const region = normalizeRegion(output.region, env.region);
641 const deleted = yield* compute
642 .deleteResourcePolicies({
643 project,
644 region,
645 resourcePolicy: output.resourcePolicyName,
646 })
647 .pipe(
648 Effect.catchTag("NotFound", () => Effect.undefined),
649 Effect.retry({
650 while: (error) => error._tag === "Conflict",
651 times: 8,
652 schedule: Schedule.spaced("2 seconds"),
653 }),
654 );
655 if (deleted !== undefined) {
656 yield* waitRegionOperation(project, region, deleted, {
657 ignore: ["RESOURCE_NOT_FOUND"],
658 });
659 }
660 yield* waitPolicyGone(project, region, output.resourcePolicyName);
661 }),
662 });