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 { waitGlobalOperation } from "./operations.ts"; |
| 15 | |
| 16 | const MAX_NAME_LENGTH = 63; |
| 17 | |
| 18 | export type WireGroupWireProperties = compute.WireProperties; |
| 19 | export type WireGroupEndpoint = compute.WireGroupEndpoint; |
| 20 | export type WireGroupEndpointMap = compute.WireGroupEndpointMap; |
| 21 | |
| 22 | export type WireGroupProps = { |
| 23 | /** |
| 24 | * Wire group name (RFC1035, 1-63 characters). If omitted, a unique name |
| 25 | * is generated from the stack, stage, and logical id. Changing the name |
| 26 | * replaces the group. |
| 27 | */ |
| 28 | wireGroupName?: string; |
| 29 | /** |
| 30 | * Parent cross-site network name. Immutable — changing it replaces the |
| 31 | * group. |
| 32 | */ |
| 33 | crossSiteNetwork: string; |
| 34 | /** |
| 35 | * Optional description. Compute wire groups have no labels field, so |
| 36 | * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) |
| 37 | * is stored in a `[alchemy …]` prefix for `list` / nuke. |
| 38 | */ |
| 39 | description?: string; |
| 40 | /** |
| 41 | * Whether wires in the group are enabled. Mutable in place. |
| 42 | * @default true |
| 43 | */ |
| 44 | adminEnabled?: boolean; |
| 45 | /** |
| 46 | * Properties applied to every wire (bandwidth, fault response). |
| 47 | */ |
| 48 | wireProperties?: WireGroupWireProperties; |
| 49 | /** |
| 50 | * Logical endpoints keyed by RFC1035 labels. Each endpoint lists |
| 51 | * interconnects and VLAN tags. |
| 52 | */ |
| 53 | endpoints?: WireGroupEndpointMap; |
| 54 | }; |
| 55 | |
| 56 | export type WireGroup = Resource< |
| 57 | "GCP.Compute.WireGroup", |
| 58 | WireGroupProps, |
| 59 | { |
| 60 | /** Wire group name. */ |
| 61 | wireGroupName: string; |
| 62 | /** Parent cross-site network name. */ |
| 63 | crossSiteNetwork: string; |
| 64 | /** Server-assigned numeric id. */ |
| 65 | wireGroupId: string | undefined; |
| 66 | /** Project id. */ |
| 67 | project: string; |
| 68 | /** User description with the Alchemy ownership prefix stripped. */ |
| 69 | description: string | undefined; |
| 70 | /** Whether wires in the group are enabled. */ |
| 71 | adminEnabled: boolean; |
| 72 | /** Wire properties. */ |
| 73 | wireProperties: WireGroupWireProperties | undefined; |
| 74 | /** Logical endpoints. */ |
| 75 | endpoints: WireGroupEndpointMap | undefined; |
| 76 | /** Whether the group still has pending wire changes. */ |
| 77 | reconciling: boolean; |
| 78 | /** Compute Engine self-link. */ |
| 79 | selfLink: string | undefined; |
| 80 | /** RFC3339 creation timestamp. */ |
| 81 | creationTimestamp: string | undefined; |
| 82 | }, |
| 83 | never, |
| 84 | Providers |
| 85 | >; |
| 86 | |
| 87 | /** |
| 88 | * A global Compute Engine wire group on a cross-site network. |
| 89 | * |
| 90 | * Wire groups connect Interconnect endpoints across metros. Compute Engine |
| 91 | * has no labels on this resource, so Alchemy stamps ownership into the |
| 92 | * description so `list` / `pnpm nuke:gcp` can find them. |
| 93 | * |
| 94 | * Name and parent `crossSiteNetwork` are immutable — changing them |
| 95 | * replaces the group. `adminEnabled`, `wireProperties`, `endpoints`, and |
| 96 | * description update in place via `wireGroups.patch`. |
| 97 | * |
| 98 | * ### Creating a Wire Group |
| 99 | * **Example:** Two-endpoint VLAN wire group |
| 100 | * ```typescript |
| 101 | * const wires = yield* GCP.Compute.WireGroup("metro", { |
| 102 | * crossSiteNetwork: network.crossSiteNetworkName, |
| 103 | * description: "nyc-to-sfo", |
| 104 | * wireProperties: { |
| 105 | * bandwidthUnmetered: "10", |
| 106 | * bandwidthAllocation: "SHARED_WITH_WIRE_GROUP", |
| 107 | * }, |
| 108 | * endpoints: { |
| 109 | * nyc: { |
| 110 | * interconnects: { |
| 111 | * a: { interconnect: "global/interconnects/nyc-a", vlanTags: [100] }, |
| 112 | * }, |
| 113 | * }, |
| 114 | * sfo: { |
| 115 | * interconnects: { |
| 116 | * a: { interconnect: "global/interconnects/sfo-a", vlanTags: [100] }, |
| 117 | * }, |
| 118 | * }, |
| 119 | * }, |
| 120 | * }); |
| 121 | * ``` |
| 122 | * |
| 123 | * @resource |
| 124 | * @category Compute |
| 125 | */ |
| 126 | export const WireGroup = Resource<WireGroup>("GCP.Compute.WireGroup"); |
| 127 | |
| 128 | export class WireGroupNotResolved extends Data.TaggedError("GCP.Compute.WireGroupNotResolved")<{ |
| 129 | wireGroupName: string; |
| 130 | crossSiteNetwork: string; |
| 131 | }> {} |
| 132 | |
| 133 | export class WireGroupStillExists extends Data.TaggedError("GCP.Compute.WireGroupStillExists")<{ |
| 134 | wireGroupName: string; |
| 135 | }> {} |
| 136 | |
| 137 | const lastSegment = (value: string | undefined): string => { |
| 138 | if (value === undefined || value.length === 0) return ""; |
| 139 | const trimmed = value.replace(/\/+$/, ""); |
| 140 | const parts = trimmed.split("/"); |
| 141 | return parts[parts.length - 1] || trimmed; |
| 142 | }; |
| 143 | |
| 144 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 145 | Effect.gen(function* () { |
| 146 | if (name !== undefined) return name; |
| 147 | if (existing !== undefined) return existing; |
| 148 | const generated = yield* createPhysicalName({ |
| 149 | id, |
| 150 | maxLength: MAX_NAME_LENGTH, |
| 151 | lowercase: true, |
| 152 | }); |
| 153 | return /^[a-z]/.test(generated) ? generated : `w${generated}`.slice(0, MAX_NAME_LENGTH); |
| 154 | }); |
| 155 | |
| 156 | const encodeDescription = ( |
| 157 | labels: Record<string, string>, |
| 158 | description: string | undefined, |
| 159 | ): string => { |
| 160 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 161 | return description ? `${marker}\n${description}` : marker; |
| 162 | }; |
| 163 | |
| 164 | const parseDescription = ( |
| 165 | description: string | undefined, |
| 166 | ): { |
| 167 | labels: Record<string, string>; |
| 168 | description: string | undefined; |
| 169 | } => { |
| 170 | if (!description?.startsWith("[alchemy ")) { |
| 171 | return { labels: {}, description }; |
| 172 | } |
| 173 | const end = description.indexOf("]"); |
| 174 | if (end < 0) return { labels: {}, description }; |
| 175 | const labels: Record<string, string> = {}; |
| 176 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 177 | const eq = part.indexOf("="); |
| 178 | if (eq > 0) { |
| 179 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 180 | } |
| 181 | } |
| 182 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 183 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 184 | }; |
| 185 | |
| 186 | const hasOwnershipMarker = (description: string | undefined) => |
| 187 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 188 | |
| 189 | const sameJson = (left: unknown, right: unknown) => |
| 190 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 191 | |
| 192 | const toBody = ( |
| 193 | wireGroupName: string, |
| 194 | props: WireGroupProps, |
| 195 | ownership: Record<string, string>, |
| 196 | ): compute.WireGroup => ({ |
| 197 | name: wireGroupName, |
| 198 | description: encodeDescription(ownership, props.description), |
| 199 | adminEnabled: props.adminEnabled ?? true, |
| 200 | wireProperties: props.wireProperties, |
| 201 | endpoints: props.endpoints, |
| 202 | }); |
| 203 | |
| 204 | const toAttrs = ( |
| 205 | group: compute.WireGroup, |
| 206 | project: string, |
| 207 | crossSiteNetwork: string, |
| 208 | ): WireGroup["Attributes"] => { |
| 209 | const parsed = parseDescription(group.description); |
| 210 | return { |
| 211 | wireGroupName: group.name ?? group.id ?? "", |
| 212 | crossSiteNetwork: lastSegment(crossSiteNetwork), |
| 213 | wireGroupId: group.id, |
| 214 | project, |
| 215 | description: parsed.description, |
| 216 | adminEnabled: group.adminEnabled !== false, |
| 217 | wireProperties: group.wireProperties, |
| 218 | endpoints: group.endpoints, |
| 219 | reconciling: group.reconciling === true, |
| 220 | selfLink: group.selfLink, |
| 221 | creationTimestamp: group.creationTimestamp, |
| 222 | }; |
| 223 | }; |
| 224 | |
| 225 | const getByName = (project: string, crossSiteNetwork: string, wireGroup: string) => |
| 226 | compute |
| 227 | .getWireGroups({ project, crossSiteNetwork, wireGroup }) |
| 228 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 229 | |
| 230 | const waitGroupGone = (project: string, crossSiteNetwork: string, wireGroupName: string) => |
| 231 | getByName(project, crossSiteNetwork, wireGroupName).pipe( |
| 232 | Effect.flatMap((group) => |
| 233 | group === undefined |
| 234 | ? Effect.void |
| 235 | : Effect.fail( |
| 236 | new WireGroupStillExists({ |
| 237 | wireGroupName, |
| 238 | }), |
| 239 | ), |
| 240 | ), |
| 241 | Effect.retry({ |
| 242 | while: (error) => error instanceof WireGroupStillExists, |
| 243 | times: 10, |
| 244 | schedule: Schedule.spaced("2 seconds"), |
| 245 | }), |
| 246 | ); |
| 247 | |
| 248 | const listParents = (project: string) => |
| 249 | compute.listCrossSiteNetworks |
| 250 | .items({ project, maxResults: 500, returnPartialSuccess: true }) |
| 251 | .pipe( |
| 252 | Stream.runCollect, |
| 253 | Effect.map((chunk) => Array.from(chunk)), |
| 254 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 255 | ); |
| 256 | |
| 257 | export const WireGroupProvider = () => |
| 258 | Provider.succeed(WireGroup, { |
| 259 | stables: [ |
| 260 | "wireGroupName", |
| 261 | "wireGroupId", |
| 262 | "project", |
| 263 | "crossSiteNetwork", |
| 264 | "selfLink", |
| 265 | "creationTimestamp", |
| 266 | ], |
| 267 | |
| 268 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 269 | if (!isResolved(news)) return undefined; |
| 270 | |
| 271 | const previousName = olds?.wireGroupName ?? output?.wireGroupName; |
| 272 | const nextName = news.wireGroupName ?? previousName; |
| 273 | const nameChanged = |
| 274 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 275 | |
| 276 | const previousParent = lastSegment(olds?.crossSiteNetwork ?? output?.crossSiteNetwork); |
| 277 | const nextParent = lastSegment(news.crossSiteNetwork); |
| 278 | const parentChanged = |
| 279 | previousParent.length > 0 && nextParent.length > 0 && previousParent !== nextParent; |
| 280 | |
| 281 | if (nameChanged || parentChanged) { |
| 282 | return { |
| 283 | action: "replace" as const, |
| 284 | deleteFirst: !parentChanged && !nameChanged ? true : parentChanged, |
| 285 | }; |
| 286 | } |
| 287 | return undefined; |
| 288 | }), |
| 289 | |
| 290 | read: Effect.fn(function* ({ id, olds, output }) { |
| 291 | const env = yield* GcpEnvironment.current; |
| 292 | const wireGroupName = yield* toName(id, olds?.wireGroupName, output?.wireGroupName); |
| 293 | const preferredParent = lastSegment(olds?.crossSiteNetwork ?? output?.crossSiteNetwork); |
| 294 | |
| 295 | if (preferredParent.length > 0) { |
| 296 | const existing = yield* getByName(env.project, preferredParent, wireGroupName); |
| 297 | if (existing !== undefined) { |
| 298 | const attrs = toAttrs(existing, env.project, preferredParent); |
| 299 | const { labels } = parseDescription(existing.description); |
| 300 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | const parents = yield* listParents(env.project); |
| 305 | for (const parent of parents) { |
| 306 | const parentName = parent.name; |
| 307 | if (parentName === undefined) continue; |
| 308 | const existing = yield* getByName(env.project, parentName, wireGroupName); |
| 309 | if (existing === undefined) continue; |
| 310 | const attrs = toAttrs(existing, env.project, parentName); |
| 311 | const { labels } = parseDescription(existing.description); |
| 312 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 313 | } |
| 314 | return undefined; |
| 315 | }), |
| 316 | |
| 317 | list: () => |
| 318 | Effect.gen(function* () { |
| 319 | const env = yield* GcpEnvironment.current; |
| 320 | const parents = yield* listParents(env.project); |
| 321 | const groups = yield* Effect.forEach( |
| 322 | parents, |
| 323 | (parent) => { |
| 324 | const crossSiteNetwork = parent.name; |
| 325 | if (crossSiteNetwork === undefined) { |
| 326 | return Effect.succeed([] as WireGroup["Attributes"][]); |
| 327 | } |
| 328 | return compute.listWireGroups |
| 329 | .items({ |
| 330 | project: env.project, |
| 331 | crossSiteNetwork, |
| 332 | maxResults: 500, |
| 333 | returnPartialSuccess: true, |
| 334 | }) |
| 335 | .pipe( |
| 336 | Stream.filter((group) => hasOwnershipMarker(group.description)), |
| 337 | Stream.map((group) => toAttrs(group, env.project, crossSiteNetwork)), |
| 338 | Stream.runCollect, |
| 339 | Effect.map((chunk) => Array.from(chunk)), |
| 340 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 341 | ); |
| 342 | }, |
| 343 | { concurrency: 8 }, |
| 344 | ); |
| 345 | return groups.flat(); |
| 346 | }), |
| 347 | |
| 348 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 349 | const env = yield* GcpEnvironment.current; |
| 350 | const wireGroupName = yield* toName(id, news.wireGroupName, output?.wireGroupName); |
| 351 | const crossSiteNetwork = lastSegment(news.crossSiteNetwork ?? output?.crossSiteNetwork); |
| 352 | const ownership = yield* createInternalLabels(id); |
| 353 | const desired = toBody(wireGroupName, news, ownership); |
| 354 | |
| 355 | let current = yield* getByName(env.project, crossSiteNetwork, wireGroupName); |
| 356 | |
| 357 | if (current === undefined) { |
| 358 | const inserted = yield* compute |
| 359 | .insertWireGroups({ |
| 360 | project: env.project, |
| 361 | crossSiteNetwork, |
| 362 | body: desired, |
| 363 | }) |
| 364 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 365 | if (inserted !== undefined) { |
| 366 | yield* waitGlobalOperation(env.project, inserted, { |
| 367 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 368 | }); |
| 369 | } |
| 370 | current = yield* getByName(env.project, crossSiteNetwork, wireGroupName).pipe( |
| 371 | Effect.filterOrFail( |
| 372 | (group): group is compute.WireGroup => group !== undefined, |
| 373 | () => |
| 374 | new WireGroupNotResolved({ |
| 375 | wireGroupName, |
| 376 | crossSiteNetwork, |
| 377 | }), |
| 378 | ), |
| 379 | Effect.retry({ |
| 380 | while: (error) => error._tag === "GCP.Compute.WireGroupNotResolved", |
| 381 | times: 8, |
| 382 | schedule: Schedule.spaced("1 second"), |
| 383 | }), |
| 384 | ); |
| 385 | } |
| 386 | |
| 387 | if (current === undefined) { |
| 388 | return yield* new WireGroupNotResolved({ |
| 389 | wireGroupName, |
| 390 | crossSiteNetwork, |
| 391 | }); |
| 392 | } |
| 393 | |
| 394 | const descriptionChanged = (current.description ?? "") !== (desired.description ?? ""); |
| 395 | const adminChanged = (current.adminEnabled !== false) !== (desired.adminEnabled !== false); |
| 396 | const propertiesChanged = !sameJson(current.wireProperties, desired.wireProperties); |
| 397 | const endpointsChanged = !sameJson(current.endpoints, desired.endpoints); |
| 398 | |
| 399 | if (descriptionChanged || adminChanged || propertiesChanged || endpointsChanged) { |
| 400 | const patched = yield* compute.patchWireGroups({ |
| 401 | project: env.project, |
| 402 | crossSiteNetwork, |
| 403 | wireGroup: wireGroupName, |
| 404 | updateMask: [ |
| 405 | descriptionChanged ? "description" : undefined, |
| 406 | adminChanged ? "adminEnabled" : undefined, |
| 407 | propertiesChanged ? "wireProperties" : undefined, |
| 408 | endpointsChanged ? "endpoints" : undefined, |
| 409 | ] |
| 410 | .filter((field): field is string => field !== undefined) |
| 411 | .join(","), |
| 412 | body: desired, |
| 413 | }); |
| 414 | yield* waitGlobalOperation(env.project, patched); |
| 415 | current = (yield* getByName(env.project, crossSiteNetwork, wireGroupName)) ?? current; |
| 416 | } |
| 417 | |
| 418 | return toAttrs(current, env.project, crossSiteNetwork); |
| 419 | }), |
| 420 | |
| 421 | delete: Effect.fn(function* ({ output }) { |
| 422 | const env = yield* GcpEnvironment.current; |
| 423 | const project = output.project || env.project; |
| 424 | const crossSiteNetwork = lastSegment(output.crossSiteNetwork); |
| 425 | const deleted = yield* compute |
| 426 | .deleteWireGroups({ |
| 427 | project, |
| 428 | crossSiteNetwork, |
| 429 | wireGroup: output.wireGroupName, |
| 430 | }) |
| 431 | .pipe( |
| 432 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 433 | Effect.retry({ |
| 434 | while: (error) => error._tag === "Conflict", |
| 435 | times: 8, |
| 436 | schedule: Schedule.spaced("2 seconds"), |
| 437 | }), |
| 438 | ); |
| 439 | if (deleted !== undefined) { |
| 440 | yield* waitGlobalOperation(project, deleted, { |
| 441 | ignore: ["RESOURCE_NOT_FOUND"], |
| 442 | }); |
| 443 | } |
| 444 | yield* waitGroupGone(project, crossSiteNetwork, output.wireGroupName); |
| 445 | }), |
| 446 | }); |