@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 345 lines 11.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 hasAlchemyLabelKeys,
19 loggingKey,
20 normalizeLocation,
21 parentOf,
22 parseName,
23 resourceName,
24 rfc1035,
25 sameJson,
26 textKey,
27 toLoggingConfig,
28 toPhysicalId,
29 userAnnotations,
30 userLabels,
31 retryOnTransient,
32 waitForOperation,
33 waitUntilGone,
34 waitUntilPresent,
35 } from "./internal.ts";
36
37 export type { LoggingConfig } from "./internal.ts";
38
39 const COLLECTION = "messageBuses";
40
41 export type MessageBusProps = {
42 /**
43 * Message bus id (the `{messageBus}` segment of
44 * `projects/{project}/locations/{location}/messageBuses/{messageBus}`).
45 * If omitted, a unique name is generated from the stack, stage, and
46 * logical id. Must match `[a-z]([a-z0-9-]*[a-z0-9])?` and be 1-63
47 * characters. Immutable — changing it replaces the bus.
48 */
49 messageBusId?: string;
50 /**
51 * Eventarc Advanced location (`us-central1`, `us-east4`, …). Immutable
52 * — changing it replaces the bus. `US-CENTRAL1` is accepted and
53 * normalized to `us-central1`.
54 * @default the stack's GCP region (`GCP.Region`, else the profile
55 * region, else `us-central1`)
56 */
57 location?: string;
58 /**
59 * Human-readable display name.
60 */
61 displayName?: string;
62 /**
63 * Customer-managed Cloud KMS key used to encrypt/decrypt event data,
64 * as
65 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`.
66 */
67 cryptoKeyName?: string;
68 /**
69 * Platform logging configuration applied to the bus and its
70 * enrollments.
71 */
72 loggingConfig?: LoggingConfig;
73 /**
74 * User labels. Alchemy ownership labels are merged in automatically.
75 */
76 labels?: Record<string, string>;
77 /**
78 * Free-form annotations.
79 */
80 annotations?: Record<string, string>;
81 };
82
83 export type MessageBus = Resource<
84 "GCP.Eventarc.MessageBus",
85 MessageBusProps,
86 {
87 /** Full resource name `projects/{project}/locations/{location}/messageBuses/{messageBus}`. */
88 name: string;
89 /** Message bus id (last path segment). */
90 messageBusId: string;
91 /** Project id. */
92 project: string;
93 /** Location id (`us-central1`, …). */
94 location: string;
95 /** Display name. */
96 displayName: string | undefined;
97 /** Customer-managed KMS key, if any. */
98 cryptoKeyName: string | undefined;
99 /** Platform logging configuration. */
100 loggingConfig: LoggingConfig | undefined;
101 /** User labels (Alchemy ownership labels stripped). */
102 labels: Record<string, string>;
103 /** User annotations. */
104 annotations: Record<string, string>;
105 /** Server-assigned UUID4, stable until delete. */
106 uid: string | undefined;
107 /** Server checksum of the resource. */
108 etag: string | undefined;
109 /** RFC3339 creation timestamp. */
110 createTime: string | undefined;
111 /** RFC3339 last-update timestamp. */
112 updateTime: string | undefined;
113 },
114 never,
115 Providers
116 >;
117
118 /**
119 * An Eventarc Advanced message bus that routes published events to
120 * enrollments. One bus may exist per project per region.
121 *
122 * `messageBusId` and `location` are identity — changing either replaces
123 * the bus. Display name, labels, annotations, logging, and CMEK update
124 * in place.
125 *
126 * ### Creating a MessageBus
127 * **Example:** Generated name
128 * ```typescript
129 * const bus = yield* GCP.Eventarc.MessageBus("Events", {
130 * location: "us-central1",
131 * labels: { env: "prod" },
132 * });
133 * ```
134 *
135 * **Example:** Named bus with logging
136 * ```typescript
137 * const bus = yield* GCP.Eventarc.MessageBus("Events", {
138 * messageBusId: "app-events",
139 * location: "us-central1",
140 * displayName: "app events",
141 * loggingConfig: { logSeverity: "INFO" },
142 * });
143 * ```
144 *
145 * ### Updating a MessageBus
146 * Re-declare the same logical id with changed props; the engine keeps the
147 * physical bus and patches it in place.
148 *
149 * **Example:** Change labels and display name
150 * ```typescript
151 * const bus = yield* GCP.Eventarc.MessageBus("Events", {
152 * location: "us-central1",
153 * displayName: "app events v2",
154 * labels: { env: "prod", role: "bus" },
155 * });
156 * ```
157 *
158 * @resource
159 * @category Eventarc
160 */
161 export const MessageBus = Resource<MessageBus>("GCP.Eventarc.MessageBus");
162
163 const toAttrs = (bus: eventarc.MessageBus, project: string, region: string) => {
164 const name = bus.name ?? "";
165 const parsed = parseName(name, COLLECTION, region);
166 return {
167 name,
168 messageBusId: parsed.id,
169 project: parsed.project || project,
170 location: parsed.location,
171 displayName: bus.displayName,
172 cryptoKeyName: bus.cryptoKeyName,
173 loggingConfig: toLoggingConfig(bus.loggingConfig),
174 labels: userLabels(bus.labels),
175 annotations: userAnnotations(bus.annotations),
176 uid: bus.uid,
177 etag: bus.etag,
178 createTime: bus.createTime,
179 updateTime: bus.updateTime,
180 };
181 };
182
183 const getByName = (name: string) =>
184 eventarc
185 .getProjectsLocationsMessageBuses({ name })
186 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
187
188 export const MessageBusProvider = () =>
189 Provider.succeed(MessageBus, {
190 stables: ["name", "messageBusId", "project", "location", "uid", "createTime"],
191
192 diff: Effect.fn(function* ({ news, olds, output }) {
193 if (!isResolved(news)) return undefined;
194 const env = yield* GcpEnvironment.current;
195 const previousId = olds?.messageBusId ?? output?.messageBusId;
196 const nextId = news.messageBusId ? rfc1035(news.messageBusId, "message-bus") : previousId;
197 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
198 const nextLocation = normalizeLocation(
199 news.location ?? olds?.location ?? output?.location,
200 env.region,
201 );
202 if (
203 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
204 previousLocation !== nextLocation
205 ) {
206 return { action: "replace" as const };
207 }
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ id, olds, output }) {
212 const env = yield* GcpEnvironment.current;
213 const messageBusId = yield* toPhysicalId(
214 id,
215 olds?.messageBusId,
216 output?.messageBusId,
217 "message-bus",
218 );
219 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
220 const name = output?.name ?? resourceName(env.project, location, COLLECTION, messageBusId);
221 const existing = yield* getByName(name);
222 if (existing === undefined) return undefined;
223 const attrs = toAttrs(existing, env.project, env.region);
224 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
225 }),
226
227 list: () =>
228 Effect.gen(function* () {
229 const env = yield* GcpEnvironment.current;
230 const items = yield* collectPages(
231 eventarc.listProjectsLocationsMessageBuses.pages({
232 parent: parentOf(env.project, "-"),
233 pageSize: 1000,
234 }),
235 (page) => page.messageBuses,
236 );
237 return items
238 .filter((item) => hasAlchemyLabelKeys(item.labels))
239 .map((item) => toAttrs(item, env.project, env.region));
240 }),
241
242 reconcile: Effect.fn(function* ({ id, news, output }) {
243 const env = yield* GcpEnvironment.current;
244 const messageBusId = yield* toPhysicalId(
245 id,
246 news.messageBusId,
247 output?.messageBusId,
248 "message-bus",
249 );
250 const location = normalizeLocation(news.location ?? output?.location, env.region);
251 const name = resourceName(env.project, location, COLLECTION, messageBusId);
252 const desiredLabels = {
253 ...toLabels(news.labels),
254 ...(yield* createInternalLabels(id)),
255 };
256 const desiredLogging = toLoggingConfig(news.loggingConfig);
257 const desiredCrypto =
258 news.cryptoKeyName && news.cryptoKeyName.length > 0 ? news.cryptoKeyName : undefined;
259 const desiredAnnotations = news.annotations ? tagRecord(news.annotations) : undefined;
260
261 let current = yield* getByName(name);
262
263 if (current === undefined) {
264 const created = yield* eventarc
265 .createProjectsLocationsMessageBuses({
266 parent: parentOf(env.project, location),
267 messageBusId,
268 body: compact({
269 name,
270 displayName: news.displayName,
271 cryptoKeyName: desiredCrypto,
272 loggingConfig: desiredLogging,
273 labels: desiredLabels,
274 annotations: desiredAnnotations,
275 }),
276 })
277 .pipe(
278 Effect.retry({
279 while: (error) => error._tag === "Conflict",
280 times: 5,
281 schedule: Schedule.spaced("2 seconds"),
282 }),
283 Effect.catchTag("Conflict", () => Effect.undefined),
284 );
285 if (created !== undefined) {
286 yield* waitForOperation(created);
287 }
288 current = yield* waitUntilPresent(getByName(name), name);
289 }
290
291 const observedLabels = tagRecord(current.labels);
292 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
293 const updateMask = changedFields([
294 ["labels", upsert.length > 0 || removed.length > 0],
295 ["displayName", textKey(current.displayName) !== textKey(news.displayName)],
296 ["cryptoKeyName", cryptoKeyKey(current.cryptoKeyName) !== cryptoKeyKey(desiredCrypto)],
297 ["loggingConfig", loggingKey(current.loggingConfig) !== loggingKey(desiredLogging)],
298 ["annotations", !sameJson(tagRecord(current.annotations), desiredAnnotations ?? {})],
299 ]);
300
301 if (updateMask.length > 0) {
302 const patched = yield* eventarc.patchProjectsLocationsMessageBuses({
303 name: current.name ?? name,
304 updateMask: updateMask.join(","),
305 body: {
306 name: current.name ?? name,
307 displayName: news.displayName,
308 cryptoKeyName: desiredCrypto,
309 loggingConfig: desiredLogging,
310 labels: desiredLabels,
311 annotations: desiredAnnotations ?? {},
312 },
313 });
314 yield* waitForOperation(patched);
315 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
316 }
317
318 return toAttrs(current, env.project, env.region);
319 }),
320
321 delete: Effect.fn(function* ({ output }) {
322 yield* retryOnTransient(
323 Effect.gen(function* () {
324 const existing = yield* getByName(output.name);
325 if (existing === undefined) return;
326 const operation = yield* eventarc
327 .deleteProjectsLocationsMessageBuses({
328 name: output.name,
329 allowMissing: true,
330 })
331 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
332 if (operation !== undefined) {
333 yield* waitForOperation(operation, { notFoundOk: true });
334 }
335 }),
336 ).pipe(
337 Effect.catchTag("GCP.OperationFailed", (error) =>
338 getByName(output.name).pipe(
339 Effect.flatMap((current) => (current === undefined ? Effect.void : Effect.fail(error))),
340 ),
341 ),
342 );
343 yield* waitUntilGone(getByName(output.name), output.name);
344 }),
345 });