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

main
ts 741 lines 25.4 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as compute from "@distilled.cloud/gcp/compute_v1";
3 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
14 import type { Providers } from "../Providers.ts";
15 import { ignoredCodes } from "./internal.ts";
16 import { waitOrganizationOperation } from "./operations.ts";
17
18 const DEFAULT_POLICY_TYPE = "VPC_POLICY";
19 const DEFAULT_RULE_PRIORITY = 2147483647;
20 const MAX_NAME_LENGTH = 63;
21
22 export type FirewallPolicyType = compute.FirewallPolicyPolicyTypeEnum | (string & {});
23 export type FirewallPolicyRule = compute.FirewallPolicyRule;
24 export type FirewallPolicyRuleMatcher = compute.FirewallPolicyRuleMatcher;
25 export type FirewallPolicyAssociation = compute.FirewallPolicyAssociation;
26
27 export type FirewallPolicyProps = {
28 /**
29 * User-provided RFC1035 name (`shortName`). Unique within the parent
30 * organization or folder. If omitted, a unique name is generated from
31 * the stack, stage, and logical id. Immutable — changing it replaces
32 * the policy. After create, GCP also assigns a numeric `name`.
33 */
34 shortName?: string;
35 /**
36 * Parent folder or organization. Format `folders/{folder}` or
37 * `organizations/{organization}`. If omitted, Alchemy uses the project
38 * parent from Cloud Resource Manager. Immutable — changing it replaces
39 * the policy.
40 */
41 parent?: string;
42 /**
43 * Optional description. Hierarchical firewall policies have no labels
44 * field, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
45 * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke.
46 */
47 description?: string;
48 /**
49 * Policy type. Set only at create time — changing it replaces the
50 * policy.
51 * @default "VPC_POLICY"
52 */
53 policyType?: FirewallPolicyType;
54 /**
55 * Hierarchical firewall rules. GCP always keeps a default rule at
56 * priority `2147483647` matching all traffic (`goto_next` if you do
57 * not supply one). When this field is set, Alchemy syncs rules with
58 * `addRule` / `patchRule` / `removeRule` (not `patch`). When omitted
59 * on later updates, observed rules are left in place.
60 */
61 rules?: FirewallPolicyRule[];
62 };
63
64 export type FirewallPolicy = Resource<
65 "GCP.Compute.FirewallPolicy",
66 FirewallPolicyProps,
67 {
68 /** User-provided RFC1035 name. */
69 shortName: string;
70 /** Server-assigned numeric policy id (`name` in the API). */
71 firewallPolicyId: string;
72 /** Parent `folders/{folder}` or `organizations/{organization}`. */
73 parent: string;
74 /** Project id of the deploying stack (policies are org/folder scoped). */
75 project: string;
76 /** User description with the Alchemy ownership prefix stripped. */
77 description: string | undefined;
78 /** Policy type (`VPC_POLICY`, `RDMA_ROCE_POLICY`, `ULL_POLICY`). */
79 policyType: string;
80 /** Rules currently attached (including the default). */
81 rules: FirewallPolicyRule[];
82 /** Associations currently attached to this policy. */
83 associations: FirewallPolicyAssociation[];
84 /** Optimistic-locking fingerprint for metadata patches. */
85 fingerprint: string | undefined;
86 /** Server-defined URL. */
87 selfLink: string | undefined;
88 /** Server-defined URL including the numeric id. */
89 selfLinkWithId: string | undefined;
90 /** RFC3339 creation timestamp. */
91 creationTimestamp: string | undefined;
92 /** Total count of rule tuples. */
93 ruleTupleCount: number | undefined;
94 /** Server-assigned numeric id (same as `firewallPolicyId` when present). */
95 id: string | undefined;
96 /** Resource kind. */
97 kind: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A hierarchical firewall policy attached to an organization or folder.
105 *
106 * Policies live under `locations/global/firewallPolicies` and are
107 * identified by a server-assigned numeric id. The user-facing name is
108 * `shortName`. Parent and `shortName` are immutable — changing either
109 * replaces the policy. Description updates in place via
110 * `firewallPolicies.patch`. Rules are synced with `addRule` /
111 * `patchRule` / `removeRule`.
112 *
113 * Compute Engine firewall policies have no resource labels. Alchemy
114 * stamps ownership into the description so `read` / `list` (and
115 * `pnpm nuke:gcp`) can find them.
116 *
117 * ### Creating a Firewall Policy
118 * **Example:** Generated name with an allow rule
119 * ```typescript
120 * const policy = yield* GCP.Compute.FirewallPolicy("OrgFw", {
121 * description: "allow internal http",
122 * rules: [
123 * {
124 * action: "allow",
125 * priority: 1000,
126 * direction: "INGRESS",
127 * match: {
128 * srcIpRanges: ["10.0.0.0/8"],
129 * layer4Configs: [{ ipProtocol: "tcp", ports: ["80"] }],
130 * },
131 * },
132 * ],
133 * });
134 * ```
135 *
136 * **Example:** Named policy under a folder
137 * ```typescript
138 * const policy = yield* GCP.Compute.FirewallPolicy("OrgFw", {
139 * shortName: "app-org-fw",
140 * parent: "folders/123456789",
141 * description: "folder guardrail",
142 * });
143 * ```
144 *
145 * @resource
146 * @category Compute
147 */
148 export const FirewallPolicy = Resource<FirewallPolicy>("GCP.Compute.FirewallPolicy");
149
150 export class FirewallPolicyNotResolved extends Data.TaggedError(
151 "GCP.Compute.FirewallPolicyNotResolved",
152 )<{
153 firewallPolicyId: string;
154 shortName: string;
155 }> {}
156
157 export class FirewallPolicyParentRequired extends Data.TaggedError(
158 "GCP.Compute.FirewallPolicyParentRequired",
159 )<{
160 project: string;
161 }> {}
162
163 export class FirewallPolicyStillExists extends Data.TaggedError(
164 "GCP.Compute.FirewallPolicyStillExists",
165 )<{
166 firewallPolicyId: string;
167 }> {}
168
169 const lastSegment = (value: string | undefined): string => {
170 if (value === undefined || value.length === 0) return "";
171 const trimmed = value.replace(/\/+$/, "");
172 const parts = trimmed.split("/");
173 return parts[parts.length - 1] || trimmed;
174 };
175
176 const rfc1035 = (name: string): string => {
177 let next = name
178 .toLowerCase()
179 .replace(/[^a-z0-9-]/g, "-")
180 .replace(/-+/g, "-")
181 .replace(/^-+/, "")
182 .replace(/-+$/, "");
183 if (!/^[a-z]/.test(next)) {
184 next = `f${next}`;
185 }
186 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
187 return next.length > 0 ? next : "policy";
188 };
189
190 const toName = (id: string, name: string | undefined, existing?: string) =>
191 Effect.gen(function* () {
192 if (name !== undefined) return name;
193 if (existing !== undefined) return existing;
194 return rfc1035(
195 yield* createPhysicalName({
196 id,
197 maxLength: MAX_NAME_LENGTH,
198 lowercase: true,
199 }),
200 );
201 });
202
203 const normalizeParent = (value: string): string => {
204 const trimmed = value.trim().replace(/\/+$/, "");
205 if (trimmed.startsWith("organizations/") || trimmed.startsWith("folders/")) {
206 return trimmed;
207 }
208 if (trimmed.startsWith("organization/")) {
209 return `organizations/${trimmed.slice("organization/".length)}`;
210 }
211 if (trimmed.startsWith("folder/")) {
212 return `folders/${trimmed.slice("folder/".length)}`;
213 }
214 if (/^\d+$/.test(trimmed)) return `organizations/${trimmed}`;
215 return trimmed;
216 };
217
218 const typeOf = (value: string | undefined) => (value ?? DEFAULT_POLICY_TYPE).toUpperCase();
219
220 const encodeDescription = (
221 labels: Record<string, string>,
222 description: string | undefined,
223 ): string => {
224 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
225 return description ? `${marker}\n${description}` : marker;
226 };
227
228 const parseDescription = (
229 description: string | undefined,
230 ): {
231 labels: Record<string, string>;
232 description: string | undefined;
233 } => {
234 if (!description?.startsWith("[alchemy ")) {
235 return { labels: {}, description };
236 }
237 const end = description.indexOf("]");
238 if (end < 0) return { labels: {}, description };
239 const labels: Record<string, string> = {};
240 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
241 const eq = part.indexOf("=");
242 if (eq > 0) {
243 labels[part.slice(0, eq)] = part.slice(eq + 1);
244 }
245 }
246 const rest = description.slice(end + 1).replace(/^\n/, "");
247 return { labels, description: rest.length > 0 ? rest : undefined };
248 };
249
250 const hasOwnershipMarker = (description: string | undefined) =>
251 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
252
253 const projectParent = (project: string) =>
254 resourcemanager.getProjects({ name: `projects/${project}` }).pipe(
255 Effect.map((resource) =>
256 resource.parent !== undefined && resource.parent.length > 0
257 ? normalizeParent(resource.parent)
258 : undefined,
259 ),
260 Effect.catchTag("NotFound", () => Effect.undefined),
261 );
262
263 const resolveParent = (news: FirewallPolicyProps, output: { parent?: string } | undefined) =>
264 Effect.gen(function* () {
265 const explicit = news.parent ?? output?.parent;
266 if (explicit !== undefined && explicit.length > 0) {
267 return normalizeParent(explicit);
268 }
269 const env = yield* GcpEnvironment.current;
270 const fromProject = yield* projectParent(env.project);
271 if (fromProject !== undefined) return fromProject;
272 return yield* new FirewallPolicyParentRequired({ project: env.project });
273 });
274
275 const listParents = (project: string) =>
276 Effect.gen(function* () {
277 const parents = new Set<string>();
278 const fromProject = yield* projectParent(project);
279 if (fromProject !== undefined) parents.add(fromProject);
280 return [...parents];
281 });
282
283 const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort();
284
285 const sameJson = (left: unknown, right: unknown) =>
286 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
287
288 const canonMatch = (match: FirewallPolicyRuleMatcher | undefined) => {
289 if (match === undefined) return undefined;
290 return {
291 srcIpRanges: sorted(match.srcIpRanges),
292 destIpRanges: sorted(match.destIpRanges),
293 srcFqdns: sorted(match.srcFqdns),
294 destFqdns: sorted(match.destFqdns),
295 srcRegionCodes: sorted(match.srcRegionCodes),
296 destRegionCodes: sorted(match.destRegionCodes),
297 srcAddressGroups: sorted(match.srcAddressGroups),
298 destAddressGroups: sorted(match.destAddressGroups),
299 srcThreatIntelligences: sorted(match.srcThreatIntelligences),
300 destThreatIntelligences: sorted(match.destThreatIntelligences),
301 srcNetworks: sorted(match.srcNetworks),
302 srcNetworkType: match.srcNetworkType,
303 destNetworkType: match.destNetworkType,
304 srcNetworkContext: match.srcNetworkContext,
305 destNetworkContext: match.destNetworkContext,
306 layer4Configs: [...(match.layer4Configs ?? [])]
307 .map((config) => ({
308 ipProtocol: (config.ipProtocol ?? "").toLowerCase(),
309 ports: sorted(config.ports),
310 }))
311 .sort(
312 (left, right) =>
313 left.ipProtocol.localeCompare(right.ipProtocol) ||
314 JSON.stringify(left.ports).localeCompare(JSON.stringify(right.ports)),
315 ),
316 srcSecureTags: [...(match.srcSecureTags ?? [])].map((tag) => tag.name ?? "").sort(),
317 };
318 };
319
320 const canonRule = (rule: FirewallPolicyRule) => ({
321 priority: rule.priority,
322 action: rule.action,
323 description: rule.description ?? "",
324 direction: (rule.direction ?? "INGRESS").toUpperCase(),
325 enableLogging: rule.enableLogging === true,
326 disabled: rule.disabled === true,
327 ruleName: rule.ruleName ?? "",
328 tlsInspect: rule.tlsInspect === true,
329 targetType: rule.targetType ?? "INSTANCES",
330 securityProfileGroup: rule.securityProfileGroup ?? "",
331 match: canonMatch(rule.match),
332 targetResources: sorted(rule.targetResources),
333 targetServiceAccounts: sorted(rule.targetServiceAccounts),
334 targetForwardingRules: sorted(rule.targetForwardingRules),
335 targetSecureTags: [...(rule.targetSecureTags ?? [])].map((tag) => tag.name ?? "").sort(),
336 });
337
338 const ruleEquals = (left: FirewallPolicyRule, right: FirewallPolicyRule) =>
339 sameJson(canonRule(left), canonRule(right));
340
341 const toRuleBody = (rule: FirewallPolicyRule): FirewallPolicyRule => ({
342 priority: rule.priority,
343 action: rule.action,
344 description: rule.description,
345 direction: rule.direction,
346 enableLogging: rule.enableLogging === true ? true : undefined,
347 disabled: rule.disabled === true ? true : undefined,
348 ruleName: rule.ruleName,
349 tlsInspect: rule.tlsInspect === true ? true : undefined,
350 targetType: rule.targetType,
351 securityProfileGroup: rule.securityProfileGroup,
352 match: rule.match,
353 targetResources: rule.targetResources,
354 targetServiceAccounts: rule.targetServiceAccounts,
355 targetForwardingRules: rule.targetForwardingRules,
356 targetSecureTags: rule.targetSecureTags,
357 });
358
359 const desiredRules = (
360 news: FirewallPolicyProps,
361 observed: readonly FirewallPolicyRule[],
362 ): FirewallPolicyRule[] | undefined => {
363 if (news.rules === undefined) return undefined;
364 const byPriority = new Map<number, FirewallPolicyRule>();
365 for (const rule of news.rules) {
366 if (rule.priority === undefined) continue;
367 byPriority.set(rule.priority, rule);
368 }
369 if (!byPriority.has(DEFAULT_RULE_PRIORITY)) {
370 const observedDefault = observed.find((rule) => rule.priority === DEFAULT_RULE_PRIORITY);
371 if (observedDefault !== undefined) {
372 byPriority.set(DEFAULT_RULE_PRIORITY, observedDefault);
373 }
374 }
375 return [...byPriority.values()].sort(
376 (left, right) => (left.priority ?? 0) - (right.priority ?? 0),
377 );
378 };
379
380 const policyIdOf = (policy: compute.FirewallPolicy) =>
381 policy.name ?? policy.id ?? lastSegment(policy.selfLinkWithId);
382
383 const toAttrs = (policy: compute.FirewallPolicy, project: string): FirewallPolicy["Attributes"] => {
384 const parsed = parseDescription(policy.description);
385 return {
386 shortName: policy.shortName ?? policy.displayName ?? "",
387 firewallPolicyId: policyIdOf(policy),
388 parent: policy.parent ?? "",
389 project,
390 description: parsed.description,
391 policyType: typeOf(policy.policyType),
392 rules: policy.rules ?? [],
393 associations: policy.associations ?? [],
394 fingerprint: policy.fingerprint,
395 selfLink: policy.selfLink,
396 selfLinkWithId: policy.selfLinkWithId,
397 creationTimestamp: policy.creationTimestamp,
398 ruleTupleCount: policy.ruleTupleCount,
399 id: policy.id,
400 kind: policy.kind,
401 };
402 };
403
404 const getById = (firewallPolicy: string) =>
405 compute
406 .getFirewallPolicies({ firewallPolicy })
407 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
408
409 const findByShortName = (parentId: string, shortName: string) =>
410 compute.listFirewallPolicies
411 .items({
412 parentId,
413 maxResults: 500,
414 returnPartialSuccess: true,
415 })
416 .pipe(
417 Stream.filter((policy) => policy.shortName === shortName),
418 Stream.runCollect,
419 Effect.map((chunk) => Array.from(chunk)[0]),
420 Effect.catchTag("NotFound", () => Effect.undefined),
421 );
422
423 const observe = (firewallPolicyId: string | undefined, parentId: string, shortName: string) =>
424 Effect.gen(function* () {
425 if (firewallPolicyId !== undefined && firewallPolicyId.length > 0) {
426 const existing = yield* getById(firewallPolicyId);
427 if (existing !== undefined) return existing;
428 }
429 return yield* findByShortName(parentId, shortName);
430 });
431
432 const awaitResource = (firewallPolicyId: string, parentId: string, shortName: string) =>
433 observe(firewallPolicyId, parentId, shortName).pipe(
434 Effect.flatMap((policy) =>
435 policy !== undefined
436 ? Effect.succeed(policy)
437 : Effect.fail(new FirewallPolicyNotResolved({ firewallPolicyId, shortName })),
438 ),
439 Effect.retry({
440 while: (error) => error._tag === "GCP.Compute.FirewallPolicyNotResolved",
441 times: 8,
442 schedule: Schedule.spaced("1 second"),
443 }),
444 );
445
446 const waitUntilGone = (firewallPolicyId: string) =>
447 getById(firewallPolicyId).pipe(
448 Effect.flatMap((policy) =>
449 policy === undefined
450 ? Effect.void
451 : Effect.fail(new FirewallPolicyStillExists({ firewallPolicyId })),
452 ),
453 Effect.retry({
454 while: (error) => error._tag === "GCP.Compute.FirewallPolicyStillExists",
455 times: 10,
456 schedule: Schedule.spaced("1 second"),
457 }),
458 Effect.catchTag("GCP.Compute.FirewallPolicyStillExists", () => Effect.void),
459 );
460
461 const runOp = <E extends { readonly _tag: string }, R>(
462 firewallPolicyId: string,
463 parentId: string,
464 start: Effect.Effect<compute.Operation, E, R>,
465 options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean },
466 ) =>
467 start.pipe(
468 Effect.flatMap((operation) =>
469 waitOrganizationOperation(operation, parentId, {
470 ignore: ignoredCodes(options),
471 }),
472 ),
473 Effect.retry({
474 while: (error) => error._tag === "Conflict",
475 times: 5,
476 schedule: Schedule.spaced("1 second"),
477 }),
478 );
479
480 const insertBody = (
481 shortName: string,
482 news: FirewallPolicyProps,
483 description: string,
484 ): compute.FirewallPolicy => ({
485 shortName,
486 description,
487 policyType: typeOf(news.policyType),
488 rules: news.rules !== undefined ? news.rules.map(toRuleBody) : undefined,
489 });
490
491 const idFromOperation = (operation: compute.Operation) => {
492 if (operation.targetId !== undefined && operation.targetId.length > 0) {
493 return operation.targetId;
494 }
495 const fromLink = lastSegment(operation.targetLink);
496 return fromLink.length > 0 ? fromLink : "";
497 };
498
499 const syncRules = (
500 firewallPolicyId: string,
501 parentId: string,
502 observed: readonly FirewallPolicyRule[],
503 desired: readonly FirewallPolicyRule[],
504 ) =>
505 Effect.gen(function* () {
506 const observedByPriority = new Map<number, FirewallPolicyRule>();
507 for (const rule of observed) {
508 if (rule.priority !== undefined) {
509 observedByPriority.set(rule.priority, rule);
510 }
511 }
512 const desiredByPriority = new Map<number, FirewallPolicyRule>();
513 for (const rule of desired) {
514 if (rule.priority !== undefined) {
515 desiredByPriority.set(rule.priority, rule);
516 }
517 }
518
519 for (const [priority, rule] of desiredByPriority) {
520 const current = observedByPriority.get(priority);
521 if (current === undefined) {
522 yield* runOp(
523 firewallPolicyId,
524 parentId,
525 compute.addRuleFirewallPolicies({
526 firewallPolicy: firewallPolicyId,
527 body: toRuleBody(rule),
528 }),
529 { ignoreAlreadyExists: true },
530 );
531 continue;
532 }
533 if (!ruleEquals(current, rule)) {
534 yield* runOp(
535 firewallPolicyId,
536 parentId,
537 compute.patchRuleFirewallPolicies({
538 firewallPolicy: firewallPolicyId,
539 priority,
540 body: toRuleBody(rule),
541 }),
542 );
543 }
544 }
545
546 for (const priority of observedByPriority.keys()) {
547 if (desiredByPriority.has(priority)) continue;
548 if (priority === DEFAULT_RULE_PRIORITY) continue;
549 yield* runOp(
550 firewallPolicyId,
551 parentId,
552 compute.removeRuleFirewallPolicies({
553 firewallPolicy: firewallPolicyId,
554 priority,
555 }),
556 { ignoreNotFound: true },
557 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
558 }
559 });
560
561 export const FirewallPolicyProvider = () =>
562 Provider.succeed(FirewallPolicy, {
563 stables: [
564 "shortName",
565 "firewallPolicyId",
566 "parent",
567 "project",
568 "policyType",
569 "id",
570 "selfLink",
571 "selfLinkWithId",
572 "creationTimestamp",
573 ],
574
575 diff: Effect.fn(function* ({ news, olds, output }) {
576 if (!isResolved(news)) return undefined;
577
578 const previousName = olds?.shortName ?? output?.shortName;
579 const nextName = news.shortName ?? previousName;
580 const nameChanged =
581 previousName !== undefined && nextName !== undefined && previousName !== nextName;
582
583 const previousParent = olds?.parent ?? output?.parent;
584 const nextParent = news.parent !== undefined ? normalizeParent(news.parent) : previousParent;
585 const parentChanged =
586 previousParent !== undefined &&
587 nextParent !== undefined &&
588 normalizeParent(previousParent) !== normalizeParent(nextParent);
589
590 const previousType = typeOf(olds?.policyType ?? output?.policyType);
591 const nextType = typeOf(news.policyType ?? output?.policyType);
592 const typeChanged = previousType !== nextType;
593
594 if (nameChanged) {
595 return { action: "replace" as const, deleteFirst: false };
596 }
597 if (parentChanged || typeChanged) {
598 return { action: "replace" as const, deleteFirst: true };
599 }
600 return undefined;
601 }),
602
603 read: Effect.fn(function* ({ id, olds, output, previous }) {
604 const env = yield* GcpEnvironment.current;
605 const shortName = yield* toName(id, olds?.shortName, output?.shortName);
606 const parent = yield* resolveParent(olds ?? {}, output).pipe(
607 Effect.catchTag("GCP.Compute.FirewallPolicyParentRequired", () =>
608 Effect.succeed(output?.parent ?? olds?.parent ?? ""),
609 ),
610 );
611 const existing = yield* observe(output?.firewallPolicyId, parent, shortName);
612 if (existing === undefined) return undefined;
613 const attrs = toAttrs(existing, env.project);
614 const { labels } = parseDescription(existing.description);
615 return (yield* hasAlchemyLabels(id, labels))
616 ? attrs
617 : unownedUnlessPrevious(attrs, previous, "shortName");
618 }),
619
620 list: () =>
621 Effect.gen(function* () {
622 const env = yield* GcpEnvironment.current;
623 const parents = yield* listParents(env.project);
624 if (parents.length === 0) return [];
625 const listed: FirewallPolicy["Attributes"][] = [];
626 for (const parentId of parents) {
627 const chunk = yield* compute.listFirewallPolicies
628 .items({
629 parentId,
630 maxResults: 500,
631 returnPartialSuccess: true,
632 })
633 .pipe(
634 Stream.filter((policy) => hasOwnershipMarker(policy.description)),
635 Stream.map((policy) => toAttrs(policy, env.project)),
636 Stream.runCollect,
637 Effect.map((items) => Array.from(items)),
638 Effect.catchTag("NotFound", () =>
639 Effect.succeed([] as FirewallPolicy["Attributes"][]),
640 ),
641 );
642 listed.push(...chunk);
643 }
644 return listed;
645 }),
646
647 reconcile: Effect.fn(function* ({ id, news, output }) {
648 const env = yield* GcpEnvironment.current;
649 const shortName = yield* toName(id, news.shortName, output?.shortName);
650 const parentId = yield* resolveParent(news, output);
651 const ownership = yield* createInternalLabels(id);
652 const desiredDescription = encodeDescription(ownership, news.description);
653
654 let current = yield* observe(output?.firewallPolicyId, parentId, shortName);
655
656 if (current === undefined) {
657 const inserted = yield* compute
658 .insertFirewallPolicies({
659 parentId,
660 body: insertBody(shortName, news, desiredDescription),
661 })
662 .pipe(
663 Effect.flatMap((operation) =>
664 waitOrganizationOperation(operation, parentId, {
665 ignore: ["RESOURCE_ALREADY_EXISTS"],
666 }),
667 ),
668 Effect.catchTag("Conflict", () => Effect.undefined),
669 );
670 const createdId = inserted !== undefined ? idFromOperation(inserted) : "";
671 current = yield* awaitResource(
672 createdId.length > 0 ? createdId : (output?.firewallPolicyId ?? ""),
673 parentId,
674 shortName,
675 );
676 }
677
678 if (current === undefined) {
679 return yield* new FirewallPolicyNotResolved({
680 firewallPolicyId: output?.firewallPolicyId ?? "",
681 shortName,
682 });
683 }
684
685 const firewallPolicyId = policyIdOf(current);
686
687 if ((current.description ?? "") !== desiredDescription) {
688 yield* runOp(
689 firewallPolicyId,
690 parentId,
691 compute.patchFirewallPolicies({
692 firewallPolicy: firewallPolicyId,
693 body: {
694 description: desiredDescription,
695 fingerprint: current.fingerprint,
696 },
697 }),
698 );
699 current = (yield* getById(firewallPolicyId)) ?? current;
700 }
701
702 const nextRules = desiredRules(news, current.rules ?? []);
703 if (nextRules !== undefined) {
704 yield* syncRules(firewallPolicyId, parentId, current.rules ?? [], nextRules);
705 current = (yield* getById(firewallPolicyId)) ?? current;
706 }
707
708 if (current === undefined) {
709 return yield* new FirewallPolicyNotResolved({
710 firewallPolicyId,
711 shortName,
712 });
713 }
714
715 return toAttrs(current, env.project);
716 }),
717
718 delete: Effect.fn(function* ({ output }) {
719 const firewallPolicyId = output.firewallPolicyId;
720 if (firewallPolicyId.length === 0) return;
721 const parentId = output.parent.length > 0 ? normalizeParent(output.parent) : undefined;
722 yield* compute
723 .deleteFirewallPolicies({
724 firewallPolicy: firewallPolicyId,
725 })
726 .pipe(
727 Effect.flatMap((operation) =>
728 waitOrganizationOperation(operation, parentId ?? "", {
729 ignore: ["RESOURCE_NOT_FOUND"],
730 }),
731 ),
732 Effect.catchTag("NotFound", () => Effect.void),
733 Effect.retry({
734 while: (error) => error._tag === "Conflict",
735 times: 8,
736 schedule: Schedule.spaced("2 seconds"),
737 }),
738 );
739 yield* waitUntilGone(firewallPolicyId);
740 }),
741 });