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

main
ts 437 lines 15.2 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 { 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 { waitForOperation } from "./internal.ts";
22
23 const MAX_NAME_LENGTH = 63;
24
25 export type ChannelState = eventarc.ChannelStateEnum | (string & {});
26
27 export type ChannelProps = {
28 /**
29 * Channel id (the `{channel}` segment of
30 * `projects/{project}/locations/{location}/channels/{channel}`). If
31 * omitted, a unique name is generated from the stack, stage, and
32 * logical id. Must match `[a-z]([a-z0-9-]*[a-z0-9])?` and be 1-63
33 * characters. Immutable — changing it replaces the channel.
34 */
35 channelId?: string;
36 /**
37 * Eventarc location (`us-central1`, `us-east1`, …). Immutable —
38 * changing it replaces the channel. `US-CENTRAL1` is accepted and
39 * normalized to `us-central1`.
40 * @default the stack's GCP region (`GCP.Region`, else the profile
41 * region, else `us-central1`)
42 */
43 location?: string;
44 /**
45 * Event provider associated with the channel (an Eventarc SaaS
46 * partner). Format
47 * `projects/{project}/locations/{location}/providers/{providerId}` or
48 * the `{providerId}` segment. The provider is granted permission to
49 * publish events on the channel. Omit for a Google channel with no
50 * third-party partner. Immutable — changing it replaces the channel.
51 */
52 provider?: string;
53 /**
54 * Customer-managed Cloud KMS key used to encrypt/decrypt event data,
55 * as
56 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`.
57 */
58 cryptoKeyName?: string;
59 /**
60 * User labels. Alchemy ownership labels are merged in automatically.
61 */
62 labels?: Record<string, string>;
63 };
64
65 export type Channel = Resource<
66 "GCP.Eventarc.Channel",
67 ChannelProps,
68 {
69 /** Full resource name `projects/{project}/locations/{location}/channels/{channel}`. */
70 name: string;
71 /** Channel id (last path segment). */
72 channelId: string;
73 /** Project id. */
74 project: string;
75 /** Location id (`us-central1`, …). */
76 location: string;
77 /** Event provider resource name, if any. */
78 provider: string | undefined;
79 /** Customer-managed KMS key, if any. */
80 cryptoKeyName: string | undefined;
81 /** User labels (Alchemy ownership labels stripped). */
82 labels: Record<string, string>;
83 /**
84 * Pub/Sub topic Eventarc manages as the channel transport
85 * (`projects/{project}/topics/{topic}`).
86 */
87 pubsubTopic: string | undefined;
88 /** Channel lifecycle state (`PENDING`, `ACTIVE`, `INACTIVE`, …). */
89 state: ChannelState | undefined;
90 /**
91 * Activation token the provider uses to register the channel. Present
92 * while the channel is `PENDING`.
93 */
94 activationToken: string | undefined;
95 /** Server-assigned UUID4, stable until delete. */
96 uid: string | undefined;
97 /** RFC3339 creation timestamp. */
98 createTime: string | undefined;
99 /** RFC3339 last-update timestamp. */
100 updateTime: string | undefined;
101 /** Whether the channel satisfies physical zone separation. */
102 satisfiesPzs: boolean | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * An Eventarc channel representing a subscriber's intent to receive
110 * events from an event provider. Published events are delivered over
111 * the transport Eventarc associates with the channel.
112 *
113 * `channelId`, `location`, and `provider` are identity — changing any
114 * of them replaces the channel. Labels and `cryptoKeyName` update in
115 * place. A Google channel (no third-party `provider`) is valid; SaaS
116 * partner channels stay `PENDING` until the partner activates them.
117 *
118 * ### Creating a Channel
119 * **Example:** Google channel
120 * ```typescript
121 * const channel = yield* GCP.Eventarc.Channel("events", {
122 * location: "us-central1",
123 * labels: { env: "prod" },
124 * });
125 * ```
126 *
127 * **Example:** Third-party provider channel
128 * ```typescript
129 * const channel = yield* GCP.Eventarc.Channel("datadog", {
130 * channelId: "datadog-events",
131 * location: "us-central1",
132 * provider:
133 * "projects/my-project/locations/us-central1/providers/datadog",
134 * });
135 * ```
136 *
137 * ### Updating a Channel
138 * Re-declare the same logical id with changed props; the engine keeps the
139 * physical channel and patches it in place.
140 *
141 * **Example:** Change labels and CMEK
142 * ```typescript
143 * const channel = yield* GCP.Eventarc.Channel("events", {
144 * location: "us-central1",
145 * cryptoKeyName:
146 * "projects/my-project/locations/us-central1/keyRings/keys/cryptoKeys/events",
147 * labels: { env: "prod", role: "events" },
148 * });
149 * ```
150 *
151 * @resource
152 * @category Eventarc
153 */
154 export const Channel = Resource<Channel>("GCP.Eventarc.Channel");
155
156 export class ChannelNotResolved extends Data.TaggedError("GCP.Eventarc.ChannelNotResolved")<{
157 resourceName: string;
158 }> {}
159
160 export class ChannelStillExists extends Data.TaggedError("GCP.Eventarc.ChannelStillExists")<{
161 resourceName: string;
162 }> {}
163
164 const lastSegment = (value: string) => {
165 const trimmed = value.replace(/\/+$/, "");
166 const parts = trimmed.split("/");
167 return parts[parts.length - 1] || trimmed;
168 };
169
170 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
171 lastSegment(location ?? defaultLocation).toLowerCase();
172
173 const rfc1035 = (name: string): string => {
174 let next = name
175 .toLowerCase()
176 .replace(/[^a-z0-9-]/g, "-")
177 .replace(/-+/g, "-")
178 .replace(/^-+|-+$/g, "");
179 if (!/^[a-z]/.test(next)) next = `c${next}`;
180 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
181 return next.length > 0 ? next : "channel";
182 };
183
184 const resourceName = (project: string, location: string, channelId: string) =>
185 `projects/${project}/locations/${location}/channels/${channelId}`;
186
187 const parseName = (name: string, defaultLocation: string) => {
188 const parts = name.split("/").filter((part) => part.length > 0);
189 const channelsAt = parts.lastIndexOf("channels");
190 const locationsAt = parts.lastIndexOf("locations");
191 const projectsAt = parts.lastIndexOf("projects");
192 return {
193 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
194 location:
195 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
196 channelId:
197 channelsAt >= 0 && parts[channelsAt + 1] ? parts[channelsAt + 1]! : lastSegment(name),
198 };
199 };
200
201 const userLabels = (
202 labels: Record<string, string | undefined> | null | undefined,
203 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
204
205 const toId = (id: string, channelId: string | undefined, existing?: string) =>
206 Effect.gen(function* () {
207 if (channelId !== undefined) return rfc1035(channelId);
208 if (existing !== undefined) return existing;
209 return rfc1035(
210 yield* createPhysicalName({
211 id,
212 maxLength: MAX_NAME_LENGTH,
213 lowercase: true,
214 }),
215 );
216 });
217
218 const compact = <T extends Record<string, unknown>>(value: T): T => {
219 const next: Record<string, unknown> = {};
220 for (const [key, entry] of Object.entries(value)) {
221 if (entry !== undefined && entry !== "") next[key] = entry;
222 }
223 return next as T;
224 };
225
226 const providerKey = (provider: string | undefined, project: string, location: string) => {
227 if (provider === undefined || provider.length === 0) return "";
228 if (provider.includes("/")) return provider;
229 return `projects/${project}/locations/${location}/providers/${provider}`;
230 };
231
232 const cryptoKeyKey = (name: string | undefined) =>
233 name === undefined || name.length === 0 ? "" : name;
234
235 const toAttrs = (channel: eventarc.Channel, project: string, region: string) => {
236 const name = channel.name ?? "";
237 const parsed = parseName(name, region);
238 return {
239 name,
240 channelId: parsed.channelId,
241 project: parsed.project || project,
242 location: parsed.location,
243 provider: channel.provider,
244 cryptoKeyName: channel.cryptoKeyName,
245 labels: userLabels(channel.labels),
246 pubsubTopic: channel.pubsubTopic,
247 state: channel.state,
248 activationToken: channel.activationToken,
249 uid: channel.uid,
250 createTime: channel.createTime,
251 updateTime: channel.updateTime,
252 satisfiesPzs: channel.satisfiesPzs,
253 };
254 };
255
256 const getByName = (name: string) =>
257 eventarc
258 .getProjectsLocationsChannels({ name })
259 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
260
261 const waitUntilExists = (name: string) =>
262 getByName(name).pipe(
263 Effect.flatMap((channel) =>
264 channel
265 ? Effect.succeed(channel)
266 : Effect.fail(new ChannelNotResolved({ resourceName: name })),
267 ),
268 Effect.retry({
269 while: (error) => error._tag === "GCP.Eventarc.ChannelNotResolved",
270 times: 8,
271 schedule: Schedule.spaced("1 second"),
272 }),
273 );
274
275 const waitUntilGone = (name: string) =>
276 getByName(name).pipe(
277 Effect.flatMap((channel) =>
278 channel === undefined
279 ? Effect.void
280 : Effect.fail(new ChannelStillExists({ resourceName: name })),
281 ),
282 Effect.retry({
283 while: (error) => error._tag === "GCP.Eventarc.ChannelStillExists",
284 times: 10,
285 schedule: Schedule.spaced("2 seconds"),
286 }),
287 );
288
289 export const ChannelProvider = () =>
290 Provider.succeed(Channel, {
291 stables: ["name", "channelId", "project", "location", "uid", "createTime", "provider"],
292
293 diff: Effect.fn(function* ({ news, olds, output }) {
294 if (!isResolved(news)) return undefined;
295 const env = yield* GcpEnvironment.current;
296
297 const previousId = olds?.channelId ?? output?.channelId;
298 const nextId = news.channelId ? rfc1035(news.channelId) : previousId;
299 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
300 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
301 const project = output?.project ?? "";
302 const previousProvider = providerKey(
303 olds?.provider ?? output?.provider,
304 project,
305 previousLocation,
306 );
307 const nextProvider =
308 news.provider !== undefined
309 ? providerKey(news.provider, project, nextLocation)
310 : previousProvider;
311
312 const replace =
313 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
314 previousLocation !== nextLocation ||
315 previousProvider !== nextProvider;
316
317 if (!replace) return undefined;
318 return {
319 action: "replace" as const,
320 deleteFirst:
321 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
322 };
323 }),
324
325 read: Effect.fn(function* ({ id, olds, output }) {
326 const env = yield* GcpEnvironment.current;
327 const channelId = yield* toId(id, olds?.channelId, output?.channelId);
328 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
329 const name = output?.name ?? resourceName(env.project, location, channelId);
330 const existing = yield* getByName(name);
331 if (existing === undefined) return undefined;
332 const attrs = toAttrs(existing, env.project, env.region);
333 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
334 }),
335
336 list: () =>
337 Effect.gen(function* () {
338 const env = yield* GcpEnvironment.current;
339 return yield* eventarc.listProjectsLocationsChannels
340 .pages({
341 parent: `projects/${env.project}/locations/-`,
342 pageSize: 1000,
343 })
344 .pipe(
345 Stream.flatMap((page) => Stream.fromIterable(page.channels ?? [])),
346 Stream.filter((channel) =>
347 Object.keys(channel.labels ?? {}).some((key) => key.startsWith("alchemy-")),
348 ),
349 Stream.map((channel) => toAttrs(channel, env.project, env.region)),
350 Stream.runCollect,
351 Effect.map((chunk) => Array.from(chunk)),
352 Effect.catchTag("NotFound", () => Effect.succeed([])),
353 );
354 }),
355
356 reconcile: Effect.fn(function* ({ id, news, output }) {
357 const env = yield* GcpEnvironment.current;
358 const channelId = yield* toId(id, news.channelId, output?.channelId);
359 const location = normalizeLocation(news.location ?? output?.location, env.region);
360 const name = resourceName(env.project, location, channelId);
361 const desiredLabels = {
362 ...toLabels(news.labels),
363 ...(yield* createInternalLabels(id)),
364 };
365 const desiredProvider = news.provider
366 ? providerKey(news.provider, env.project, location)
367 : undefined;
368 const desiredCryptoKey =
369 news.cryptoKeyName && news.cryptoKeyName.length > 0 ? news.cryptoKeyName : undefined;
370
371 let current = yield* getByName(name);
372
373 if (current === undefined) {
374 const created = yield* eventarc
375 .createProjectsLocationsChannels({
376 parent: `projects/${env.project}/locations/${location}`,
377 channelId,
378 body: compact({
379 name,
380 labels: desiredLabels,
381 provider: desiredProvider,
382 cryptoKeyName: desiredCryptoKey,
383 }),
384 })
385 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
386 if (created !== undefined) {
387 yield* waitForOperation(created);
388 }
389 current = yield* waitUntilExists(name);
390 }
391
392 if (current === undefined) {
393 return yield* new ChannelNotResolved({ resourceName: name });
394 }
395
396 const observedLabels = tagRecord(current.labels);
397 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
398 const labelsChanged = upsert.length > 0 || removed.length > 0;
399 const cryptoKeyChanged =
400 cryptoKeyKey(current.cryptoKeyName) !== cryptoKeyKey(desiredCryptoKey);
401
402 if (labelsChanged || cryptoKeyChanged) {
403 const updateMask = [
404 labelsChanged ? "labels" : undefined,
405 cryptoKeyChanged ? "cryptoKeyName" : undefined,
406 ].filter((field): field is string => field !== undefined);
407
408 const patched = yield* eventarc.patchProjectsLocationsChannels({
409 name,
410 updateMask: updateMask.join(","),
411 body: {
412 name,
413 labels: desiredLabels,
414 cryptoKeyName: desiredCryptoKey,
415 },
416 });
417 yield* waitForOperation(patched);
418 current = yield* waitUntilExists(name);
419 }
420
421 return toAttrs(current, env.project, env.region);
422 }),
423
424 delete: Effect.fn(function* ({ output }) {
425 const existing = yield* getByName(output.name);
426 if (existing === undefined) return;
427 const operation = yield* eventarc
428 .deleteProjectsLocationsChannels({
429 name: output.name,
430 })
431 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
432 if (operation !== undefined) {
433 yield* waitForOperation(operation, { notFoundOk: true });
434 }
435 yield* waitUntilGone(output.name);
436 }),
437 });