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

main
ts 752 lines 24.7 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { Unowned } 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 { tagRecord } from "alchemy/Tags";
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 {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { ignoredCodes } from "./internal.ts";
22 import { waitRegionOperation } from "./operations.ts";
23 import type {
24 SecurityPolicyAdaptiveProtectionConfig,
25 SecurityPolicyAdvancedOptionsConfig,
26 SecurityPolicyDdosProtectionConfig,
27 SecurityPolicyRecaptchaOptionsConfig,
28 SecurityPolicyRule,
29 SecurityPolicyRuleMatcher,
30 SecurityPolicyType,
31 SecurityPolicyUserDefinedField,
32 } from "./SecurityPolicy.ts";
33
34 const DEFAULT_TYPE = "CLOUD_ARMOR";
35 const DEFAULT_RULE_PRIORITY = 2147483647;
36 const MAX_NAME_LENGTH = 63;
37
38 export type RegionSecurityPolicyProps = {
39 /**
40 * Policy name (RFC1035, 1-63 characters). If omitted, a unique name is
41 * generated from the stack, stage, and logical id. Changing the name
42 * replaces the policy.
43 */
44 securityPolicyName?: string;
45 /**
46 * Region the policy lives in (e.g. `us-central1`). Immutable — changing
47 * it replaces the policy. `US-CENTRAL1` is accepted and normalized to
48 * `us-central1`.
49 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
50 */
51 region?: string;
52 /**
53 * Intended use of the policy. Set only at create time — changing it
54 * replaces the policy.
55 * @default "CLOUD_ARMOR"
56 */
57 type?: SecurityPolicyType;
58 /**
59 * Optional description. Mutable in place via `regionSecurityPolicies.patch`.
60 */
61 description?: string;
62 /**
63 * User labels. Alchemy ownership labels (`alchemy-stack` /
64 * `alchemy-stage` / `alchemy-id`) are merged in automatically and
65 * synced via `setLabels` (labels cannot be set on insert).
66 */
67 labels?: Record<string, string>;
68 /**
69 * Ordered Cloud Armor rules. There must always be a default rule at
70 * priority `2147483647` matching `*`. If omitted on create, GCP adds
71 * an `allow` default. When this field is set, Alchemy syncs rules with
72 * `addRule` / `patchRule` / `removeRule` (not `patch`). When omitted
73 * on later updates, observed rules are left in place.
74 */
75 rules?: SecurityPolicyRule[];
76 /**
77 * JSON parsing, log level, and related WAF options. Only applied when
78 * set; omitted values leave the observed config in place.
79 */
80 advancedOptionsConfig?: SecurityPolicyAdvancedOptionsConfig;
81 /**
82 * Cloud Armor Adaptive Protection (CAAP). Only applied when set.
83 */
84 adaptiveProtectionConfig?: SecurityPolicyAdaptiveProtectionConfig;
85 /**
86 * reCAPTCHA site key used by `redirect` rules of type
87 * `GOOGLE_RECAPTCHA`. Only applied when set.
88 */
89 recaptchaOptionsConfig?: SecurityPolicyRecaptchaOptionsConfig;
90 /**
91 * Network DDoS protection (`STANDARD` or `ADVANCED`). Only applied
92 * when set.
93 */
94 ddosProtectionConfig?: SecurityPolicyDdosProtectionConfig;
95 /**
96 * Packet field extractors for `CLOUD_ARMOR_NETWORK` policies. Only
97 * applied when set.
98 */
99 userDefinedFields?: SecurityPolicyUserDefinedField[];
100 };
101
102 export type RegionSecurityPolicy = Resource<
103 "GCP.Compute.RegionSecurityPolicy",
104 RegionSecurityPolicyProps,
105 {
106 /** Policy name. */
107 securityPolicyName: string;
108 /** Project id. */
109 project: string;
110 /** Region short name (`us-central1`). */
111 region: string;
112 /** Policy type (`CLOUD_ARMOR`, `CLOUD_ARMOR_EDGE`, …). */
113 type: string;
114 /** Description. */
115 description: string | undefined;
116 /** User labels (Alchemy ownership labels stripped). */
117 labels: Record<string, string>;
118 /** Rules currently attached to the policy (including the default). */
119 rules: SecurityPolicyRule[];
120 /** Advanced WAF options, if configured. */
121 advancedOptionsConfig: SecurityPolicyAdvancedOptionsConfig | undefined;
122 /** Adaptive Protection config, if configured. */
123 adaptiveProtectionConfig: SecurityPolicyAdaptiveProtectionConfig | undefined;
124 /** reCAPTCHA options, if configured. */
125 recaptchaOptionsConfig: SecurityPolicyRecaptchaOptionsConfig | undefined;
126 /** DDoS protection config, if configured. */
127 ddosProtectionConfig: SecurityPolicyDdosProtectionConfig | undefined;
128 /** User-defined packet fields, if configured. */
129 userDefinedFields: SecurityPolicyUserDefinedField[];
130 /** Optimistic-locking fingerprint for metadata patches. */
131 fingerprint: string | undefined;
132 /** Label fingerprint for `setLabels`. */
133 labelFingerprint: string | undefined;
134 /** Server-defined URL. */
135 selfLink: string | undefined;
136 /** Server-assigned numeric id. */
137 securityPolicyId: string | undefined;
138 /** RFC3339 creation timestamp. */
139 creationTimestamp: string | undefined;
140 /** Resource kind. */
141 kind: string | undefined;
142 },
143 never,
144 Providers
145 >;
146
147 /**
148 * A regional Cloud Armor security policy that filters HTTP(S) requests
149 * targeting regional backend services.
150 *
151 * Type and region are immutable — changing either replaces the policy.
152 * Description, advanced options, Adaptive Protection, reCAPTCHA, DDoS
153 * config, and user-defined fields update in place via
154 * `regionSecurityPolicies.patch`. Rules are synced with `addRule` /
155 * `patchRule` / `removeRule` (not `patch`). Labels are applied with
156 * `setLabels` after the policy exists.
157 *
158 * ### Creating a Regional Security Policy
159 * **Example:** Generated name with a deny rule
160 * ```typescript
161 * const policy = yield* GCP.Compute.RegionSecurityPolicy("Armor", {
162 * region: "us-central1",
163 * description: "deny a scanner",
164 * rules: [
165 * {
166 * action: "deny(403)",
167 * priority: 1000,
168 * description: "block scanner",
169 * match: {
170 * versionedExpr: "SRC_IPS_V1",
171 * config: { srcIpRanges: ["9.9.9.0/24"] },
172 * },
173 * },
174 * ],
175 * });
176 * ```
177 *
178 * @resource
179 * @category Compute
180 */
181 export const RegionSecurityPolicy = Resource<RegionSecurityPolicy>(
182 "GCP.Compute.RegionSecurityPolicy",
183 );
184
185 export class RegionSecurityPolicyNotResolved extends Data.TaggedError(
186 "GCP.Compute.RegionSecurityPolicyNotResolved",
187 )<{
188 securityPolicyName: string;
189 region: string;
190 }> {}
191
192 export class RegionSecurityPolicyStillExists extends Data.TaggedError(
193 "GCP.Compute.RegionSecurityPolicyStillExists",
194 )<{
195 securityPolicyName: string;
196 region: string;
197 }> {}
198
199 const lastSegment = (value: string | undefined): string => {
200 if (value === undefined || value.length === 0) return "";
201 const parts = value.split("/");
202 return parts[parts.length - 1] || value;
203 };
204
205 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
206 lastSegment(region ?? defaultRegion).toLowerCase();
207
208 const rfc1035 = (name: string): string => {
209 let next = name
210 .toLowerCase()
211 .replace(/[^a-z0-9-]/g, "-")
212 .replace(/-+/g, "-")
213 .replace(/^-+/, "")
214 .replace(/-+$/, "");
215 if (!/^[a-z]/.test(next)) {
216 next = `s${next}`;
217 }
218 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
219 return next.length > 0 ? next : "policy";
220 };
221
222 const toName = (id: string, name: string | undefined, existing?: string) =>
223 Effect.gen(function* () {
224 if (name !== undefined) return name;
225 if (existing !== undefined) return existing;
226 return rfc1035(
227 yield* createPhysicalName({
228 id,
229 maxLength: MAX_NAME_LENGTH,
230 lowercase: true,
231 }),
232 );
233 });
234
235 const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase();
236
237 const userLabels = (
238 labels: Record<string, string | undefined> | null | undefined,
239 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
240
241 const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort();
242
243 const sameJson = (left: unknown, right: unknown) =>
244 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
245
246 const subsetEqual = (observed: unknown, desired: unknown): boolean => {
247 if (desired === undefined) return true;
248 if (typeof desired !== typeof observed) return false;
249 if (desired === null || observed === null) return desired === observed;
250 if (Array.isArray(desired)) {
251 if (!Array.isArray(observed) || desired.length !== observed.length) {
252 return false;
253 }
254 return desired.every((item, index) => subsetEqual(observed[index], item));
255 }
256 if (typeof desired === "object") {
257 if (typeof observed !== "object") return false;
258 const current = observed as Record<string, unknown>;
259 return Object.entries(desired as Record<string, unknown>).every(
260 ([key, value]) => value === undefined || subsetEqual(current[key], value),
261 );
262 }
263 return observed === desired;
264 };
265
266 const canonMatch = (match: SecurityPolicyRuleMatcher | undefined) => {
267 if (match === undefined) return undefined;
268 return {
269 versionedExpr: match.versionedExpr,
270 config: match.config ? { srcIpRanges: sorted(match.config.srcIpRanges) } : undefined,
271 expr: match.expr,
272 exprOptions: match.exprOptions,
273 };
274 };
275
276 const canonRule = (rule: SecurityPolicyRule) => ({
277 priority: rule.priority,
278 action: rule.action,
279 description: rule.description ?? "",
280 preview: rule.preview === true,
281 match: canonMatch(rule.match),
282 redirectOptions: rule.redirectOptions ?? null,
283 rateLimitOptions: rule.rateLimitOptions ?? null,
284 headerAction: rule.headerAction ?? null,
285 preconfiguredWafConfig: rule.preconfiguredWafConfig ?? null,
286 networkMatch: rule.networkMatch ?? null,
287 });
288
289 const ruleEquals = (left: SecurityPolicyRule, right: SecurityPolicyRule) =>
290 sameJson(canonRule(left), canonRule(right));
291
292 const toRuleBody = (rule: SecurityPolicyRule): SecurityPolicyRule => ({
293 priority: rule.priority,
294 action: rule.action,
295 description: rule.description,
296 preview: rule.preview === true ? true : undefined,
297 match: rule.match,
298 redirectOptions: rule.redirectOptions,
299 rateLimitOptions: rule.rateLimitOptions,
300 headerAction: rule.headerAction,
301 preconfiguredWafConfig: rule.preconfiguredWafConfig,
302 networkMatch: rule.networkMatch,
303 });
304
305 const withDefaultRule = (
306 rules: readonly SecurityPolicyRule[] | undefined,
307 ): SecurityPolicyRule[] | undefined => {
308 if (rules === undefined) return undefined;
309 const bodies = rules.map(toRuleBody);
310 if (bodies.some((rule) => rule.priority === DEFAULT_RULE_PRIORITY)) {
311 return bodies;
312 }
313 return [...bodies, defaultAllowRule()];
314 };
315
316 const defaultAllowRule = (): SecurityPolicyRule => ({
317 action: "allow",
318 priority: DEFAULT_RULE_PRIORITY,
319 match: {
320 versionedExpr: "SRC_IPS_V1",
321 config: { srcIpRanges: ["*"] },
322 },
323 });
324
325 const desiredRules = (
326 news: RegionSecurityPolicyProps,
327 observed: readonly SecurityPolicyRule[],
328 ): SecurityPolicyRule[] | undefined => {
329 if (news.rules === undefined) return undefined;
330 const byPriority = new Map<number, SecurityPolicyRule>();
331 for (const rule of news.rules) {
332 if (rule.priority === undefined) continue;
333 byPriority.set(rule.priority, rule);
334 }
335 if (!byPriority.has(DEFAULT_RULE_PRIORITY)) {
336 const observedDefault = observed.find((rule) => rule.priority === DEFAULT_RULE_PRIORITY);
337 byPriority.set(DEFAULT_RULE_PRIORITY, observedDefault ?? defaultAllowRule());
338 }
339 return [...byPriority.values()].sort(
340 (left, right) => (left.priority ?? 0) - (right.priority ?? 0),
341 );
342 };
343
344 const toAttrs = (policy: compute.SecurityPolicy, project: string) => ({
345 securityPolicyName: policy.name ?? policy.id ?? "",
346 project,
347 region: lastSegment(policy.region).toLowerCase(),
348 type: typeOf(policy.type),
349 description: policy.description,
350 labels: userLabels(policy.labels),
351 rules: policy.rules ?? [],
352 advancedOptionsConfig: policy.advancedOptionsConfig,
353 adaptiveProtectionConfig: policy.adaptiveProtectionConfig,
354 recaptchaOptionsConfig: policy.recaptchaOptionsConfig,
355 ddosProtectionConfig: policy.ddosProtectionConfig,
356 userDefinedFields: policy.userDefinedFields ?? [],
357 fingerprint: policy.fingerprint,
358 labelFingerprint: policy.labelFingerprint,
359 selfLink: policy.selfLink,
360 securityPolicyId: policy.id,
361 creationTimestamp: policy.creationTimestamp,
362 kind: policy.kind,
363 });
364
365 const getByName = (project: string, region: string, securityPolicy: string) =>
366 compute
367 .getRegionSecurityPolicies({ project, region, securityPolicy })
368 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
369
370 const awaitResource = (project: string, region: string, securityPolicyName: string) =>
371 getByName(project, region, securityPolicyName).pipe(
372 Effect.flatMap((policy) =>
373 policy !== undefined
374 ? Effect.succeed(policy)
375 : Effect.fail(
376 new RegionSecurityPolicyNotResolved({
377 securityPolicyName,
378 region,
379 }),
380 ),
381 ),
382 Effect.retry({
383 while: (error) => error._tag === "GCP.Compute.RegionSecurityPolicyNotResolved",
384 times: 8,
385 schedule: Schedule.spaced("1 second"),
386 }),
387 );
388
389 const waitUntilGone = (project: string, region: string, securityPolicyName: string) =>
390 getByName(project, region, securityPolicyName).pipe(
391 Effect.flatMap((policy) =>
392 policy === undefined
393 ? Effect.void
394 : Effect.fail(
395 new RegionSecurityPolicyStillExists({
396 securityPolicyName,
397 region,
398 }),
399 ),
400 ),
401 Effect.retry({
402 while: (error) => error._tag === "GCP.Compute.RegionSecurityPolicyStillExists",
403 times: 10,
404 schedule: Schedule.spaced("1 second"),
405 }),
406 Effect.catchTag("GCP.Compute.RegionSecurityPolicyStillExists", () => Effect.void),
407 );
408
409 const runOp = <E extends { readonly _tag: string }, R>(
410 project: string,
411 region: string,
412 securityPolicyName: string,
413 start: Effect.Effect<compute.Operation, E, R>,
414 options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean },
415 ) =>
416 start.pipe(
417 Effect.flatMap((operation) =>
418 waitRegionOperation(project, region, operation, {
419 ignore: ignoredCodes(options),
420 }),
421 ),
422 Effect.retry({
423 while: (error) => error._tag === "Conflict",
424 times: 5,
425 schedule: Schedule.spaced("1 second"),
426 }),
427 );
428
429 const insertBody = (
430 securityPolicyName: string,
431 news: RegionSecurityPolicyProps,
432 ): compute.SecurityPolicy => ({
433 name: securityPolicyName,
434 description: news.description,
435 type: typeOf(news.type),
436 rules: withDefaultRule(news.rules),
437 advancedOptionsConfig: news.advancedOptionsConfig,
438 adaptiveProtectionConfig: news.adaptiveProtectionConfig,
439 recaptchaOptionsConfig: news.recaptchaOptionsConfig,
440 ddosProtectionConfig: news.ddosProtectionConfig,
441 userDefinedFields: news.userDefinedFields,
442 });
443
444 const syncRules = (
445 project: string,
446 region: string,
447 securityPolicyName: string,
448 observed: readonly SecurityPolicyRule[],
449 desired: readonly SecurityPolicyRule[],
450 ) =>
451 Effect.gen(function* () {
452 const observedByPriority = new Map<number, SecurityPolicyRule>();
453 for (const rule of observed) {
454 if (rule.priority !== undefined) {
455 observedByPriority.set(rule.priority, rule);
456 }
457 }
458 const desiredByPriority = new Map<number, SecurityPolicyRule>();
459 for (const rule of desired) {
460 if (rule.priority !== undefined) {
461 desiredByPriority.set(rule.priority, rule);
462 }
463 }
464
465 for (const [priority, rule] of desiredByPriority) {
466 const current = observedByPriority.get(priority);
467 if (current === undefined) {
468 yield* runOp(
469 project,
470 region,
471 securityPolicyName,
472 compute.addRuleRegionSecurityPolicies({
473 project,
474 region,
475 securityPolicy: securityPolicyName,
476 body: toRuleBody(rule),
477 }),
478 { ignoreAlreadyExists: true },
479 );
480 continue;
481 }
482 if (!ruleEquals(current, rule)) {
483 yield* runOp(
484 project,
485 region,
486 securityPolicyName,
487 compute.patchRuleRegionSecurityPolicies({
488 project,
489 region,
490 securityPolicy: securityPolicyName,
491 priority,
492 body: toRuleBody(rule),
493 }),
494 );
495 }
496 }
497
498 for (const priority of observedByPriority.keys()) {
499 if (desiredByPriority.has(priority)) continue;
500 if (priority === DEFAULT_RULE_PRIORITY) continue;
501 yield* runOp(
502 project,
503 region,
504 securityPolicyName,
505 compute.removeRuleRegionSecurityPolicies({
506 project,
507 region,
508 securityPolicy: securityPolicyName,
509 priority,
510 }),
511 { ignoreNotFound: true },
512 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
513 }
514 });
515
516 export const RegionSecurityPolicyProvider = () =>
517 Provider.succeed(RegionSecurityPolicy, {
518 stables: [
519 "securityPolicyName",
520 "project",
521 "region",
522 "type",
523 "securityPolicyId",
524 "selfLink",
525 "creationTimestamp",
526 ],
527
528 diff: Effect.fn(function* ({ news, olds, output }) {
529 if (!isResolved(news)) return undefined;
530 const env = yield* GcpEnvironment.current;
531
532 const previousName = olds?.securityPolicyName ?? output?.securityPolicyName;
533 const nextName = news.securityPolicyName ?? previousName;
534 const nameChanged =
535 previousName !== undefined && nextName !== undefined && previousName !== nextName;
536
537 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
538 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
539 const regionChanged = previousRegion !== nextRegion;
540
541 const previousType = typeOf(olds?.type ?? output?.type);
542 const nextType = typeOf(news.type ?? output?.type);
543 const typeChanged = previousType !== nextType;
544
545 if (nameChanged) {
546 return { action: "replace" as const, deleteFirst: false };
547 }
548 if (regionChanged || typeChanged) {
549 return { action: "replace" as const, deleteFirst: !regionChanged };
550 }
551 return undefined;
552 }),
553
554 read: Effect.fn(function* ({ id, olds, output }) {
555 const env = yield* GcpEnvironment.current;
556 const securityPolicyName = yield* toName(
557 id,
558 olds?.securityPolicyName,
559 output?.securityPolicyName,
560 );
561 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
562 const existing = yield* getByName(env.project, region, securityPolicyName);
563 if (existing === undefined) return undefined;
564 const attrs = toAttrs(existing, env.project);
565 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
566 }),
567
568 list: () =>
569 Effect.gen(function* () {
570 const env = yield* GcpEnvironment.current;
571 const pages = yield* compute.aggregatedListSecurityPolicies
572 .pages({
573 project: env.project,
574 maxResults: 500,
575 filter: "labels.alchemy-id:*",
576 returnPartialSuccess: true,
577 })
578 .pipe(Stream.runCollect);
579 return Array.from(pages).flatMap((page) =>
580 Object.values(page.items ?? {}).flatMap((scoped) =>
581 (scoped?.securityPolicies ?? [])
582 .filter((policy) => (policy.region ?? "").length > 0)
583 .filter((policy) =>
584 Object.keys(policy.labels ?? {}).some((key) => key.startsWith("alchemy-")),
585 )
586 .map((policy) => toAttrs(policy, env.project)),
587 ),
588 );
589 }),
590
591 reconcile: Effect.fn(function* ({ id, news, output }) {
592 const env = yield* GcpEnvironment.current;
593 const securityPolicyName = yield* toName(
594 id,
595 news.securityPolicyName,
596 output?.securityPolicyName,
597 );
598 const region = normalizeRegion(news.region ?? output?.region, env.region);
599 const desiredLabels = {
600 ...toLabels(news.labels),
601 ...(yield* createInternalLabels(id)),
602 };
603
604 let current = yield* getByName(env.project, region, securityPolicyName);
605
606 if (current === undefined) {
607 yield* compute
608 .insertRegionSecurityPolicies({
609 project: env.project,
610 region,
611 body: insertBody(securityPolicyName, news),
612 })
613 .pipe(
614 Effect.flatMap((operation) =>
615 waitRegionOperation(env.project, region, operation, {
616 ignore: ["RESOURCE_ALREADY_EXISTS"],
617 }),
618 ),
619 Effect.catchTag("Conflict", () => Effect.void),
620 );
621 current = yield* awaitResource(env.project, region, securityPolicyName);
622 }
623
624 if (current === undefined) {
625 return yield* new RegionSecurityPolicyNotResolved({
626 securityPolicyName,
627 region,
628 });
629 }
630
631 const patch: compute.SecurityPolicy = {
632 fingerprint: current.fingerprint,
633 };
634 let needsPatch = false;
635
636 if ((current.description ?? "") !== (news.description ?? "")) {
637 patch.description = news.description ?? "";
638 needsPatch = true;
639 }
640 if (
641 news.advancedOptionsConfig !== undefined &&
642 !subsetEqual(current.advancedOptionsConfig, news.advancedOptionsConfig)
643 ) {
644 patch.advancedOptionsConfig = news.advancedOptionsConfig;
645 needsPatch = true;
646 }
647 if (
648 news.adaptiveProtectionConfig !== undefined &&
649 !subsetEqual(current.adaptiveProtectionConfig, news.adaptiveProtectionConfig)
650 ) {
651 patch.adaptiveProtectionConfig = news.adaptiveProtectionConfig;
652 needsPatch = true;
653 }
654 if (
655 news.recaptchaOptionsConfig !== undefined &&
656 !subsetEqual(current.recaptchaOptionsConfig, news.recaptchaOptionsConfig)
657 ) {
658 patch.recaptchaOptionsConfig = news.recaptchaOptionsConfig;
659 needsPatch = true;
660 }
661 if (
662 news.ddosProtectionConfig !== undefined &&
663 !subsetEqual(current.ddosProtectionConfig, news.ddosProtectionConfig)
664 ) {
665 patch.ddosProtectionConfig = news.ddosProtectionConfig;
666 needsPatch = true;
667 }
668 if (
669 news.userDefinedFields !== undefined &&
670 !sameJson(current.userDefinedFields ?? [], news.userDefinedFields)
671 ) {
672 patch.userDefinedFields = news.userDefinedFields;
673 needsPatch = true;
674 }
675
676 if (needsPatch) {
677 yield* runOp(
678 env.project,
679 region,
680 securityPolicyName,
681 compute.patchRegionSecurityPolicies({
682 project: env.project,
683 region,
684 securityPolicy: securityPolicyName,
685 body: patch,
686 }),
687 );
688 current = (yield* getByName(env.project, region, securityPolicyName)) ?? current;
689 }
690
691 const nextRules = desiredRules(news, current.rules ?? []);
692 if (nextRules !== undefined) {
693 yield* syncRules(env.project, region, securityPolicyName, current.rules ?? [], nextRules);
694 current = (yield* getByName(env.project, region, securityPolicyName)) ?? current;
695 }
696
697 const observedLabels = tagRecord(current.labels);
698 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
699 if (upsert.length > 0 || removed.length > 0) {
700 yield* runOp(
701 env.project,
702 region,
703 securityPolicyName,
704 compute.setLabelsRegionSecurityPolicies({
705 project: env.project,
706 region,
707 resource: securityPolicyName,
708 body: {
709 labels: desiredLabels,
710 labelFingerprint: current.labelFingerprint,
711 },
712 }),
713 );
714 current = (yield* getByName(env.project, region, securityPolicyName)) ?? current;
715 }
716
717 if (current === undefined) {
718 return yield* new RegionSecurityPolicyNotResolved({
719 securityPolicyName,
720 region,
721 });
722 }
723
724 return toAttrs(current, env.project);
725 }),
726
727 delete: Effect.fn(function* ({ output }) {
728 const env = yield* GcpEnvironment.current;
729 const project = output.project || env.project;
730 const region = normalizeRegion(output.region, env.region);
731 yield* compute
732 .deleteRegionSecurityPolicies({
733 project,
734 region,
735 securityPolicy: output.securityPolicyName,
736 })
737 .pipe(
738 Effect.flatMap((operation) =>
739 waitRegionOperation(project, region, operation, {
740 ignore: ["RESOURCE_NOT_FOUND"],
741 }),
742 ),
743 Effect.catchTag("NotFound", () => Effect.void),
744 Effect.retry({
745 while: (error) => error._tag === "Conflict",
746 times: 8,
747 schedule: Schedule.spaced("2 seconds"),
748 }),
749 );
750 yield* waitUntilGone(project, region, output.securityPolicyName);
751 }),
752 });