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

main
ts 417 lines 14.5 KB
Raw
1 import * as eventarc from "@distilled.cloud/gcp/eventarc_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 type LoggingConfig,
14 changedFields,
15 compact,
16 cryptoKeyKey,
17 collectPages,
18 expandResource,
19 hasAlchemyLabelKeys,
20 loggingKey,
21 normalizeLocation,
22 parentOf,
23 parseName,
24 resourceName,
25 rfc1035,
26 sameJson,
27 textKey,
28 toLoggingConfig,
29 toPhysicalId,
30 userAnnotations,
31 userLabels,
32 retryOnTransient,
33 waitForOperation,
34 waitUntilGone,
35 waitUntilPresent,
36 } from "./internal.ts";
37
38 const COLLECTION = "googleApiSources";
39
40 export type ProjectSubscriptions = {
41 /**
42 * Projects to receive events from, as `projects/{id}` or
43 * `projects/{number}`. All projects must share an organization. At
44 * most 100.
45 */
46 list?: string[];
47 };
48
49 export type OrganizationSubscription = {
50 /**
51 * When true, subscribe to events from every project in the source's
52 * organization.
53 */
54 enabled?: boolean;
55 };
56
57 export type GoogleApiSourceProps = {
58 /**
59 * Google API source id (the `{googleApiSource}` segment of
60 * `projects/{project}/locations/{location}/googleApiSources/{googleApiSource}`).
61 * If omitted, a unique name is generated. Must match
62 * `[a-z]([a-z0-9-]*[a-z0-9])?` and be 1-63 characters. Immutable —
63 * changing it replaces the source.
64 */
65 googleApiSourceId?: string;
66 /**
67 * Eventarc Advanced location (`us-central1`, `us-east4`, …). Immutable
68 * — changing it replaces the source. `US-CENTRAL1` is accepted and
69 * normalized to `us-central1`. One source is allowed per project per
70 * region.
71 * @default the stack's GCP region (`GCP.Region`, else the profile
72 * region, else `us-central1`)
73 */
74 location?: string;
75 /**
76 * MessageBus that receives Google API events, as
77 * `projects/{project}/locations/{location}/messageBuses/{messageBus}`
78 * or the `{messageBus}` segment.
79 */
80 destination: string;
81 /**
82 * Human-readable display name.
83 */
84 displayName?: string;
85 /**
86 * Customer-managed Cloud KMS key used to encrypt/decrypt event data,
87 * as
88 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`.
89 */
90 cryptoKeyName?: string;
91 /**
92 * Platform logging configuration.
93 */
94 loggingConfig?: LoggingConfig;
95 /**
96 * Subscribe to events from every project in the organization.
97 */
98 organizationSubscription?: OrganizationSubscription;
99 /**
100 * Subscribe to events from an explicit list of projects in the same
101 * organization.
102 */
103 projectSubscriptions?: ProjectSubscriptions;
104 /**
105 * User labels. Alchemy ownership labels are merged in automatically.
106 */
107 labels?: Record<string, string>;
108 /**
109 * Free-form annotations.
110 */
111 annotations?: Record<string, string>;
112 };
113
114 export type GoogleApiSource = Resource<
115 "GCP.Eventarc.GoogleApiSource",
116 GoogleApiSourceProps,
117 {
118 /** Full resource name `projects/{project}/locations/{location}/googleApiSources/{googleApiSource}`. */
119 name: string;
120 /** Google API source id (last path segment). */
121 googleApiSourceId: string;
122 /** Project id. */
123 project: string;
124 /** Location id (`us-central1`, …). */
125 location: string;
126 /** Destination MessageBus resource name. */
127 destination: string | undefined;
128 /** Display name. */
129 displayName: string | undefined;
130 /** Customer-managed KMS key, if any. */
131 cryptoKeyName: string | undefined;
132 /** Platform logging configuration. */
133 loggingConfig: LoggingConfig | undefined;
134 /** Organization-wide subscription config. */
135 organizationSubscription: OrganizationSubscription | undefined;
136 /** Explicit project subscription list. */
137 projectSubscriptions: ProjectSubscriptions | undefined;
138 /** User labels (Alchemy ownership labels stripped). */
139 labels: Record<string, string>;
140 /** User annotations. */
141 annotations: Record<string, string>;
142 /** Server-assigned UUID4, stable until delete. */
143 uid: string | undefined;
144 /** Server checksum of the resource. */
145 etag: string | undefined;
146 /** RFC3339 creation timestamp. */
147 createTime: string | undefined;
148 /** RFC3339 last-update timestamp. */
149 updateTime: string | undefined;
150 },
151 never,
152 Providers
153 >;
154
155 /**
156 * An Eventarc Advanced GoogleApiSource that delivers first-party Google
157 * API events onto a MessageBus. One source is allowed per project per
158 * region.
159 *
160 * `googleApiSourceId` and `location` are identity — changing either
161 * replaces the source. Destination, display name, labels, annotations,
162 * logging, CMEK, and subscription config update in place.
163 *
164 * ### Creating a GoogleApiSource
165 * **Example:** Collect Google events onto a bus
166 * ```typescript
167 * const bus = yield* GCP.Eventarc.MessageBus("Events", {
168 * location: "us-central1",
169 * });
170 * const source = yield* GCP.Eventarc.GoogleApiSource("GoogleEvents", {
171 * location: "us-central1",
172 * destination: bus.name,
173 * labels: { env: "prod" },
174 * });
175 * ```
176 *
177 * ### Updating a GoogleApiSource
178 * Re-declare the same logical id with changed props; the engine keeps the
179 * physical source and patches it in place.
180 *
181 * **Example:** Change labels and display name
182 * ```typescript
183 * const source = yield* GCP.Eventarc.GoogleApiSource("GoogleEvents", {
184 * location: "us-central1",
185 * destination: bus.name,
186 * displayName: "google events v2",
187 * labels: { env: "prod", role: "source" },
188 * });
189 * ```
190 *
191 * @resource
192 * @category Eventarc
193 */
194 export const GoogleApiSource = Resource<GoogleApiSource>("GCP.Eventarc.GoogleApiSource");
195
196 const toProjectSubscriptions = (
197 value: ProjectSubscriptions | eventarc.ProjectSubscriptions | undefined,
198 ): ProjectSubscriptions | undefined => {
199 const list = [...(value?.list ?? [])].filter((item) => item.length > 0);
200 if (list.length === 0) return undefined;
201 return { list };
202 };
203
204 const toOrganizationSubscription = (
205 value: OrganizationSubscription | eventarc.OrganizationSubscription | undefined,
206 ): OrganizationSubscription | undefined => {
207 if (value === undefined || value.enabled === undefined) return undefined;
208 return { enabled: value.enabled };
209 };
210
211 const toAttrs = (source: eventarc.GoogleApiSource, project: string, region: string) => {
212 const name = source.name ?? "";
213 const parsed = parseName(name, COLLECTION, region);
214 return {
215 name,
216 googleApiSourceId: parsed.id,
217 project: parsed.project || project,
218 location: parsed.location,
219 destination: source.destination,
220 displayName: source.displayName,
221 cryptoKeyName: source.cryptoKeyName,
222 loggingConfig: toLoggingConfig(source.loggingConfig),
223 organizationSubscription: toOrganizationSubscription(source.organizationSubscription),
224 projectSubscriptions: toProjectSubscriptions(source.projectSubscriptions),
225 labels: userLabels(source.labels),
226 annotations: userAnnotations(source.annotations),
227 uid: source.uid,
228 etag: source.etag,
229 createTime: source.createTime,
230 updateTime: source.updateTime,
231 };
232 };
233
234 const getByName = (name: string) =>
235 eventarc
236 .getProjectsLocationsGoogleApiSources({ name })
237 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
238
239 export const GoogleApiSourceProvider = () =>
240 Provider.succeed(GoogleApiSource, {
241 stables: ["name", "googleApiSourceId", "project", "location", "uid", "createTime"],
242
243 diff: Effect.fn(function* ({ news, olds, output }) {
244 if (!isResolved(news)) return undefined;
245 const env = yield* GcpEnvironment.current;
246 const previousId = olds?.googleApiSourceId ?? output?.googleApiSourceId;
247 const nextId = news.googleApiSourceId
248 ? rfc1035(news.googleApiSourceId, "google-api-source")
249 : previousId;
250 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
251 const nextLocation = normalizeLocation(
252 news.location ?? olds?.location ?? output?.location,
253 env.region,
254 );
255 if (
256 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
257 previousLocation !== nextLocation
258 ) {
259 return { action: "replace" as const };
260 }
261 return undefined;
262 }),
263
264 read: Effect.fn(function* ({ id, olds, output }) {
265 const env = yield* GcpEnvironment.current;
266 const googleApiSourceId = yield* toPhysicalId(
267 id,
268 olds?.googleApiSourceId,
269 output?.googleApiSourceId,
270 "google-api-source",
271 );
272 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
273 const name =
274 output?.name ?? resourceName(env.project, location, COLLECTION, googleApiSourceId);
275 const existing = yield* getByName(name);
276 if (existing === undefined) return undefined;
277 const attrs = toAttrs(existing, env.project, env.region);
278 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
279 }),
280
281 list: () =>
282 Effect.gen(function* () {
283 const env = yield* GcpEnvironment.current;
284 const items = yield* collectPages(
285 eventarc.listProjectsLocationsGoogleApiSources.pages({
286 parent: parentOf(env.project, "-"),
287 pageSize: 1000,
288 }),
289 (page) => page.googleApiSources,
290 );
291 return items
292 .filter((item) => hasAlchemyLabelKeys(item.labels))
293 .map((item) => toAttrs(item, env.project, env.region));
294 }),
295
296 reconcile: Effect.fn(function* ({ id, news, output }) {
297 const env = yield* GcpEnvironment.current;
298 const googleApiSourceId = yield* toPhysicalId(
299 id,
300 news.googleApiSourceId,
301 output?.googleApiSourceId,
302 "google-api-source",
303 );
304 const location = normalizeLocation(news.location ?? output?.location, env.region);
305 const name = resourceName(env.project, location, COLLECTION, googleApiSourceId);
306 const desiredLabels = {
307 ...toLabels(news.labels),
308 ...(yield* createInternalLabels(id)),
309 };
310 const destination = expandResource(news.destination, env.project, location, "messageBuses");
311 const desiredLogging = toLoggingConfig(news.loggingConfig);
312 const desiredCrypto =
313 news.cryptoKeyName && news.cryptoKeyName.length > 0 ? news.cryptoKeyName : undefined;
314 const desiredAnnotations = news.annotations ? tagRecord(news.annotations) : undefined;
315 const desiredOrg = toOrganizationSubscription(news.organizationSubscription);
316 const desiredProjects = toProjectSubscriptions(news.projectSubscriptions);
317
318 let current = yield* getByName(name);
319
320 if (current === undefined) {
321 const created = yield* eventarc
322 .createProjectsLocationsGoogleApiSources({
323 parent: parentOf(env.project, location),
324 googleApiSourceId,
325 body: compact({
326 name,
327 destination,
328 displayName: news.displayName,
329 cryptoKeyName: desiredCrypto,
330 loggingConfig: desiredLogging,
331 organizationSubscription: desiredOrg,
332 projectSubscriptions: desiredProjects,
333 labels: desiredLabels,
334 annotations: desiredAnnotations,
335 }),
336 })
337 .pipe(
338 Effect.retry({
339 while: (error) => error._tag === "Conflict",
340 times: 5,
341 schedule: Schedule.spaced("2 seconds"),
342 }),
343 Effect.catchTag("Conflict", () => Effect.undefined),
344 );
345 if (created !== undefined) {
346 yield* waitForOperation(created);
347 }
348 current = yield* waitUntilPresent(getByName(name), name);
349 }
350
351 const observedLabels = tagRecord(current.labels);
352 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
353 const updateMask = changedFields([
354 ["labels", upsert.length > 0 || removed.length > 0],
355 ["destination", textKey(current.destination) !== destination],
356 ["displayName", textKey(current.displayName) !== textKey(news.displayName)],
357 ["cryptoKeyName", cryptoKeyKey(current.cryptoKeyName) !== cryptoKeyKey(desiredCrypto)],
358 ["loggingConfig", loggingKey(current.loggingConfig) !== loggingKey(desiredLogging)],
359 [
360 "organizationSubscription",
361 !sameJson(toOrganizationSubscription(current.organizationSubscription), desiredOrg),
362 ],
363 [
364 "projectSubscriptions",
365 !sameJson(toProjectSubscriptions(current.projectSubscriptions), desiredProjects),
366 ],
367 ["annotations", !sameJson(tagRecord(current.annotations), desiredAnnotations ?? {})],
368 ]);
369
370 if (updateMask.length > 0) {
371 const patched = yield* eventarc.patchProjectsLocationsGoogleApiSources({
372 name: current.name ?? name,
373 updateMask: updateMask.join(","),
374 body: {
375 name: current.name ?? name,
376 destination,
377 displayName: news.displayName,
378 cryptoKeyName: desiredCrypto,
379 loggingConfig: desiredLogging,
380 organizationSubscription: desiredOrg,
381 projectSubscriptions: desiredProjects,
382 labels: desiredLabels,
383 annotations: desiredAnnotations ?? {},
384 },
385 });
386 yield* waitForOperation(patched);
387 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
388 }
389
390 return toAttrs(current, env.project, env.region);
391 }),
392
393 delete: Effect.fn(function* ({ output }) {
394 yield* retryOnTransient(
395 Effect.gen(function* () {
396 const existing = yield* getByName(output.name);
397 if (existing === undefined) return;
398 const operation = yield* eventarc
399 .deleteProjectsLocationsGoogleApiSources({
400 name: output.name,
401 allowMissing: true,
402 })
403 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
404 if (operation !== undefined) {
405 yield* waitForOperation(operation, { notFoundOk: true });
406 }
407 }),
408 ).pipe(
409 Effect.catchTag("GCP.OperationFailed", (error) =>
410 getByName(output.name).pipe(
411 Effect.flatMap((current) => (current === undefined ? Effect.void : Effect.fail(error))),
412 ),
413 ),
414 );
415 yield* waitUntilGone(getByName(output.name), output.name);
416 }),
417 });