@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 710 lines 26 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 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20 import { waitRegionOperation } from "./operations.ts";
21
22 const DEFAULT_CONNECTION_PREFERENCE = "ACCEPT_AUTOMATIC";
23 const MAX_NAME_LENGTH = 63;
24
25 export type ServiceAttachmentConnectionPreference =
26 | compute.ServiceAttachmentConnectionPreferenceEnum
27 | (string & {});
28
29 export type ServiceAttachmentConsumerAccept = {
30 /** Consumer project id or number allowed to connect. */
31 projectIdOrNum?: string;
32 /** Consumer network URL allowed to connect. */
33 networkUrl?: string;
34 /** Consumer endpoint URL allowed to connect. */
35 endpointUrl?: string;
36 /** Max consumer forwarding rules (or 1 for an endpoint). */
37 connectionLimit?: number;
38 };
39
40 export type ServiceAttachmentConnectedEndpoint = {
41 /** Connection status (`PENDING`, `ACCEPTED`, `REJECTED`, …). */
42 status: string | undefined;
43 /** Consumer forwarding-rule URL. */
44 endpoint: string | undefined;
45 /** Consumer network URL. */
46 consumerNetwork: string | undefined;
47 /** PSC connection id. */
48 pscConnectionId: string | undefined;
49 /** Propagated NCC spoke count. */
50 propagatedConnectionCount: number | undefined;
51 /** NAT IPs of the connected endpoint. */
52 natIps: ReadonlyArray<string>;
53 };
54
55 export type ServiceAttachmentProps = {
56 /**
57 * Service attachment name (RFC1035, 1-63 characters). If omitted, a
58 * unique name is generated from the stack, stage, and logical id.
59 * Immutable — changing it replaces the attachment.
60 */
61 serviceAttachmentName?: string;
62 /**
63 * Region the attachment lives in. Immutable — changing it replaces
64 * the attachment. `US-CENTRAL1` is accepted and normalized to
65 * `us-central1`.
66 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
67 */
68 region?: string;
69 /**
70 * Optional description. Compute service attachments have no labels
71 * field, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
72 * `alchemy-id`) plus user `labels` are stored in a `[alchemy …]`
73 * prefix for `list` / nuke. Updated in place via `patch`.
74 */
75 description?: string;
76 /**
77 * URL of the producer forwarding rule (or other target service) this
78 * attachment exposes. Required. Names are expanded to
79 * `projects/{project}/regions/{region}/forwardingRules/{name}`.
80 * Updated in place via `patch`.
81 */
82 targetService: string;
83 /**
84 * Subnet URLs or names the producer provides for PSC NAT. Each subnet
85 * must have purpose `PRIVATE_SERVICE_CONNECT`. Required. Updated in
86 * place via `patch`.
87 */
88 natSubnets: string[];
89 /**
90 * How consumer connections are admitted.
91 * `ACCEPT_AUTOMATIC` always accepts; `ACCEPT_MANUAL` uses the accept
92 * and reject lists.
93 * @default "ACCEPT_AUTOMATIC"
94 */
95 connectionPreference?: ServiceAttachmentConnectionPreference;
96 /**
97 * Send PROXY protocol v1 headers to backends. Must be `false` for
98 * passthrough internal load balancers.
99 * @default false
100 */
101 enableProxyProtocol?: boolean;
102 /**
103 * Projects, networks, or endpoints allowed to connect, each with a
104 * connection limit. Used with `ACCEPT_MANUAL`. A given attachment
105 * manages connections at one level — projects, networks, or
106 * endpoints — not mixed. Updated in place via `patch`.
107 */
108 consumerAcceptLists?: ServiceAttachmentConsumerAccept[];
109 /**
110 * Projects or networks that must not connect. Must use the same
111 * level as `consumerAcceptLists`. Updated in place via `patch`.
112 */
113 consumerRejectLists?: string[];
114 /**
115 * When `true`, accept/reject-list changes also move existing
116 * `ACCEPTED` / `REJECTED` endpoints. When `false`, only `PENDING`
117 * endpoints are affected. Updated in place via `patch`.
118 */
119 reconcileConnections?: boolean;
120 /**
121 * Max Network Connectivity Center spokes a connected endpoint may
122 * propagate to. Default `250` when omitted.
123 */
124 propagatedConnectionLimit?: number;
125 /**
126 * NAT IPs allocated per connected endpoint.
127 * @default 1
128 */
129 natIpsPerEndpoint?: number;
130 /**
131 * DNS domain names used when integrating connected endpoints with
132 * Cloud DNS (max 1, for example `p.mycompany.com.`). Immutable —
133 * changing them replaces the attachment.
134 */
135 domainNames?: string[];
136 /**
137 * User labels. Packed into the description marker (and `metadata`)
138 * together with Alchemy ownership labels.
139 */
140 labels?: Record<string, string>;
141 };
142
143 export type ServiceAttachment = Resource<
144 "GCP.Compute.ServiceAttachment",
145 ServiceAttachmentProps,
146 {
147 /** Service attachment name. */
148 serviceAttachmentName: string;
149 /** Project id. */
150 project: string;
151 /** Region short name (`us-central1`). */
152 region: string;
153 /** Server-assigned numeric id. */
154 serviceAttachmentId: string | undefined;
155 /** Resource self-link. */
156 selfLink: string | undefined;
157 /** User description with the Alchemy ownership prefix stripped. */
158 description: string | undefined;
159 /** Producer forwarding rule / target service URL. */
160 targetService: string | undefined;
161 /** Producer forwarding-rule URL, if the API reports it separately. */
162 producerForwardingRule: string | undefined;
163 /** NAT subnet URLs. */
164 natSubnets: ReadonlyArray<string>;
165 /** Connection preference. */
166 connectionPreference: string | undefined;
167 /** Whether PROXY protocol is enabled. */
168 enableProxyProtocol: boolean;
169 /** Accepted consumers. */
170 consumerAcceptLists: ReadonlyArray<ServiceAttachmentConsumerAccept>;
171 /** Rejected projects or networks. */
172 consumerRejectLists: ReadonlyArray<string>;
173 /** Whether list changes reconcile existing endpoints. */
174 reconcileConnections: boolean;
175 /** Propagated connection limit. */
176 propagatedConnectionLimit: number | undefined;
177 /** NAT IPs per connected endpoint. */
178 natIpsPerEndpoint: number | undefined;
179 /** Cloud DNS domain names. */
180 domainNames: ReadonlyArray<string>;
181 /** Connected consumer endpoints. */
182 connectedEndpoints: ReadonlyArray<ServiceAttachmentConnectedEndpoint>;
183 /** 128-bit PSC service-attachment id. */
184 pscServiceAttachmentId: { high: string | undefined; low: string | undefined } | undefined;
185 /** User labels (Alchemy ownership labels stripped). */
186 labels: Record<string, string>;
187 /** RFC3339 creation timestamp. */
188 creationTimestamp: string | undefined;
189 /** Resource kind. */
190 kind: string | undefined;
191 },
192 never,
193 Providers
194 >;
195
196 /**
197 * A regional Compute Engine Private Service Connect service attachment.
198 *
199 * A service attachment is how a producer exposes an internal load
200 * balancer (or other target service) to consumers over Private Service
201 * Connect. It points at a producer forwarding rule, lists NAT subnets
202 * with purpose `PRIVATE_SERVICE_CONNECT`, and admits consumers either
203 * automatically or via accept/reject lists.
204 *
205 * Compute ServiceAttachment has no labels field — Alchemy ownership is
206 * stored in the description so nuke can find leaked attachments.
207 *
208 * ### Creating a Service Attachment
209 * **Example:** Generated name, automatic accept
210 * ```typescript
211 * const attachment = yield* GCP.Compute.ServiceAttachment("Producer", {
212 * region: "us-central1",
213 * targetService: forwardingRule.selfLink,
214 * natSubnets: [natSubnet.selfLink],
215 * connectionPreference: "ACCEPT_AUTOMATIC",
216 * enableProxyProtocol: false,
217 * });
218 * ```
219 *
220 * **Example:** Named attachment with labels
221 * ```typescript
222 * const attachment = yield* GCP.Compute.ServiceAttachment("Producer", {
223 * serviceAttachmentName: "app-psc",
224 * region: "us-central1",
225 * targetService: forwardingRule.selfLink,
226 * natSubnets: [natSubnet.selfLink],
227 * description: "private service connect",
228 * labels: { env: "prod" },
229 * });
230 * ```
231 *
232 * ### Manual admission
233 * **Example:** Accept a consumer project
234 * ```typescript
235 * const attachment = yield* GCP.Compute.ServiceAttachment("Producer", {
236 * targetService: forwardingRule.selfLink,
237 * natSubnets: [natSubnet.selfLink],
238 * connectionPreference: "ACCEPT_MANUAL",
239 * consumerAcceptLists: [
240 * { projectIdOrNum: "my-consumer-project", connectionLimit: 10 },
241 * ],
242 * reconcileConnections: true,
243 * });
244 * ```
245 *
246 * @resource
247 * @category Compute
248 */
249 export const ServiceAttachment = Resource<ServiceAttachment>("GCP.Compute.ServiceAttachment");
250
251 export class ServiceAttachmentNotResolved extends Data.TaggedError(
252 "GCP.Compute.ServiceAttachmentNotResolved",
253 )<{
254 serviceAttachmentName: string;
255 region: string;
256 }> {}
257
258 export class ServiceAttachmentPending extends Data.TaggedError(
259 "GCP.Compute.ServiceAttachmentPending",
260 )<{
261 serviceAttachmentName: string;
262 status: string;
263 }> {}
264
265 const userLabels = (
266 labels: Record<string, string | undefined> | null | undefined,
267 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
268
269 const lastSegment = (value: string | undefined) => {
270 if (!value) return "";
271 const trimmed = value.replace(/\/+$/, "");
272 const parts = trimmed.split("/");
273 return parts[parts.length - 1] || trimmed;
274 };
275
276 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
277 lastSegment(region ?? defaultRegion).toLowerCase();
278
279 const resourceRefOf = (value: string | undefined) => lastSegment(value);
280
281 const refsKey = (values: ReadonlyArray<string> | undefined) =>
282 [...(values ?? [])]
283 .map((value) => resourceRefOf(value))
284 .filter((value) => value.length > 0)
285 .sort()
286 .join(",");
287
288 const connectionPreferenceOf = (value: string | undefined) =>
289 value && value.length > 0 ? value : DEFAULT_CONNECTION_PREFERENCE;
290
291 const domainNamesKey = (names: ReadonlyArray<string> | undefined) =>
292 [...(names ?? [])].map(String).sort().join(",");
293
294 const acceptKey = (item: ServiceAttachmentConsumerAccept) =>
295 JSON.stringify({
296 projectIdOrNum: item.projectIdOrNum ?? "",
297 networkUrl: resourceRefOf(item.networkUrl),
298 endpointUrl: resourceRefOf(item.endpointUrl),
299 connectionLimit: item.connectionLimit ?? 0,
300 });
301
302 const acceptListsKey = (lists: ReadonlyArray<ServiceAttachmentConsumerAccept> | undefined) =>
303 JSON.stringify([...(lists ?? [])].map(acceptKey).sort());
304
305 const encodeDescription = (user: string | undefined, labels: Record<string, string>): string => {
306 const packed = Object.entries(labels)
307 .sort(([left], [right]) => left.localeCompare(right))
308 .map(([key, value]) => `${key}=${value}`)
309 .join(" ");
310 const marker = `[alchemy ${packed}]`;
311 return user ? `${marker}\n${user}` : marker;
312 };
313
314 const parseDescription = (
315 description: string | undefined,
316 ): { labels: Record<string, string>; user: string | undefined } => {
317 if (!description?.startsWith("[alchemy ")) {
318 return { labels: {}, user: description };
319 }
320 const end = description.indexOf("]");
321 if (end < 0) return { labels: {}, user: description };
322 const labels: Record<string, string> = {};
323 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
324 const eq = part.indexOf("=");
325 if (eq > 0) {
326 labels[part.slice(0, eq)] = part.slice(eq + 1);
327 }
328 }
329 const rest = description.slice(end + 1).replace(/^\n/, "");
330 return { labels, user: rest.length > 0 ? rest : undefined };
331 };
332
333 const hasOwnershipMarker = (description: string | undefined): boolean =>
334 (description ?? "").startsWith("[alchemy ");
335
336 const toName = (id: string, name: string | undefined, existing?: string) =>
337 Effect.gen(function* () {
338 if (name !== undefined) return name;
339 if (existing !== undefined) return existing;
340 const generated = yield* createPhysicalName({
341 id,
342 maxLength: MAX_NAME_LENGTH,
343 lowercase: true,
344 });
345 return /^[a-z]/.test(generated) ? generated : `s${generated}`.slice(0, MAX_NAME_LENGTH);
346 });
347
348 const toForwardingRuleUrl = (project: string, region: string, value: string) => {
349 if (value.includes("/")) return value;
350 return `projects/${project}/regions/${region}/forwardingRules/${value}`;
351 };
352
353 const toSubnetworkUrl = (project: string, region: string, value: string) => {
354 if (value.includes("/")) return value;
355 return `projects/${project}/regions/${region}/subnetworks/${value}`;
356 };
357
358 const toConnectedEndpoint = (
359 endpoint: compute.ServiceAttachmentConnectedEndpoint,
360 ): ServiceAttachmentConnectedEndpoint => ({
361 status: endpoint.status,
362 endpoint: endpoint.endpoint,
363 consumerNetwork: endpoint.consumerNetwork,
364 pscConnectionId: endpoint.pscConnectionId,
365 propagatedConnectionCount: endpoint.propagatedConnectionCount,
366 natIps: endpoint.natIps ?? [],
367 });
368
369 const toAccept = (
370 item: compute.ServiceAttachmentConsumerProjectLimit,
371 ): ServiceAttachmentConsumerAccept => ({
372 projectIdOrNum: item.projectIdOrNum,
373 networkUrl: item.networkUrl,
374 endpointUrl: item.endpointUrl,
375 connectionLimit: item.connectionLimit,
376 });
377
378 const toAttrs = (
379 attachment: compute.ServiceAttachment,
380 project: string,
381 ): ServiceAttachment["Attributes"] => {
382 const decoded = parseDescription(attachment.description);
383 const fromMetadata = userLabels(attachment.metadata);
384 const fromDescription = userLabels(decoded.labels);
385 return {
386 serviceAttachmentName: attachment.name ?? "",
387 project,
388 region: lastSegment(attachment.region).toLowerCase(),
389 serviceAttachmentId: attachment.id,
390 selfLink: attachment.selfLink,
391 description: decoded.user,
392 targetService: attachment.targetService,
393 producerForwardingRule: attachment.producerForwardingRule,
394 natSubnets: attachment.natSubnets ?? [],
395 connectionPreference: attachment.connectionPreference,
396 enableProxyProtocol: attachment.enableProxyProtocol === true,
397 consumerAcceptLists: (attachment.consumerAcceptLists ?? []).map(toAccept),
398 consumerRejectLists: attachment.consumerRejectLists ?? [],
399 reconcileConnections: attachment.reconcileConnections === true,
400 propagatedConnectionLimit: attachment.propagatedConnectionLimit,
401 natIpsPerEndpoint: attachment.natIpsPerEndpoint,
402 domainNames: attachment.domainNames ?? [],
403 connectedEndpoints: (attachment.connectedEndpoints ?? []).map(toConnectedEndpoint),
404 pscServiceAttachmentId: attachment.pscServiceAttachmentId
405 ? {
406 high: attachment.pscServiceAttachmentId.high,
407 low: attachment.pscServiceAttachmentId.low,
408 }
409 : undefined,
410 labels: Object.keys(fromMetadata).length > 0 ? fromMetadata : fromDescription,
411 creationTimestamp: attachment.creationTimestamp,
412 kind: attachment.kind,
413 };
414 };
415
416 const getByName = (project: string, region: string, serviceAttachment: string) =>
417 compute
418 .getServiceAttachments({ project, region, serviceAttachment })
419 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
420
421 const requireAttachment = (project: string, region: string, serviceAttachmentName: string) =>
422 getByName(project, region, serviceAttachmentName).pipe(
423 Effect.flatMap((attachment) =>
424 attachment
425 ? Effect.succeed(attachment)
426 : Effect.fail(
427 new ServiceAttachmentNotResolved({
428 serviceAttachmentName,
429 region,
430 }),
431 ),
432 ),
433 Effect.retry({
434 while: (e) => e._tag === "GCP.Compute.ServiceAttachmentNotResolved",
435 schedule: Schedule.spaced("1 second"),
436 times: 8,
437 }),
438 );
439
440 const waitUntilGone = (project: string, region: string, serviceAttachmentName: string) =>
441 getByName(project, region, serviceAttachmentName).pipe(
442 Effect.flatMap((attachment) =>
443 attachment === undefined
444 ? Effect.void
445 : Effect.fail(
446 new ServiceAttachmentPending({
447 serviceAttachmentName,
448 status: "EXISTS",
449 }),
450 ),
451 ),
452 Effect.retry({
453 while: (e) => e._tag === "GCP.Compute.ServiceAttachmentPending",
454 times: 10,
455 schedule: Schedule.spaced("2 seconds"),
456 }),
457 );
458
459 const runOp = <E, R>(
460 project: string,
461 region: string,
462 serviceAttachmentName: string,
463 operation: Effect.Effect<compute.Operation, E, R>,
464 ) => operation.pipe(Effect.flatMap((op) => waitRegionOperation(project, region, op)));
465
466 export const ServiceAttachmentProvider = () =>
467 Provider.succeed(ServiceAttachment, {
468 stables: [
469 "serviceAttachmentName",
470 "project",
471 "region",
472 "serviceAttachmentId",
473 "selfLink",
474 "creationTimestamp",
475 ],
476
477 diff: Effect.fn(function* ({ news, olds, output }) {
478 if (!isResolved(news)) return undefined;
479 const env = yield* GcpEnvironment.current;
480 const previousName = olds.serviceAttachmentName ?? output?.serviceAttachmentName;
481 const nextName = news.serviceAttachmentName ?? previousName;
482 const nameChanged =
483 previousName !== undefined && nextName !== undefined && nextName !== previousName;
484
485 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
486 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
487 const regionChanged = previousRegion !== nextRegion;
488
489 const previousDomains = domainNamesKey(olds.domainNames ?? output?.domainNames);
490 const nextDomains = domainNamesKey(
491 news.domainNames ?? olds.domainNames ?? output?.domainNames,
492 );
493 const domainChanged = news.domainNames !== undefined && previousDomains !== nextDomains;
494
495 if (nameChanged || regionChanged) {
496 return { action: "replace" as const, deleteFirst: false };
497 }
498 if (domainChanged) {
499 return {
500 action: "replace" as const,
501 deleteFirst:
502 previousName !== undefined &&
503 (news.serviceAttachmentName === undefined ||
504 news.serviceAttachmentName === previousName),
505 };
506 }
507 return undefined;
508 }),
509
510 read: Effect.fn(function* ({ id, olds, output }) {
511 const env = yield* GcpEnvironment.current;
512 const serviceAttachmentName = yield* toName(
513 id,
514 olds?.serviceAttachmentName,
515 output?.serviceAttachmentName,
516 );
517 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
518 const existing = yield* getByName(env.project, region, serviceAttachmentName);
519 if (existing === undefined) return undefined;
520 const attrs = toAttrs(existing, env.project);
521 const decoded = parseDescription(existing.description);
522 const owned =
523 (yield* hasAlchemyLabels(id, decoded.labels)) ||
524 (yield* hasAlchemyLabels(id, tagRecord(existing.metadata)));
525 return owned ? attrs : Unowned(attrs);
526 }),
527
528 list: () =>
529 Effect.gen(function* () {
530 const env = yield* GcpEnvironment.current;
531 const pages = yield* compute.aggregatedListServiceAttachments
532 .pages({
533 project: env.project,
534 returnPartialSuccess: true,
535 maxResults: 500,
536 })
537 .pipe(Stream.runCollect);
538 return Array.from(pages).flatMap((page) =>
539 Object.values(page.items ?? {}).flatMap((scoped) =>
540 (scoped?.serviceAttachments ?? [])
541 .filter(
542 (item) =>
543 hasOwnershipMarker(item.description) ||
544 Object.keys(item.metadata ?? {}).some((key) => key.startsWith("alchemy-")),
545 )
546 .map((item) => toAttrs(item, env.project)),
547 ),
548 );
549 }),
550
551 reconcile: Effect.fn(function* ({ id, news, output }) {
552 const env = yield* GcpEnvironment.current;
553 const serviceAttachmentName = yield* toName(
554 id,
555 news.serviceAttachmentName,
556 output?.serviceAttachmentName,
557 );
558 const region = normalizeRegion(news.region ?? output?.region, env.region);
559 const desiredLabels = {
560 ...toLabels(news.labels),
561 ...(yield* createInternalLabels(id)),
562 };
563 const desiredDescription = encodeDescription(news.description, desiredLabels);
564 const targetService = toForwardingRuleUrl(env.project, region, news.targetService);
565 const natSubnets = news.natSubnets.map((subnet) =>
566 toSubnetworkUrl(env.project, region, subnet),
567 );
568 const connectionPreference = connectionPreferenceOf(news.connectionPreference);
569 const enableProxyProtocol = news.enableProxyProtocol === true;
570
571 let current = yield* getByName(env.project, region, serviceAttachmentName);
572
573 if (current === undefined) {
574 const created = yield* compute
575 .insertServiceAttachments({
576 project: env.project,
577 region,
578 body: {
579 name: serviceAttachmentName,
580 description: desiredDescription,
581 targetService,
582 natSubnets,
583 connectionPreference,
584 enableProxyProtocol,
585 consumerAcceptLists: news.consumerAcceptLists,
586 consumerRejectLists: news.consumerRejectLists,
587 reconcileConnections: news.reconcileConnections,
588 propagatedConnectionLimit: news.propagatedConnectionLimit,
589 natIpsPerEndpoint: news.natIpsPerEndpoint,
590 domainNames: news.domainNames,
591 metadata: desiredLabels,
592 },
593 })
594 .pipe(
595 Effect.flatMap((operation) =>
596 waitRegionOperation(env.project, region, operation, {
597 ignore: ["RESOURCE_ALREADY_EXISTS"],
598 }).pipe(
599 Effect.flatMap(() => requireAttachment(env.project, region, serviceAttachmentName)),
600 ),
601 ),
602 Effect.catchTag("Conflict", () =>
603 requireAttachment(env.project, region, serviceAttachmentName),
604 ),
605 );
606 current = created ?? undefined;
607 }
608
609 if (current === undefined) {
610 return yield* new ServiceAttachmentNotResolved({
611 serviceAttachmentName,
612 region,
613 });
614 }
615
616 const observedPreference = connectionPreferenceOf(current.connectionPreference);
617 const observedTarget = resourceRefOf(current.targetService ?? current.producerForwardingRule);
618 const observedNat = refsKey(current.natSubnets);
619 const observedAccept = acceptListsKey((current.consumerAcceptLists ?? []).map(toAccept));
620 const observedReject = refsKey(current.consumerRejectLists);
621 const decoded = parseDescription(current.description);
622 const observedMetadata = tagRecord(current.metadata);
623 const labelsChanged =
624 JSON.stringify(observedMetadata) !== JSON.stringify(desiredLabels) ||
625 decoded.user !== (news.description ?? undefined) ||
626 JSON.stringify(userLabels(decoded.labels)) !== JSON.stringify(userLabels(desiredLabels));
627
628 const needsPatch =
629 labelsChanged ||
630 observedPreference !== connectionPreference ||
631 observedTarget !== resourceRefOf(targetService) ||
632 observedNat !== refsKey(natSubnets) ||
633 (current.enableProxyProtocol === true) !== enableProxyProtocol ||
634 (news.consumerAcceptLists !== undefined &&
635 observedAccept !== acceptListsKey(news.consumerAcceptLists)) ||
636 (news.consumerRejectLists !== undefined &&
637 observedReject !== refsKey(news.consumerRejectLists)) ||
638 (news.reconcileConnections !== undefined &&
639 (current.reconcileConnections === true) !== news.reconcileConnections) ||
640 (news.propagatedConnectionLimit !== undefined &&
641 (current.propagatedConnectionLimit ?? 250) !== news.propagatedConnectionLimit) ||
642 (news.natIpsPerEndpoint !== undefined &&
643 (current.natIpsPerEndpoint ?? 1) !== news.natIpsPerEndpoint);
644
645 if (needsPatch) {
646 const latest = (yield* getByName(env.project, region, serviceAttachmentName)) ?? current;
647 yield* runOp(
648 env.project,
649 region,
650 serviceAttachmentName,
651 compute.patchServiceAttachments({
652 project: env.project,
653 region,
654 serviceAttachment: serviceAttachmentName,
655 body: {
656 name: serviceAttachmentName,
657 fingerprint: latest.fingerprint,
658 description: desiredDescription,
659 targetService,
660 natSubnets,
661 connectionPreference,
662 enableProxyProtocol,
663 consumerAcceptLists: news.consumerAcceptLists ?? current.consumerAcceptLists,
664 consumerRejectLists: news.consumerRejectLists ?? current.consumerRejectLists,
665 reconcileConnections: news.reconcileConnections ?? current.reconcileConnections,
666 propagatedConnectionLimit:
667 news.propagatedConnectionLimit ?? current.propagatedConnectionLimit,
668 natIpsPerEndpoint: news.natIpsPerEndpoint ?? current.natIpsPerEndpoint,
669 metadata: desiredLabels,
670 },
671 }),
672 ).pipe(
673 Effect.retry({
674 while: (e) => e._tag === "Conflict",
675 times: 5,
676 schedule: Schedule.spaced("1 second"),
677 }),
678 );
679 current = (yield* getByName(env.project, region, serviceAttachmentName)) ?? current;
680 }
681
682 return toAttrs(current, env.project);
683 }),
684
685 delete: Effect.fn(function* ({ output }) {
686 const env = yield* GcpEnvironment.current;
687 const project = output.project || env.project;
688 const region = normalizeRegion(output.region, env.region);
689 yield* compute
690 .deleteServiceAttachments({
691 project,
692 region,
693 serviceAttachment: output.serviceAttachmentName,
694 })
695 .pipe(
696 Effect.flatMap((operation) =>
697 waitRegionOperation(project, region, operation, {
698 ignore: ["RESOURCE_NOT_FOUND"],
699 }),
700 ),
701 Effect.catchTag("NotFound", () => Effect.void),
702 Effect.retry({
703 while: (e) => e._tag === "Conflict",
704 times: 8,
705 schedule: Schedule.spaced("2 seconds"),
706 }),
707 );
708 yield* waitUntilGone(project, region, output.serviceAttachmentName);
709 }),
710 });