The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as compute from "@distilled.cloud/gcp/compute_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 * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { ignoredCodes } from "./internal.ts"; |
| 15 | import { waitGlobalOperation } from "./operations.ts"; |
| 16 | |
| 17 | const MAX_NAME_LENGTH = 63; |
| 18 | const DEFAULT_SLA = "NO_SLA"; |
| 19 | |
| 20 | export type InterconnectAttachmentGroupIntent = compute.InterconnectAttachmentGroupIntent; |
| 21 | export type InterconnectAttachmentGroupAttachmentMap = |
| 22 | compute.InterconnectAttachmentGroupAttachmentMap; |
| 23 | |
| 24 | export type InterconnectAttachmentGroupProps = { |
| 25 | /** |
| 26 | * Group name (RFC1035, 1-63 characters). If omitted, a unique name is |
| 27 | * generated from the stack, stage, and logical id. Immutable — changing |
| 28 | * it replaces the group. |
| 29 | */ |
| 30 | interconnectAttachmentGroupName?: string; |
| 31 | /** |
| 32 | * Optional description. Attachment groups have no labels field, so |
| 33 | * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) |
| 34 | * is stored in a `[alchemy …]` prefix for `list` / nuke. Updated in |
| 35 | * place via `patch`. |
| 36 | */ |
| 37 | description?: string; |
| 38 | /** |
| 39 | * Intended availability SLA (`NO_SLA`, `PRODUCTION_NON_CRITICAL`, |
| 40 | * `PRODUCTION_CRITICAL`). Required on create. Updated in place. |
| 41 | * @default "NO_SLA" |
| 42 | */ |
| 43 | intent?: InterconnectAttachmentGroupIntent; |
| 44 | /** |
| 45 | * Member VLAN attachments. Keys are arbitrary; values are |
| 46 | * `{ attachment }` URLs. Updated in place via `patch`. |
| 47 | */ |
| 48 | attachments?: InterconnectAttachmentGroupAttachmentMap; |
| 49 | /** |
| 50 | * Optional InterconnectGroup URL that groups these attachments' |
| 51 | * interconnects. Only set when directed by Google Support. |
| 52 | */ |
| 53 | interconnectGroup?: string; |
| 54 | }; |
| 55 | |
| 56 | export type InterconnectAttachmentGroup = Resource< |
| 57 | "GCP.Compute.InterconnectAttachmentGroup", |
| 58 | InterconnectAttachmentGroupProps, |
| 59 | { |
| 60 | /** Group name. */ |
| 61 | interconnectAttachmentGroupName: string; |
| 62 | /** Project id. */ |
| 63 | project: string; |
| 64 | /** User description with the Alchemy ownership prefix stripped. */ |
| 65 | description: string | undefined; |
| 66 | /** User intent. */ |
| 67 | intent: InterconnectAttachmentGroupIntent | undefined; |
| 68 | /** Member VLAN attachments. */ |
| 69 | attachments: InterconnectAttachmentGroupAttachmentMap; |
| 70 | /** Linked InterconnectGroup URL, if any. */ |
| 71 | interconnectGroup: string | undefined; |
| 72 | /** Effective SLA reported by GCP. */ |
| 73 | configured: compute.InterconnectAttachmentGroupConfigured | undefined; |
| 74 | /** Logical structure of member attachments. */ |
| 75 | logicalStructure: compute.InterconnectAttachmentGroupLogicalStructure | undefined; |
| 76 | /** Optimistic-locking etag. */ |
| 77 | etag: string | undefined; |
| 78 | /** Server-assigned numeric id. */ |
| 79 | interconnectAttachmentGroupId: string | undefined; |
| 80 | /** Resource self-link. */ |
| 81 | selfLink: string | undefined; |
| 82 | /** RFC3339 creation timestamp. */ |
| 83 | creationTimestamp: string | undefined; |
| 84 | /** Resource kind. */ |
| 85 | kind: string | undefined; |
| 86 | }, |
| 87 | never, |
| 88 | Providers |
| 89 | >; |
| 90 | |
| 91 | /** |
| 92 | * A global Compute Engine Interconnect attachment group. |
| 93 | * |
| 94 | * Groups collect VLAN attachments so GCP can report the availability SLA |
| 95 | * they actually provide. Name is immutable. Description, intent, member |
| 96 | * attachments, and the optional InterconnectGroup URL update in place via |
| 97 | * `interconnectAttachmentGroups.patch`. Compute InterconnectAttachmentGroup |
| 98 | * has no labels field — Alchemy stamps ownership into the description so |
| 99 | * nuke can find leaked groups. |
| 100 | * |
| 101 | * ### Creating an Attachment Group |
| 102 | * **Example:** Generated name, no SLA |
| 103 | * ```typescript |
| 104 | * const group = yield* GCP.Compute.InterconnectAttachmentGroup("Vlans", { |
| 105 | * description: "dev vlan attachments", |
| 106 | * intent: { availabilitySla: "NO_SLA" }, |
| 107 | * }); |
| 108 | * ``` |
| 109 | * |
| 110 | * **Example:** Named group with a member attachment |
| 111 | * ```typescript |
| 112 | * const group = yield* GCP.Compute.InterconnectAttachmentGroup("Vlans", { |
| 113 | * interconnectAttachmentGroupName: "app-vlan-group", |
| 114 | * intent: { availabilitySla: "PRODUCTION_NON_CRITICAL" }, |
| 115 | * attachments: { |
| 116 | * primary: { attachment: attachment.selfLink }, |
| 117 | * }, |
| 118 | * }); |
| 119 | * ``` |
| 120 | * |
| 121 | * @resource |
| 122 | * @category Compute |
| 123 | */ |
| 124 | export const InterconnectAttachmentGroup = Resource<InterconnectAttachmentGroup>( |
| 125 | "GCP.Compute.InterconnectAttachmentGroup", |
| 126 | ); |
| 127 | |
| 128 | export class InterconnectAttachmentGroupNotResolved extends Data.TaggedError( |
| 129 | "GCP.Compute.InterconnectAttachmentGroupNotResolved", |
| 130 | )<{ |
| 131 | interconnectAttachmentGroupName: string; |
| 132 | }> {} |
| 133 | |
| 134 | export class InterconnectAttachmentGroupStillExists extends Data.TaggedError( |
| 135 | "GCP.Compute.InterconnectAttachmentGroupStillExists", |
| 136 | )<{ |
| 137 | interconnectAttachmentGroupName: string; |
| 138 | }> {} |
| 139 | |
| 140 | const lastSegment = (value: string | undefined): string => { |
| 141 | if (value === undefined || value.length === 0) return ""; |
| 142 | const trimmed = value.replace(/\/+$/, ""); |
| 143 | const parts = trimmed.split("/"); |
| 144 | return parts[parts.length - 1] || trimmed; |
| 145 | }; |
| 146 | |
| 147 | const rfc1035 = (name: string): string => { |
| 148 | let next = name |
| 149 | .toLowerCase() |
| 150 | .replace(/[^a-z0-9-]/g, "-") |
| 151 | .replace(/-+/g, "-") |
| 152 | .replace(/^-+/, "") |
| 153 | .replace(/-+$/, ""); |
| 154 | if (!/^[a-z]/.test(next)) next = `g${next}`; |
| 155 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 156 | return next.length > 0 ? next : "group"; |
| 157 | }; |
| 158 | |
| 159 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 160 | Effect.gen(function* () { |
| 161 | if (name !== undefined) return name; |
| 162 | if (existing !== undefined) return existing; |
| 163 | return rfc1035( |
| 164 | yield* createPhysicalName({ |
| 165 | id, |
| 166 | maxLength: MAX_NAME_LENGTH, |
| 167 | lowercase: true, |
| 168 | }), |
| 169 | ); |
| 170 | }); |
| 171 | |
| 172 | const encodeDescription = ( |
| 173 | labels: Record<string, string>, |
| 174 | description: string | undefined, |
| 175 | ): string => { |
| 176 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 177 | return description ? `${marker}\n${description}` : marker; |
| 178 | }; |
| 179 | |
| 180 | const parseDescription = ( |
| 181 | description: string | undefined, |
| 182 | ): { |
| 183 | labels: Record<string, string>; |
| 184 | description: string | undefined; |
| 185 | } => { |
| 186 | if (!description?.startsWith("[alchemy ")) { |
| 187 | return { labels: {}, description }; |
| 188 | } |
| 189 | const end = description.indexOf("]"); |
| 190 | if (end < 0) return { labels: {}, description }; |
| 191 | const labels: Record<string, string> = {}; |
| 192 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 193 | const eq = part.indexOf("="); |
| 194 | if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 195 | } |
| 196 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 197 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 198 | }; |
| 199 | |
| 200 | const hasOwnershipMarker = (description: string | undefined) => |
| 201 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 202 | |
| 203 | const slaOf = (intent: InterconnectAttachmentGroupIntent | undefined) => |
| 204 | (intent?.availabilitySla ?? DEFAULT_SLA).toUpperCase(); |
| 205 | |
| 206 | const membersKey = (members: InterconnectAttachmentGroupAttachmentMap | undefined) => |
| 207 | Object.entries(members ?? {}) |
| 208 | .map(([key, value]) => `${key}:${lastSegment(value?.attachment)}`) |
| 209 | .sort() |
| 210 | .join("|"); |
| 211 | |
| 212 | const toAttrs = ( |
| 213 | group: compute.InterconnectAttachmentGroup, |
| 214 | project: string, |
| 215 | ): InterconnectAttachmentGroup["Attributes"] => { |
| 216 | const parsed = parseDescription(group.description); |
| 217 | return { |
| 218 | interconnectAttachmentGroupName: group.name ?? "", |
| 219 | project, |
| 220 | description: parsed.description, |
| 221 | intent: group.intent, |
| 222 | attachments: group.attachments ?? {}, |
| 223 | interconnectGroup: group.interconnectGroup, |
| 224 | configured: group.configured, |
| 225 | logicalStructure: group.logicalStructure, |
| 226 | etag: group.etag, |
| 227 | interconnectAttachmentGroupId: group.id, |
| 228 | selfLink: group.selfLink, |
| 229 | creationTimestamp: group.creationTimestamp, |
| 230 | kind: group.kind, |
| 231 | }; |
| 232 | }; |
| 233 | |
| 234 | const getByName = (project: string, interconnectAttachmentGroup: string) => |
| 235 | compute |
| 236 | .getInterconnectAttachmentGroups({ |
| 237 | project, |
| 238 | interconnectAttachmentGroup, |
| 239 | }) |
| 240 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 241 | |
| 242 | const awaitResource = (project: string, interconnectAttachmentGroupName: string) => |
| 243 | getByName(project, interconnectAttachmentGroupName).pipe( |
| 244 | Effect.flatMap((group) => |
| 245 | group !== undefined |
| 246 | ? Effect.succeed(group) |
| 247 | : Effect.fail( |
| 248 | new InterconnectAttachmentGroupNotResolved({ |
| 249 | interconnectAttachmentGroupName, |
| 250 | }), |
| 251 | ), |
| 252 | ), |
| 253 | Effect.retry({ |
| 254 | while: (error) => error._tag === "GCP.Compute.InterconnectAttachmentGroupNotResolved", |
| 255 | times: 8, |
| 256 | schedule: Schedule.spaced("1 second"), |
| 257 | }), |
| 258 | ); |
| 259 | |
| 260 | const waitUntilGone = (project: string, interconnectAttachmentGroupName: string) => |
| 261 | getByName(project, interconnectAttachmentGroupName).pipe( |
| 262 | Effect.flatMap((group) => |
| 263 | group === undefined |
| 264 | ? Effect.void |
| 265 | : Effect.fail( |
| 266 | new InterconnectAttachmentGroupStillExists({ |
| 267 | interconnectAttachmentGroupName, |
| 268 | }), |
| 269 | ), |
| 270 | ), |
| 271 | Effect.retry({ |
| 272 | while: (error) => error._tag === "GCP.Compute.InterconnectAttachmentGroupStillExists", |
| 273 | times: 10, |
| 274 | schedule: Schedule.spaced("1 second"), |
| 275 | }), |
| 276 | Effect.catchTag("GCP.Compute.InterconnectAttachmentGroupStillExists", () => Effect.void), |
| 277 | ); |
| 278 | |
| 279 | const runOp = <E extends { readonly _tag: string }, R>( |
| 280 | project: string, |
| 281 | interconnectAttachmentGroupName: string, |
| 282 | start: Effect.Effect<compute.Operation, E, R>, |
| 283 | options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean }, |
| 284 | ) => |
| 285 | start.pipe( |
| 286 | Effect.flatMap((operation) => |
| 287 | waitGlobalOperation(project, operation, { |
| 288 | ignore: ignoredCodes(options), |
| 289 | }), |
| 290 | ), |
| 291 | Effect.retry({ |
| 292 | while: (error) => error._tag === "Conflict", |
| 293 | times: 5, |
| 294 | schedule: Schedule.spaced("1 second"), |
| 295 | }), |
| 296 | ); |
| 297 | |
| 298 | export const InterconnectAttachmentGroupProvider = () => |
| 299 | Provider.succeed(InterconnectAttachmentGroup, { |
| 300 | stables: [ |
| 301 | "interconnectAttachmentGroupName", |
| 302 | "project", |
| 303 | "interconnectAttachmentGroupId", |
| 304 | "selfLink", |
| 305 | "creationTimestamp", |
| 306 | ], |
| 307 | |
| 308 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 309 | if (!isResolved(news)) return undefined; |
| 310 | const previousName = |
| 311 | olds?.interconnectAttachmentGroupName ?? output?.interconnectAttachmentGroupName; |
| 312 | const nextName = news.interconnectAttachmentGroupName ?? previousName; |
| 313 | if (previousName !== undefined && nextName !== undefined && previousName !== nextName) { |
| 314 | return { action: "replace" as const, deleteFirst: false }; |
| 315 | } |
| 316 | return undefined; |
| 317 | }), |
| 318 | |
| 319 | read: Effect.fn(function* ({ id, olds, output }) { |
| 320 | const env = yield* GcpEnvironment.current; |
| 321 | const interconnectAttachmentGroupName = yield* toName( |
| 322 | id, |
| 323 | olds?.interconnectAttachmentGroupName, |
| 324 | output?.interconnectAttachmentGroupName, |
| 325 | ); |
| 326 | const existing = yield* getByName(env.project, interconnectAttachmentGroupName); |
| 327 | if (existing === undefined) return undefined; |
| 328 | const attrs = toAttrs(existing, env.project); |
| 329 | const { labels } = parseDescription(existing.description); |
| 330 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 331 | }), |
| 332 | |
| 333 | list: () => |
| 334 | Effect.gen(function* () { |
| 335 | const env = yield* GcpEnvironment.current; |
| 336 | return yield* compute.listInterconnectAttachmentGroups |
| 337 | .items({ |
| 338 | project: env.project, |
| 339 | maxResults: 500, |
| 340 | returnPartialSuccess: true, |
| 341 | }) |
| 342 | .pipe( |
| 343 | Stream.filter((group) => hasOwnershipMarker(group.description)), |
| 344 | Stream.map((group) => toAttrs(group, env.project)), |
| 345 | Stream.runCollect, |
| 346 | Effect.map((items) => Array.from(items)), |
| 347 | Effect.catchTag("NotFound", () => |
| 348 | Effect.succeed([] as InterconnectAttachmentGroup["Attributes"][]), |
| 349 | ), |
| 350 | ); |
| 351 | }), |
| 352 | |
| 353 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 354 | const env = yield* GcpEnvironment.current; |
| 355 | const interconnectAttachmentGroupName = yield* toName( |
| 356 | id, |
| 357 | news.interconnectAttachmentGroupName, |
| 358 | output?.interconnectAttachmentGroupName, |
| 359 | ); |
| 360 | const ownership = yield* createInternalLabels(id); |
| 361 | const desiredDescription = encodeDescription(ownership, news.description); |
| 362 | const intent: InterconnectAttachmentGroupIntent = { |
| 363 | availabilitySla: slaOf(news.intent ?? output?.intent), |
| 364 | }; |
| 365 | |
| 366 | let current = yield* getByName(env.project, interconnectAttachmentGroupName); |
| 367 | |
| 368 | if (current === undefined) { |
| 369 | yield* compute |
| 370 | .insertInterconnectAttachmentGroups({ |
| 371 | project: env.project, |
| 372 | body: { |
| 373 | name: interconnectAttachmentGroupName, |
| 374 | description: desiredDescription, |
| 375 | intent, |
| 376 | attachments: news.attachments, |
| 377 | interconnectGroup: news.interconnectGroup, |
| 378 | }, |
| 379 | }) |
| 380 | .pipe( |
| 381 | Effect.flatMap((operation) => |
| 382 | waitGlobalOperation(env.project, operation, { |
| 383 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 384 | }), |
| 385 | ), |
| 386 | Effect.catchTag("Conflict", () => Effect.void), |
| 387 | ); |
| 388 | current = yield* awaitResource(env.project, interconnectAttachmentGroupName); |
| 389 | } |
| 390 | |
| 391 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 392 | const intentChanged = slaOf(current.intent) !== slaOf(intent); |
| 393 | const membersChanged = |
| 394 | news.attachments !== undefined && |
| 395 | membersKey(current.attachments) !== membersKey(news.attachments); |
| 396 | const groupChanged = |
| 397 | news.interconnectGroup !== undefined && |
| 398 | lastSegment(current.interconnectGroup) !== lastSegment(news.interconnectGroup); |
| 399 | |
| 400 | if (descriptionChanged || intentChanged || membersChanged || groupChanged) { |
| 401 | yield* runOp( |
| 402 | env.project, |
| 403 | interconnectAttachmentGroupName, |
| 404 | compute.patchInterconnectAttachmentGroups({ |
| 405 | project: env.project, |
| 406 | interconnectAttachmentGroup: interconnectAttachmentGroupName, |
| 407 | updateMask: "description,intent,attachments,interconnectGroup", |
| 408 | body: { |
| 409 | etag: current.etag, |
| 410 | description: desiredDescription, |
| 411 | intent, |
| 412 | attachments: news.attachments !== undefined ? news.attachments : current.attachments, |
| 413 | interconnectGroup: news.interconnectGroup ?? current.interconnectGroup, |
| 414 | }, |
| 415 | }), |
| 416 | ); |
| 417 | current = (yield* getByName(env.project, interconnectAttachmentGroupName)) ?? current; |
| 418 | } |
| 419 | |
| 420 | return toAttrs(current, env.project); |
| 421 | }), |
| 422 | |
| 423 | delete: Effect.fn(function* ({ output }) { |
| 424 | if (!output.interconnectAttachmentGroupName) return; |
| 425 | const env = yield* GcpEnvironment.current; |
| 426 | const project = output.project || env.project; |
| 427 | yield* compute |
| 428 | .deleteInterconnectAttachmentGroups({ |
| 429 | project, |
| 430 | interconnectAttachmentGroup: output.interconnectAttachmentGroupName, |
| 431 | }) |
| 432 | .pipe( |
| 433 | Effect.flatMap((operation) => |
| 434 | waitGlobalOperation(project, operation, { |
| 435 | ignore: ["RESOURCE_NOT_FOUND"], |
| 436 | }), |
| 437 | ), |
| 438 | Effect.catchTag("NotFound", () => Effect.void), |
| 439 | Effect.retry({ |
| 440 | while: (error) => error._tag === "Conflict", |
| 441 | times: 8, |
| 442 | schedule: Schedule.spaced("2 seconds"), |
| 443 | }), |
| 444 | ); |
| 445 | yield* waitUntilGone(project, output.interconnectAttachmentGroupName); |
| 446 | }), |
| 447 | }); |