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