@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, 06:00 UTC

main
ts 848 lines 27.6 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as eventarc from "@distilled.cloud/gcp/eventarc_v1";
3 import { Unowned } 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 { tagRecord } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { GcpEnvironment } from "../Environment.ts";
14 import {
15 createInternalLabels,
16 diffLabels,
17 hasAlchemyLabels,
18 stripInternalLabels,
19 toLabels,
20 } from "../Labels.ts";
21 import type { Providers } from "../Providers.ts";
22 import { waitForOperation } from "./internal.ts";
23
24 const DEFAULT_CONTENT_TYPE = "application/json";
25 const MAX_NAME_LENGTH = 63;
26
27 export type EventFilter = {
28 /**
29 * CloudEvents attribute to match. Every trigger must include a filter
30 * on `type`.
31 */
32 attribute: string;
33 /**
34 * Value the attribute must equal (or match via `operator`).
35 */
36 value: string;
37 /**
38 * Optional match operator. Allowed values: `path_pattern`,
39 * `match-path-pattern`. Omitted means exact match.
40 */
41 operator?: string;
42 };
43
44 export type CloudRunDestination = {
45 /**
46 * Cloud Run service name (the `{service}` segment, not a full resource
47 * name). Must live in the same project as the trigger.
48 */
49 service: string;
50 /**
51 * Region the Cloud Run service is deployed in.
52 */
53 region: string;
54 /**
55 * Relative path on the service events are sent to, e.g. `/events`.
56 */
57 path?: string;
58 };
59
60 export type GkeDestination = {
61 /**
62 * GKE cluster name. Must be in the same project as the trigger.
63 */
64 cluster: string;
65 /**
66 * Zone (zonal clusters) or region (regional clusters) of the cluster.
67 */
68 location: string;
69 /**
70 * GKE service name.
71 */
72 service: string;
73 /**
74 * Kubernetes namespace the service runs in.
75 */
76 namespace: string;
77 /**
78 * Relative path on the GKE service events are sent to.
79 */
80 path?: string;
81 };
82
83 export type HttpEndpointDestination = {
84 /**
85 * RFC2396 URI of the HTTP endpoint (`http://` or `https://`).
86 */
87 uri: string;
88 };
89
90 export type NetworkConfig = {
91 /**
92 * Network attachment granting Eventarc access to the VPC, as
93 * `projects/{project}/regions/{region}/networkAttachments/{name}`.
94 * Required with `httpEndpoint`.
95 */
96 networkAttachment: string;
97 };
98
99 export type Destination = {
100 /**
101 * Cloud Run service that receives events.
102 */
103 cloudRun?: CloudRunDestination;
104 /**
105 * GKE service that receives events.
106 */
107 gke?: GkeDestination;
108 /**
109 * Workflow resource name
110 * (`projects/{project}/locations/{location}/workflows/{workflow}`).
111 */
112 workflow?: string;
113 /**
114 * Internal HTTP endpoint that receives events.
115 */
116 httpEndpoint?: HttpEndpointDestination;
117 /**
118 * VPC network config. Only valid with `httpEndpoint`.
119 */
120 networkConfig?: NetworkConfig;
121 };
122
123 export type PubsubTransport = {
124 /**
125 * Existing Pub/Sub topic Eventarc uses as the event source, as
126 * `projects/{project}/topics/{topic}`. Required for
127 * `google.cloud.pubsub.topic.v1.messagePublished`. Immutable —
128 * changing it replaces the trigger. Eventarc-managed topics are not
129 * deleted with the trigger.
130 */
131 topic?: string;
132 /**
133 * Output only. Pub/Sub subscription Eventarc manages for delivery.
134 */
135 subscription?: string;
136 };
137
138 export type Transport = {
139 /**
140 * Pub/Sub transport intermediary.
141 */
142 pubsub?: PubsubTransport;
143 };
144
145 export type RetryPolicy = {
146 /**
147 * Maximum delivery attempts. The only valid value is `1`. Cloud Run
148 * destinations only.
149 */
150 maxAttempts?: number;
151 };
152
153 export type TriggerProps = {
154 /**
155 * Trigger id (the `{trigger}` segment of
156 * `projects/{project}/locations/{location}/triggers/{trigger}`). If
157 * omitted, a unique name is generated from the stack, stage, and
158 * logical id. Must match `[a-z]([a-z0-9-]*[a-z0-9])?` and be 1-63
159 * characters. Immutable — changing it replaces the trigger.
160 */
161 triggerId?: string;
162 /**
163 * Eventarc location (`us-central1`, `us-east1`, …). Immutable —
164 * changing it replaces the trigger. `US-CENTRAL1` is accepted and
165 * normalized to `us-central1`.
166 * @default the stack's GCP region (`GCP.Region`, else the profile
167 * region, else `us-central1`)
168 */
169 location?: string;
170 /**
171 * CloudEvents attribute filters. Every event must match all filters.
172 * A `type` filter is required. Immutable — changing filters replaces
173 * the trigger.
174 */
175 eventFilters: EventFilter[];
176 /**
177 * Where matching events are delivered (Cloud Run, GKE, Workflows, or
178 * an HTTP endpoint).
179 */
180 destination: Destination;
181 /**
182 * Transport intermediary. For Pub/Sub events, set `pubsub.topic` to an
183 * existing topic. Immutable — changing the topic replaces the trigger.
184 */
185 transport?: Transport;
186 /**
187 * Partner channel,
188 * `projects/{project}/locations/{location}/channels/{channel}`.
189 * Required for Eventarc SaaS partner events. Immutable — changing it
190 * replaces the trigger.
191 */
192 channel?: string;
193 /**
194 * IAM service account email Eventarc uses as the trigger identity.
195 * The caller needs `iam.serviceAccounts.actAs` on this account. If
196 * omitted, Alchemy uses the project's Compute Engine default service
197 * account (`{PROJECT_NUMBER}-compute@developer.gserviceaccount.com`).
198 * Required by the Eventarc API for Workflows (and most other)
199 * destinations.
200 */
201 serviceAccount?: string;
202 /**
203 * MIME type expected in the CloudEvent `data` payload.
204 * @default "application/json"
205 */
206 eventDataContentType?: string;
207 /**
208 * Retry policy. Cloud Run destinations only; omit for the 24-hour
209 * default.
210 */
211 retryPolicy?: RetryPolicy;
212 /**
213 * User labels. Alchemy ownership labels are merged in automatically.
214 */
215 labels?: Record<string, string>;
216 };
217
218 export type Trigger = Resource<
219 "GCP.Eventarc.Trigger",
220 TriggerProps,
221 {
222 /** Full resource name `projects/{project}/locations/{location}/triggers/{trigger}`. */
223 name: string;
224 /** Trigger id (last path segment). */
225 triggerId: string;
226 /** Project id. */
227 project: string;
228 /** Location id (`us-central1`, …). */
229 location: string;
230 /** CloudEvents attribute filters. */
231 eventFilters: EventFilter[];
232 /** Destination currently configured on the trigger. */
233 destination: Destination | undefined;
234 /** Transport intermediary, including Eventarc-managed Pub/Sub resources. */
235 transport: Transport | undefined;
236 /** Partner channel, if any. */
237 channel: string | undefined;
238 /** Trigger identity service account. */
239 serviceAccount: string | undefined;
240 /** CloudEvent data MIME type. */
241 eventDataContentType: string | undefined;
242 /** Retry policy, if set. */
243 retryPolicy: RetryPolicy | undefined;
244 /** User labels (Alchemy ownership labels stripped). */
245 labels: Record<string, string>;
246 /** Server-assigned UUID4, stable until delete. */
247 uid: string | undefined;
248 /** Server checksum of the resource. */
249 etag: string | undefined;
250 /** RFC3339 creation timestamp. */
251 createTime: string | undefined;
252 /** RFC3339 last-update timestamp. */
253 updateTime: string | undefined;
254 /** Whether the trigger satisfies physical zone separation. */
255 satisfiesPzs: boolean | undefined;
256 /** Reasons the trigger is in FAILED state, if any. */
257 conditions: eventarc.StateConditionMap | undefined;
258 },
259 never,
260 Providers
261 >;
262
263 /**
264 * An Eventarc trigger that routes events matching a set of CloudEvents
265 * filters to a Cloud Run service, GKE service, Workflow, or HTTP
266 * endpoint.
267 *
268 * `triggerId`, `location`, `eventFilters`, `channel`, and
269 * `transport.pubsub.topic` are identity — changing any of them replaces
270 * the trigger. Destination, service account, content type, retry policy,
271 * and labels update in place.
272 *
273 * ### Creating a Trigger
274 * **Example:** Pub/Sub messages to a Workflow
275 * ```typescript
276 * const topic = yield* GCP.PubSub.Topic("events", {});
277 * const trigger = yield* GCP.Eventarc.Trigger("orders", {
278 * eventFilters: [
279 * {
280 * attribute: "type",
281 * value: "google.cloud.pubsub.topic.v1.messagePublished",
282 * },
283 * ],
284 * destination: {
285 * workflow:
286 * "projects/my-project/locations/us-central1/workflows/orders",
287 * },
288 * transport: { pubsub: { topic: topic.name } },
289 * });
290 * ```
291 *
292 * **Example:** Pub/Sub messages to Cloud Run
293 * ```typescript
294 * const trigger = yield* GCP.Eventarc.Trigger("orders", {
295 * triggerId: "order-events",
296 * location: "us-central1",
297 * eventFilters: [
298 * {
299 * attribute: "type",
300 * value: "google.cloud.pubsub.topic.v1.messagePublished",
301 * },
302 * ],
303 * destination: {
304 * cloudRun: { service: "order-handler", region: "us-central1" },
305 * },
306 * transport: { pubsub: { topic: topic.name } },
307 * labels: { env: "prod" },
308 * });
309 * ```
310 *
311 * ### Updating a Trigger
312 * Re-declare the same logical id with changed props; the engine keeps the
313 * physical trigger and patches it in place.
314 *
315 * **Example:** Change labels and the CloudEvent content type
316 * ```typescript
317 * const trigger = yield* GCP.Eventarc.Trigger("orders", {
318 * eventFilters: [
319 * {
320 * attribute: "type",
321 * value: "google.cloud.pubsub.topic.v1.messagePublished",
322 * },
323 * ],
324 * destination: {
325 * workflow:
326 * "projects/my-project/locations/us-central1/workflows/orders",
327 * },
328 * transport: { pubsub: { topic: topic.name } },
329 * eventDataContentType: "application/json",
330 * labels: { env: "prod", role: "events" },
331 * });
332 * ```
333 *
334 * @resource
335 * @category Eventarc
336 */
337 export const Trigger = Resource<Trigger>("GCP.Eventarc.Trigger");
338
339 export class TriggerNotHealthy extends Data.TaggedError("GCP.Eventarc.TriggerNotHealthy")<{
340 resourceName: string;
341 conditions: string;
342 }> {}
343
344 export class TriggerNotResolved extends Data.TaggedError("GCP.Eventarc.TriggerNotResolved")<{
345 resourceName: string;
346 }> {}
347
348 export class TriggerStillExists extends Data.TaggedError("GCP.Eventarc.TriggerStillExists")<{
349 resourceName: string;
350 }> {}
351
352 export class TriggerServiceAccountMissing extends Data.TaggedError(
353 "GCP.Eventarc.TriggerServiceAccountMissing",
354 )<{
355 project: string;
356 }> {}
357
358 const lastSegment = (value: string) => {
359 const trimmed = value.replace(/\/+$/, "");
360 const parts = trimmed.split("/");
361 return parts[parts.length - 1] || trimmed;
362 };
363
364 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
365 lastSegment(location ?? defaultLocation).toLowerCase();
366
367 const rfc1035 = (name: string): string => {
368 let next = name
369 .toLowerCase()
370 .replace(/[^a-z0-9-]/g, "-")
371 .replace(/-+/g, "-")
372 .replace(/^-+|-+$/g, "");
373 if (!/^[a-z]/.test(next)) next = `t${next}`;
374 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
375 return next.length > 0 ? next : "trigger";
376 };
377
378 const resourceName = (project: string, location: string, triggerId: string) =>
379 `projects/${project}/locations/${location}/triggers/${triggerId}`;
380
381 const parseName = (name: string, defaultLocation: string) => {
382 const parts = name.split("/").filter((part) => part.length > 0);
383 const triggersAt = parts.lastIndexOf("triggers");
384 const locationsAt = parts.lastIndexOf("locations");
385 const projectsAt = parts.lastIndexOf("projects");
386 return {
387 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
388 location:
389 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
390 triggerId:
391 triggersAt >= 0 && parts[triggersAt + 1] ? parts[triggersAt + 1]! : lastSegment(name),
392 };
393 };
394
395 const userLabels = (
396 labels: Record<string, string | undefined> | null | undefined,
397 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
398
399 const toId = (id: string, triggerId: string | undefined, existing?: string) =>
400 Effect.gen(function* () {
401 if (triggerId !== undefined) return rfc1035(triggerId);
402 if (existing !== undefined) return existing;
403 return rfc1035(
404 yield* createPhysicalName({
405 id,
406 maxLength: MAX_NAME_LENGTH,
407 lowercase: true,
408 }),
409 );
410 });
411
412 const compact = <T extends Record<string, unknown>>(value: T): T => {
413 const next: Record<string, unknown> = {};
414 for (const [key, entry] of Object.entries(value)) {
415 if (entry !== undefined && entry !== "") next[key] = entry;
416 }
417 return next as T;
418 };
419
420 const toEventFilters = (filters: eventarc.EventFilterList | undefined): EventFilter[] =>
421 (filters ?? [])
422 .filter(
423 (
424 filter,
425 ): filter is eventarc.EventFilter & {
426 attribute: string;
427 value: string;
428 } => typeof filter.attribute === "string" && typeof filter.value === "string",
429 )
430 .map((filter) =>
431 compact({
432 attribute: filter.attribute,
433 value: filter.value,
434 operator: filter.operator,
435 }),
436 );
437
438 const toDestination = (destination: eventarc.Destination | undefined): Destination | undefined => {
439 if (destination === undefined) return undefined;
440 const next = compact({
441 cloudRun: destination.cloudRun
442 ? compact({
443 service: destination.cloudRun.service ?? "",
444 region: destination.cloudRun.region ?? "",
445 path: destination.cloudRun.path,
446 })
447 : undefined,
448 gke: destination.gke
449 ? compact({
450 cluster: destination.gke.cluster ?? "",
451 location: destination.gke.location ?? "",
452 service: destination.gke.service ?? "",
453 namespace: destination.gke.namespace ?? "",
454 path: destination.gke.path,
455 })
456 : undefined,
457 workflow: destination.workflow,
458 httpEndpoint: destination.httpEndpoint
459 ? compact({ uri: destination.httpEndpoint.uri ?? "" })
460 : undefined,
461 networkConfig: destination.networkConfig
462 ? compact({
463 networkAttachment: destination.networkConfig.networkAttachment ?? "",
464 })
465 : undefined,
466 });
467 return Object.keys(next).length > 0 ? next : undefined;
468 };
469
470 const fromDestination = (destination: Destination): eventarc.Destination =>
471 compact({
472 cloudRun: destination.cloudRun
473 ? compact({
474 service: destination.cloudRun.service,
475 region: destination.cloudRun.region,
476 path: destination.cloudRun.path,
477 })
478 : undefined,
479 gke: destination.gke
480 ? compact({
481 cluster: destination.gke.cluster,
482 location: destination.gke.location,
483 service: destination.gke.service,
484 namespace: destination.gke.namespace,
485 path: destination.gke.path,
486 })
487 : undefined,
488 workflow: destination.workflow,
489 httpEndpoint: destination.httpEndpoint
490 ? compact({ uri: destination.httpEndpoint.uri })
491 : undefined,
492 networkConfig: destination.networkConfig
493 ? compact({
494 networkAttachment: destination.networkConfig.networkAttachment,
495 })
496 : undefined,
497 });
498
499 const toTransport = (transport: eventarc.Transport | undefined): Transport | undefined => {
500 if (transport?.pubsub === undefined) return undefined;
501 return {
502 pubsub: compact({
503 topic: transport.pubsub.topic,
504 subscription: transport.pubsub.subscription,
505 }),
506 };
507 };
508
509 const topicKey = (topic: string | undefined, project: string) => {
510 if (topic === undefined || topic.length === 0) return "";
511 if (topic.includes("/")) return topic;
512 return `projects/${project}/topics/${topic}`;
513 };
514
515 const saKey = (serviceAccount: string | undefined) => {
516 if (serviceAccount === undefined || serviceAccount.length === 0) return "";
517 return serviceAccount.includes("/") ? lastSegment(serviceAccount) : serviceAccount;
518 };
519
520 const filtersKey = (filters: EventFilter[] | undefined) =>
521 JSON.stringify(
522 [...(filters ?? [])]
523 .map((filter) => ({
524 attribute: filter.attribute,
525 value: filter.value,
526 operator: filter.operator ?? "",
527 }))
528 .sort((left, right) =>
529 left.attribute === right.attribute
530 ? left.value.localeCompare(right.value)
531 : left.attribute.localeCompare(right.attribute),
532 ),
533 );
534
535 const destinationKey = (destination: Destination | undefined) =>
536 JSON.stringify(toDestination(fromDestination(destination ?? {})) ?? {});
537
538 const contentTypeKey = (value: string | undefined) =>
539 (value === undefined || value.length === 0 ? DEFAULT_CONTENT_TYPE : value).toLowerCase();
540
541 const retryKey = (policy: RetryPolicy | undefined) =>
542 JSON.stringify({ maxAttempts: policy?.maxAttempts ?? null });
543
544 const toAttrs = (trigger: eventarc.Trigger, project: string, region: string) => {
545 const name = trigger.name ?? "";
546 const parsed = parseName(name, region);
547 return {
548 name,
549 triggerId: parsed.triggerId,
550 project: parsed.project || project,
551 location: parsed.location,
552 eventFilters: toEventFilters(trigger.eventFilters),
553 destination: toDestination(trigger.destination),
554 transport: toTransport(trigger.transport),
555 channel: trigger.channel,
556 serviceAccount: trigger.serviceAccount,
557 eventDataContentType: trigger.eventDataContentType ?? DEFAULT_CONTENT_TYPE,
558 retryPolicy: trigger.retryPolicy
559 ? compact({ maxAttempts: trigger.retryPolicy.maxAttempts })
560 : undefined,
561 labels: userLabels(trigger.labels),
562 uid: trigger.uid,
563 etag: trigger.etag,
564 createTime: trigger.createTime,
565 updateTime: trigger.updateTime,
566 satisfiesPzs: trigger.satisfiesPzs,
567 conditions: trigger.conditions,
568 };
569 };
570
571 const getByName = (name: string) =>
572 eventarc
573 .getProjectsLocationsTriggers({ name })
574 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
575
576 /**
577 * Block until Eventarc reports every trigger condition healthy (`OK`), so
578 * nothing downstream assumes a trigger that is still provisioning its
579 * transport. A trigger whose conditions settle on an error fails.
580 */
581 const waitUntilHealthy = (name: string) =>
582 waitUntilExists(name).pipe(
583 Effect.flatMap((trigger) => {
584 const failing = Object.entries(trigger.conditions ?? {}).filter(
585 ([, condition]) => condition?.code !== undefined && condition.code !== "OK",
586 );
587 return failing.length === 0
588 ? Effect.succeed(trigger)
589 : Effect.fail(
590 new TriggerNotHealthy({
591 resourceName: name,
592 conditions: failing
593 .map(([key, condition]) => `${key}: ${condition?.code} ${condition?.message ?? ""}`)
594 .join("; "),
595 }),
596 );
597 }),
598 Effect.retry({
599 while: (error) => error._tag === "GCP.Eventarc.TriggerNotHealthy",
600 times: 30,
601 schedule: Schedule.spaced("5 seconds"),
602 }),
603 );
604
605 const waitUntilExists = (name: string) =>
606 getByName(name).pipe(
607 Effect.flatMap((trigger) =>
608 trigger
609 ? Effect.succeed(trigger)
610 : Effect.fail(new TriggerNotResolved({ resourceName: name })),
611 ),
612 Effect.retry({
613 while: (error) => error._tag === "GCP.Eventarc.TriggerNotResolved",
614 times: 8,
615 schedule: Schedule.spaced("1 second"),
616 }),
617 );
618
619 const waitUntilGone = (name: string) =>
620 getByName(name).pipe(
621 Effect.flatMap((trigger) =>
622 trigger === undefined
623 ? Effect.void
624 : Effect.fail(new TriggerStillExists({ resourceName: name })),
625 ),
626 Effect.retry({
627 while: (error) => error._tag === "GCP.Eventarc.TriggerStillExists",
628 times: 10,
629 schedule: Schedule.spaced("2 seconds"),
630 }),
631 );
632
633 const desiredTransport = (news: TriggerProps): eventarc.Transport | undefined => {
634 const topic = news.transport?.pubsub?.topic;
635 if (topic === undefined || topic.length === 0) return undefined;
636 return { pubsub: { topic } };
637 };
638
639 const defaultServiceAccount = (project: string) =>
640 resourcemanager.getProjects({ name: `projects/${project}` }).pipe(
641 Effect.flatMap((resource) => {
642 const projectNumber = lastSegment(resource.name ?? "");
643 if (!/^\d+$/.test(projectNumber)) {
644 return Effect.fail(new TriggerServiceAccountMissing({ project }));
645 }
646 return Effect.succeed(`${projectNumber}-compute@developer.gserviceaccount.com`);
647 }),
648 );
649
650 const resolveServiceAccount = (
651 project: string,
652 news: TriggerProps,
653 current: eventarc.Trigger | undefined,
654 ) =>
655 Effect.gen(function* () {
656 if (news.serviceAccount !== undefined && news.serviceAccount.length > 0) {
657 return news.serviceAccount;
658 }
659 if (current?.serviceAccount !== undefined && current.serviceAccount.length > 0) {
660 return current.serviceAccount;
661 }
662 return yield* defaultServiceAccount(project);
663 });
664
665 export const TriggerProvider = () =>
666 Provider.succeed(Trigger, {
667 stables: ["name", "triggerId", "project", "location", "uid", "createTime", "channel"],
668
669 diff: Effect.fn(function* ({ news, olds, output }) {
670 if (!isResolved(news)) return undefined;
671 const env = yield* GcpEnvironment.current;
672
673 const previousId = olds?.triggerId ?? output?.triggerId;
674 const nextId = news.triggerId ? rfc1035(news.triggerId) : previousId;
675 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
676 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
677 const project = output?.project ?? "";
678 const previousChannel = olds?.channel ?? output?.channel ?? "";
679 const nextChannel = news.channel ?? previousChannel;
680 const previousTopic = topicKey(
681 olds?.transport?.pubsub?.topic ?? output?.transport?.pubsub?.topic,
682 project,
683 );
684 const nextTopic =
685 news.transport?.pubsub?.topic !== undefined
686 ? topicKey(news.transport.pubsub.topic, project)
687 : previousTopic;
688 const previousFilters = filtersKey(olds?.eventFilters ?? output?.eventFilters);
689 const nextFilters = filtersKey(news.eventFilters);
690
691 const replace =
692 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
693 previousLocation !== nextLocation ||
694 previousChannel !== nextChannel ||
695 (nextTopic.length > 0 && previousTopic.length > 0 && nextTopic !== previousTopic) ||
696 previousFilters !== nextFilters;
697
698 if (!replace) return undefined;
699 return {
700 action: "replace" as const,
701 deleteFirst:
702 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
703 };
704 }),
705
706 read: Effect.fn(function* ({ id, olds, output }) {
707 const env = yield* GcpEnvironment.current;
708 const triggerId = yield* toId(id, olds?.triggerId, output?.triggerId);
709 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
710 const name = output?.name ?? resourceName(env.project, location, triggerId);
711 const existing = yield* getByName(name);
712 if (existing === undefined) return undefined;
713 const attrs = toAttrs(existing, env.project, env.region);
714 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
715 }),
716
717 list: () =>
718 Effect.gen(function* () {
719 const env = yield* GcpEnvironment.current;
720 return yield* eventarc.listProjectsLocationsTriggers
721 .pages({
722 parent: `projects/${env.project}/locations/-`,
723 pageSize: 1000,
724 })
725 .pipe(
726 Stream.flatMap((page) => Stream.fromIterable(page.triggers ?? [])),
727 Stream.filter((trigger) =>
728 Object.keys(trigger.labels ?? {}).some((key) => key.startsWith("alchemy-")),
729 ),
730 Stream.map((trigger) => toAttrs(trigger, env.project, env.region)),
731 Stream.runCollect,
732 Effect.map((chunk) => Array.from(chunk)),
733 );
734 }),
735
736 reconcile: Effect.fn(function* ({ id, news, output }) {
737 const env = yield* GcpEnvironment.current;
738 const triggerId = yield* toId(id, news.triggerId, output?.triggerId);
739 const location = normalizeLocation(news.location ?? output?.location, env.region);
740 const name = resourceName(env.project, location, triggerId);
741 const desiredLabels = {
742 ...toLabels(news.labels),
743 ...(yield* createInternalLabels(id)),
744 };
745 const eventFilters = news.eventFilters.map((filter) =>
746 compact({
747 attribute: filter.attribute,
748 value: filter.value,
749 operator: filter.operator,
750 }),
751 );
752 const destination = fromDestination(news.destination);
753 const transport = desiredTransport(news);
754
755 let current = yield* getByName(name);
756 const serviceAccount = yield* resolveServiceAccount(env.project, news, current);
757
758 if (current === undefined) {
759 const created = yield* eventarc
760 .createProjectsLocationsTriggers({
761 parent: `projects/${env.project}/locations/${location}`,
762 triggerId,
763 body: {
764 name,
765 labels: desiredLabels,
766 eventFilters,
767 destination,
768 transport,
769 channel: news.channel,
770 serviceAccount,
771 eventDataContentType: news.eventDataContentType,
772 retryPolicy: news.retryPolicy,
773 },
774 })
775 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
776 if (created !== undefined) {
777 yield* waitForOperation(created);
778 }
779 current = yield* waitUntilExists(name);
780 }
781
782 if (current === undefined) {
783 return yield* new TriggerNotResolved({ resourceName: name });
784 }
785
786 const observedLabels = tagRecord(current.labels);
787 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
788 const labelsChanged = upsert.length > 0 || removed.length > 0;
789 const destinationChanged =
790 destinationKey(toDestination(current.destination)) !== destinationKey(news.destination);
791 const serviceAccountChanged = saKey(serviceAccount) !== saKey(current.serviceAccount);
792 const contentTypeChanged =
793 news.eventDataContentType !== undefined &&
794 contentTypeKey(current.eventDataContentType) !== contentTypeKey(news.eventDataContentType);
795 const retryChanged =
796 news.retryPolicy !== undefined &&
797 retryKey(current.retryPolicy) !== retryKey(news.retryPolicy);
798
799 if (
800 labelsChanged ||
801 destinationChanged ||
802 serviceAccountChanged ||
803 contentTypeChanged ||
804 retryChanged
805 ) {
806 const updateMask = [
807 labelsChanged ? "labels" : undefined,
808 destinationChanged ? "destination" : undefined,
809 serviceAccountChanged ? "serviceAccount" : undefined,
810 contentTypeChanged ? "eventDataContentType" : undefined,
811 retryChanged ? "retryPolicy" : undefined,
812 ].filter((field): field is string => field !== undefined);
813
814 const patched = yield* eventarc.patchProjectsLocationsTriggers({
815 name,
816 updateMask: updateMask.join(","),
817 body: {
818 name,
819 labels: desiredLabels,
820 destination,
821 serviceAccount,
822 eventDataContentType: news.eventDataContentType,
823 retryPolicy: news.retryPolicy,
824 },
825 });
826 yield* waitForOperation(patched);
827 current = yield* waitUntilExists(name);
828 }
829
830 current = yield* waitUntilHealthy(name);
831 return toAttrs(current, env.project, env.region);
832 }),
833
834 delete: Effect.fn(function* ({ output }) {
835 const existing = yield* getByName(output.name);
836 if (existing === undefined) return;
837 const operation = yield* eventarc
838 .deleteProjectsLocationsTriggers({
839 name: output.name,
840 allowMissing: true,
841 })
842 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
843 if (operation !== undefined) {
844 yield* waitForOperation(operation, { notFoundOk: true });
845 }
846 yield* waitUntilGone(output.name);
847 }),
848 });