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 { unownedUnlessPrevious } 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 { waitRegionOperation } from "./operations.ts"; |
| 16 | |
| 17 | const DEFAULT_CONNECTION_PREFERENCE = "ACCEPT_AUTOMATIC"; |
| 18 | const MAX_NAME_LENGTH = 63; |
| 19 | |
| 20 | export type NetworkAttachmentConnectionPreference = |
| 21 | | compute.NetworkAttachmentConnectionPreferenceEnum |
| 22 | | (string & {}); |
| 23 | export type NetworkAttachmentConnectedEndpoint = compute.NetworkAttachmentConnectedEndpoint; |
| 24 | |
| 25 | export type NetworkAttachmentProps = { |
| 26 | /** |
| 27 | * Attachment name (RFC1035, 1-63 characters). If omitted, a unique name |
| 28 | * is generated from the stack, stage, and logical id. Immutable — |
| 29 | * changing it replaces the attachment. |
| 30 | */ |
| 31 | networkAttachmentName?: string; |
| 32 | /** |
| 33 | * Region the attachment lives in. Immutable — changing it replaces the |
| 34 | * attachment. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 35 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 36 | */ |
| 37 | region?: string; |
| 38 | /** |
| 39 | * Subnet URLs or names the consumer provides for producer endpoints. |
| 40 | * All subnets must be in the same VPC. Required. Updated in place via |
| 41 | * `patch`. |
| 42 | */ |
| 43 | subnetworks: string[]; |
| 44 | /** |
| 45 | * How producer connections are admitted. `ACCEPT_AUTOMATIC` always |
| 46 | * accepts; `ACCEPT_MANUAL` uses the accept and reject lists. |
| 47 | * Immutable — GCP rejects `patch` of this field, so changing it |
| 48 | * replaces the attachment. |
| 49 | * @default "ACCEPT_AUTOMATIC" |
| 50 | */ |
| 51 | connectionPreference?: NetworkAttachmentConnectionPreference; |
| 52 | /** |
| 53 | * Optional description. Compute network attachments have no labels |
| 54 | * field, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` / |
| 55 | * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke. |
| 56 | * Updated in place via `patch`. |
| 57 | */ |
| 58 | description?: string; |
| 59 | /** |
| 60 | * Producer projects allowed to connect (id or number). Used with |
| 61 | * `ACCEPT_MANUAL`. Updated in place via `patch`. |
| 62 | */ |
| 63 | producerAcceptLists?: string[]; |
| 64 | /** |
| 65 | * Producer projects that must not connect. Updated in place via |
| 66 | * `patch`. |
| 67 | */ |
| 68 | producerRejectLists?: string[]; |
| 69 | }; |
| 70 | |
| 71 | export type NetworkAttachment = Resource< |
| 72 | "GCP.Compute.NetworkAttachment", |
| 73 | NetworkAttachmentProps, |
| 74 | { |
| 75 | /** Attachment name. */ |
| 76 | networkAttachmentName: string; |
| 77 | /** Project id. */ |
| 78 | project: string; |
| 79 | /** Region short name (`us-central1`). */ |
| 80 | region: string; |
| 81 | /** Parent VPC network URL. */ |
| 82 | network: string | undefined; |
| 83 | /** Consumer subnet URLs. */ |
| 84 | subnetworks: ReadonlyArray<string>; |
| 85 | /** Connection preference. */ |
| 86 | connectionPreference: string | undefined; |
| 87 | /** User description with the Alchemy ownership prefix stripped. */ |
| 88 | description: string | undefined; |
| 89 | /** Accepted producer projects. */ |
| 90 | producerAcceptLists: ReadonlyArray<string>; |
| 91 | /** Rejected producer projects. */ |
| 92 | producerRejectLists: ReadonlyArray<string>; |
| 93 | /** Connected producer endpoints. */ |
| 94 | connectionEndpoints: ReadonlyArray<NetworkAttachmentConnectedEndpoint>; |
| 95 | /** Optimistic-locking fingerprint. */ |
| 96 | fingerprint: string | undefined; |
| 97 | /** Server-assigned numeric id. */ |
| 98 | networkAttachmentId: string | undefined; |
| 99 | /** Resource self-link. */ |
| 100 | selfLink: string | undefined; |
| 101 | /** Self-link including the numeric id. */ |
| 102 | selfLinkWithId: string | undefined; |
| 103 | /** RFC3339 creation timestamp. */ |
| 104 | creationTimestamp: string | undefined; |
| 105 | /** Resource kind. */ |
| 106 | kind: string | undefined; |
| 107 | }, |
| 108 | never, |
| 109 | Providers |
| 110 | >; |
| 111 | |
| 112 | /** |
| 113 | * A regional Compute Engine Private Service Connect network attachment. |
| 114 | * |
| 115 | * A network attachment lets a producer VPC initiate connections into a |
| 116 | * consumer VPC through a PSC interface. It lists consumer subnets and |
| 117 | * admits producers either automatically or via accept/reject lists. |
| 118 | * Compute NetworkAttachment has no labels field — Alchemy ownership is |
| 119 | * stored in the description so nuke can find leaked attachments. |
| 120 | * |
| 121 | * ### Creating a Network Attachment |
| 122 | * **Example:** Generated name, automatic accept |
| 123 | * ```typescript |
| 124 | * const attachment = yield* GCP.Compute.NetworkAttachment("Consumer", { |
| 125 | * region: "us-central1", |
| 126 | * subnetworks: [subnet.selfLink], |
| 127 | * connectionPreference: "ACCEPT_AUTOMATIC", |
| 128 | * }); |
| 129 | * ``` |
| 130 | * |
| 131 | * **Example:** Manual admission |
| 132 | * ```typescript |
| 133 | * const attachment = yield* GCP.Compute.NetworkAttachment("Consumer", { |
| 134 | * networkAttachmentName: "app-na", |
| 135 | * subnetworks: [subnet.selfLink], |
| 136 | * connectionPreference: "ACCEPT_MANUAL", |
| 137 | * producerAcceptLists: ["my-producer-project"], |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * @resource |
| 142 | * @category Compute |
| 143 | */ |
| 144 | export const NetworkAttachment = Resource<NetworkAttachment>("GCP.Compute.NetworkAttachment"); |
| 145 | |
| 146 | export class NetworkAttachmentNotResolved extends Data.TaggedError( |
| 147 | "GCP.Compute.NetworkAttachmentNotResolved", |
| 148 | )<{ |
| 149 | networkAttachmentName: string; |
| 150 | region: string; |
| 151 | }> {} |
| 152 | |
| 153 | export class NetworkAttachmentStillExists extends Data.TaggedError( |
| 154 | "GCP.Compute.NetworkAttachmentStillExists", |
| 155 | )<{ |
| 156 | networkAttachmentName: string; |
| 157 | }> {} |
| 158 | |
| 159 | const lastSegment = (value: string | undefined): string => { |
| 160 | if (value === undefined || value.length === 0) return ""; |
| 161 | const trimmed = value.replace(/\/+$/, ""); |
| 162 | const parts = trimmed.split("/"); |
| 163 | return parts[parts.length - 1] || trimmed; |
| 164 | }; |
| 165 | |
| 166 | const normalizeRegion = (region: string | undefined, defaultRegion: string) => |
| 167 | lastSegment(region ?? defaultRegion).toLowerCase(); |
| 168 | |
| 169 | const rfc1035 = (name: string): string => { |
| 170 | let next = name |
| 171 | .toLowerCase() |
| 172 | .replace(/[^a-z0-9-]/g, "-") |
| 173 | .replace(/-+/g, "-") |
| 174 | .replace(/^-+/, "") |
| 175 | .replace(/-+$/, ""); |
| 176 | if (!/^[a-z]/.test(next)) next = `n${next}`; |
| 177 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 178 | return next.length > 0 ? next : "attachment"; |
| 179 | }; |
| 180 | |
| 181 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 182 | Effect.gen(function* () { |
| 183 | if (name !== undefined) return name; |
| 184 | if (existing !== undefined) return existing; |
| 185 | return rfc1035( |
| 186 | yield* createPhysicalName({ |
| 187 | id, |
| 188 | maxLength: MAX_NAME_LENGTH, |
| 189 | lowercase: true, |
| 190 | }), |
| 191 | ); |
| 192 | }); |
| 193 | |
| 194 | const encodeDescription = ( |
| 195 | labels: Record<string, string>, |
| 196 | description: string | undefined, |
| 197 | ): string => { |
| 198 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 199 | return description ? `${marker}\n${description}` : marker; |
| 200 | }; |
| 201 | |
| 202 | const parseDescription = ( |
| 203 | description: string | undefined, |
| 204 | ): { |
| 205 | labels: Record<string, string>; |
| 206 | description: string | undefined; |
| 207 | } => { |
| 208 | if (!description?.startsWith("[alchemy ")) { |
| 209 | return { labels: {}, description }; |
| 210 | } |
| 211 | const end = description.indexOf("]"); |
| 212 | if (end < 0) return { labels: {}, description }; |
| 213 | const labels: Record<string, string> = {}; |
| 214 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 215 | const eq = part.indexOf("="); |
| 216 | if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 217 | } |
| 218 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 219 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 220 | }; |
| 221 | |
| 222 | const hasOwnershipMarker = (description: string | undefined) => |
| 223 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 224 | |
| 225 | const preferenceOf = (value: string | undefined) => |
| 226 | value && value.length > 0 ? value : DEFAULT_CONNECTION_PREFERENCE; |
| 227 | |
| 228 | const toSubnetworkUrl = (project: string, region: string, value: string) => { |
| 229 | if (value.includes("/")) return value; |
| 230 | return `projects/${project}/regions/${region}/subnetworks/${value}`; |
| 231 | }; |
| 232 | |
| 233 | const refsKey = (values: ReadonlyArray<string> | undefined) => |
| 234 | [...(values ?? [])] |
| 235 | .map((value) => lastSegment(value)) |
| 236 | .filter((value) => value.length > 0) |
| 237 | .sort() |
| 238 | .join(","); |
| 239 | |
| 240 | const toAttrs = ( |
| 241 | attachment: compute.NetworkAttachment, |
| 242 | project: string, |
| 243 | fallbackName?: string, |
| 244 | ): NetworkAttachment["Attributes"] => { |
| 245 | const parsed = parseDescription(attachment.description); |
| 246 | const region = lastSegment(attachment.region).toLowerCase(); |
| 247 | const networkAttachmentName = |
| 248 | attachment.name || |
| 249 | lastSegment(attachment.selfLink) || |
| 250 | lastSegment(attachment.selfLinkWithId) || |
| 251 | fallbackName || |
| 252 | ""; |
| 253 | const selfLink = |
| 254 | attachment.selfLink && attachment.selfLink.length > 0 |
| 255 | ? attachment.selfLink |
| 256 | : networkAttachmentName.length > 0 |
| 257 | ? `https://www.googleapis.com/compute/v1/projects/${project}/regions/${region}/networkAttachments/${networkAttachmentName}` |
| 258 | : undefined; |
| 259 | return { |
| 260 | networkAttachmentName, |
| 261 | project, |
| 262 | region, |
| 263 | network: attachment.network, |
| 264 | subnetworks: attachment.subnetworks ?? [], |
| 265 | connectionPreference: attachment.connectionPreference, |
| 266 | description: parsed.description, |
| 267 | producerAcceptLists: attachment.producerAcceptLists ?? [], |
| 268 | producerRejectLists: attachment.producerRejectLists ?? [], |
| 269 | connectionEndpoints: attachment.connectionEndpoints ?? [], |
| 270 | fingerprint: attachment.fingerprint, |
| 271 | networkAttachmentId: attachment.id, |
| 272 | selfLink, |
| 273 | selfLinkWithId: attachment.selfLinkWithId ?? selfLink, |
| 274 | creationTimestamp: attachment.creationTimestamp, |
| 275 | kind: attachment.kind, |
| 276 | }; |
| 277 | }; |
| 278 | |
| 279 | const getByName = (project: string, region: string, networkAttachment: string) => |
| 280 | compute |
| 281 | .getNetworkAttachments({ project, region, networkAttachment }) |
| 282 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 283 | |
| 284 | const awaitResource = (project: string, region: string, networkAttachmentName: string) => |
| 285 | getByName(project, region, networkAttachmentName).pipe( |
| 286 | Effect.flatMap((attachment) => |
| 287 | attachment !== undefined |
| 288 | ? Effect.succeed(attachment) |
| 289 | : Effect.fail( |
| 290 | new NetworkAttachmentNotResolved({ |
| 291 | networkAttachmentName, |
| 292 | region, |
| 293 | }), |
| 294 | ), |
| 295 | ), |
| 296 | Effect.retry({ |
| 297 | while: (error) => error._tag === "GCP.Compute.NetworkAttachmentNotResolved", |
| 298 | times: 8, |
| 299 | schedule: Schedule.spaced("1 second"), |
| 300 | }), |
| 301 | ); |
| 302 | |
| 303 | const waitUntilGone = (project: string, region: string, networkAttachmentName: string) => |
| 304 | getByName(project, region, networkAttachmentName).pipe( |
| 305 | Effect.flatMap((attachment) => |
| 306 | attachment === undefined |
| 307 | ? Effect.void |
| 308 | : Effect.fail(new NetworkAttachmentStillExists({ networkAttachmentName })), |
| 309 | ), |
| 310 | Effect.retry({ |
| 311 | while: (error) => error._tag === "GCP.Compute.NetworkAttachmentStillExists", |
| 312 | times: 10, |
| 313 | schedule: Schedule.spaced("2 seconds"), |
| 314 | }), |
| 315 | Effect.catchTag("GCP.Compute.NetworkAttachmentStillExists", () => Effect.void), |
| 316 | ); |
| 317 | |
| 318 | const runOp = <E extends { readonly _tag: string }, R>( |
| 319 | project: string, |
| 320 | region: string, |
| 321 | networkAttachmentName: string, |
| 322 | start: Effect.Effect<compute.Operation, E, R>, |
| 323 | options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean }, |
| 324 | ) => |
| 325 | start.pipe( |
| 326 | Effect.flatMap((operation) => |
| 327 | waitRegionOperation(project, region, operation, { |
| 328 | ignore: ignoredCodes(options), |
| 329 | }), |
| 330 | ), |
| 331 | Effect.retry({ |
| 332 | while: (error) => error._tag === "Conflict", |
| 333 | times: 5, |
| 334 | schedule: Schedule.spaced("1 second"), |
| 335 | }), |
| 336 | ); |
| 337 | |
| 338 | export const NetworkAttachmentProvider = () => |
| 339 | Provider.succeed(NetworkAttachment, { |
| 340 | stables: [ |
| 341 | "networkAttachmentName", |
| 342 | "project", |
| 343 | "region", |
| 344 | "networkAttachmentId", |
| 345 | "selfLink", |
| 346 | "selfLinkWithId", |
| 347 | "creationTimestamp", |
| 348 | ], |
| 349 | |
| 350 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 351 | if (!isResolved(news)) return undefined; |
| 352 | const env = yield* GcpEnvironment.current; |
| 353 | const previousName = olds?.networkAttachmentName ?? output?.networkAttachmentName; |
| 354 | const nextName = news.networkAttachmentName ?? previousName; |
| 355 | const nameChanged = |
| 356 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 357 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 358 | const nextRegion = normalizeRegion(news.region ?? previousRegion, env.region); |
| 359 | const previousPreference = preferenceOf( |
| 360 | olds?.connectionPreference ?? output?.connectionPreference, |
| 361 | ); |
| 362 | const nextPreference = preferenceOf(news.connectionPreference); |
| 363 | if (nameChanged) { |
| 364 | return { action: "replace" as const, deleteFirst: false }; |
| 365 | } |
| 366 | if (previousRegion !== nextRegion || previousPreference !== nextPreference) { |
| 367 | return { action: "replace" as const, deleteFirst: true }; |
| 368 | } |
| 369 | return undefined; |
| 370 | }), |
| 371 | |
| 372 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 373 | const env = yield* GcpEnvironment.current; |
| 374 | const networkAttachmentName = yield* toName( |
| 375 | id, |
| 376 | olds?.networkAttachmentName, |
| 377 | output?.networkAttachmentName, |
| 378 | ); |
| 379 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 380 | const existing = yield* getByName(env.project, region, networkAttachmentName); |
| 381 | if (existing === undefined) return undefined; |
| 382 | const attrs = toAttrs(existing, env.project, networkAttachmentName); |
| 383 | const { labels } = parseDescription(existing.description); |
| 384 | return (yield* hasAlchemyLabels(id, labels)) |
| 385 | ? attrs |
| 386 | : unownedUnlessPrevious(attrs, previous, "networkAttachmentName"); |
| 387 | }), |
| 388 | |
| 389 | list: () => |
| 390 | Effect.gen(function* () { |
| 391 | const env = yield* GcpEnvironment.current; |
| 392 | const pages = yield* compute.aggregatedListNetworkAttachments |
| 393 | .pages({ |
| 394 | project: env.project, |
| 395 | returnPartialSuccess: true, |
| 396 | maxResults: 500, |
| 397 | }) |
| 398 | .pipe(Stream.runCollect); |
| 399 | return Array.from(pages).flatMap((page) => |
| 400 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 401 | (scoped?.networkAttachments ?? []) |
| 402 | .filter((item) => hasOwnershipMarker(item.description)) |
| 403 | .map((item) => toAttrs(item, env.project)), |
| 404 | ), |
| 405 | ); |
| 406 | }), |
| 407 | |
| 408 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 409 | const env = yield* GcpEnvironment.current; |
| 410 | const networkAttachmentName = yield* toName( |
| 411 | id, |
| 412 | news.networkAttachmentName, |
| 413 | output?.networkAttachmentName, |
| 414 | ); |
| 415 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 416 | const ownership = yield* createInternalLabels(id); |
| 417 | const desiredDescription = encodeDescription(ownership, news.description); |
| 418 | const subnetworks = news.subnetworks.map((subnet) => |
| 419 | toSubnetworkUrl(env.project, region, subnet), |
| 420 | ); |
| 421 | const connectionPreference = preferenceOf(news.connectionPreference); |
| 422 | |
| 423 | let current = yield* getByName(env.project, region, networkAttachmentName); |
| 424 | |
| 425 | if (current === undefined) { |
| 426 | yield* compute |
| 427 | .insertNetworkAttachments({ |
| 428 | project: env.project, |
| 429 | region, |
| 430 | body: { |
| 431 | name: networkAttachmentName, |
| 432 | description: desiredDescription, |
| 433 | subnetworks, |
| 434 | connectionPreference, |
| 435 | producerAcceptLists: news.producerAcceptLists, |
| 436 | producerRejectLists: news.producerRejectLists, |
| 437 | }, |
| 438 | }) |
| 439 | .pipe( |
| 440 | Effect.flatMap((operation) => |
| 441 | waitRegionOperation(env.project, region, operation, { |
| 442 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 443 | }), |
| 444 | ), |
| 445 | Effect.catchTag("Conflict", () => Effect.void), |
| 446 | ); |
| 447 | current = yield* awaitResource(env.project, region, networkAttachmentName); |
| 448 | } |
| 449 | |
| 450 | const needsPatch = |
| 451 | (current.description ?? "") !== desiredDescription || |
| 452 | refsKey(current.subnetworks) !== refsKey(subnetworks) || |
| 453 | (news.producerAcceptLists !== undefined && |
| 454 | refsKey(current.producerAcceptLists) !== refsKey(news.producerAcceptLists)) || |
| 455 | (news.producerRejectLists !== undefined && |
| 456 | refsKey(current.producerRejectLists) !== refsKey(news.producerRejectLists)); |
| 457 | |
| 458 | if (needsPatch) { |
| 459 | const latest = (yield* getByName(env.project, region, networkAttachmentName)) ?? current; |
| 460 | yield* runOp( |
| 461 | env.project, |
| 462 | region, |
| 463 | networkAttachmentName, |
| 464 | compute.patchNetworkAttachments({ |
| 465 | project: env.project, |
| 466 | region, |
| 467 | networkAttachment: networkAttachmentName, |
| 468 | body: { |
| 469 | fingerprint: latest.fingerprint, |
| 470 | description: desiredDescription, |
| 471 | subnetworks, |
| 472 | producerAcceptLists: news.producerAcceptLists ?? current.producerAcceptLists, |
| 473 | producerRejectLists: news.producerRejectLists ?? current.producerRejectLists, |
| 474 | }, |
| 475 | }), |
| 476 | ); |
| 477 | current = (yield* getByName(env.project, region, networkAttachmentName)) ?? current; |
| 478 | } |
| 479 | |
| 480 | return toAttrs(current, env.project, networkAttachmentName); |
| 481 | }), |
| 482 | |
| 483 | delete: Effect.fn(function* ({ output }) { |
| 484 | if (!output.networkAttachmentName) return; |
| 485 | const env = yield* GcpEnvironment.current; |
| 486 | const project = output.project || env.project; |
| 487 | const region = normalizeRegion(output.region, env.region); |
| 488 | yield* compute |
| 489 | .deleteNetworkAttachments({ |
| 490 | project, |
| 491 | region, |
| 492 | networkAttachment: output.networkAttachmentName, |
| 493 | }) |
| 494 | .pipe( |
| 495 | Effect.flatMap((operation) => |
| 496 | waitRegionOperation(project, region, operation, { |
| 497 | ignore: ["RESOURCE_NOT_FOUND"], |
| 498 | }), |
| 499 | ), |
| 500 | Effect.catchTag("NotFound", () => Effect.void), |
| 501 | Effect.retry({ |
| 502 | while: (error) => error._tag === "Conflict", |
| 503 | times: 8, |
| 504 | schedule: Schedule.spaced("2 seconds"), |
| 505 | }), |
| 506 | ); |
| 507 | yield* waitUntilGone(project, region, output.networkAttachmentName); |
| 508 | }), |
| 509 | }); |