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
| 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 { tagRecord } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { GcpEnvironment } from "../Environment.ts"; |
| 13 | import { |
| 14 | createInternalLabels, |
| 15 | diffLabels, |
| 16 | hasAlchemyLabels, |
| 17 | stripInternalLabels, |
| 18 | toLabels, |
| 19 | } from "../Labels.ts"; |
| 20 | import type { Providers } from "../Providers.ts"; |
| 21 | import { waitGlobalOperation } from "./operations.ts"; |
| 22 | |
| 23 | const DEFAULT_ADDRESS_TYPE = "EXTERNAL"; |
| 24 | const DEFAULT_IP_VERSION = "IPV4"; |
| 25 | const DEFAULT_NETWORK_TIER = "PREMIUM"; |
| 26 | const MAX_NAME_LENGTH = 63; |
| 27 | |
| 28 | export type GlobalAddressProps = { |
| 29 | /** |
| 30 | * Name of the address. If omitted, a unique RFC1035 name is generated |
| 31 | * from the stack, stage, and logical id. Immutable — changing it |
| 32 | * replaces the address. |
| 33 | */ |
| 34 | addressName?: string; |
| 35 | /** |
| 36 | * Optional description. Immutable — changing it replaces the address. |
| 37 | */ |
| 38 | description?: string; |
| 39 | /** |
| 40 | * Specific IP to reserve. If omitted, GCP assigns one. Immutable — |
| 41 | * changing it replaces the address. |
| 42 | */ |
| 43 | address?: string; |
| 44 | /** |
| 45 | * `EXTERNAL` (global anycast) or `INTERNAL` (VPC peering / PSC). |
| 46 | * Immutable — changing it replaces the address. |
| 47 | * @default "EXTERNAL" |
| 48 | */ |
| 49 | addressType?: compute.AddressAddressTypeEnum | (string & {}); |
| 50 | /** |
| 51 | * `IPV4` or `IPV6`. Immutable — changing it replaces the address. |
| 52 | * @default "IPV4" |
| 53 | */ |
| 54 | ipVersion?: compute.AddressIpVersionEnum | (string & {}); |
| 55 | /** |
| 56 | * Prefix length when the resource is an IP range (VPC peering / |
| 57 | * PSC). Immutable — changing it replaces the address. |
| 58 | */ |
| 59 | prefixLength?: number; |
| 60 | /** |
| 61 | * Purpose of an internal address (`VPC_PEERING`, |
| 62 | * `PRIVATE_SERVICE_CONNECT`, …). Immutable — changing it replaces |
| 63 | * the address. |
| 64 | */ |
| 65 | purpose?: compute.AddressPurposeEnum | (string & {}); |
| 66 | /** |
| 67 | * Network URL for internal addresses (`VPC_PEERING` / |
| 68 | * `PRIVATE_SERVICE_CONNECT`). Immutable — changing it replaces the |
| 69 | * address. |
| 70 | */ |
| 71 | network?: string; |
| 72 | /** |
| 73 | * Networking tier. Global external addresses are always `PREMIUM`. |
| 74 | * Immutable — changing it replaces the address. |
| 75 | * @default "PREMIUM" |
| 76 | */ |
| 77 | networkTier?: compute.AddressNetworkTierEnum | (string & {}); |
| 78 | /** |
| 79 | * Endpoint type for reserved IPv6 addresses (`VM` or `NETLB`). |
| 80 | * Immutable — changing it replaces the address. |
| 81 | */ |
| 82 | ipv6EndpointType?: compute.AddressIpv6EndpointTypeEnum | (string & {}); |
| 83 | /** |
| 84 | * User labels. Alchemy ownership labels are merged in automatically |
| 85 | * and synced via `setLabels` (labels cannot be set on insert). |
| 86 | */ |
| 87 | labels?: Record<string, string>; |
| 88 | }; |
| 89 | |
| 90 | export type GlobalAddress = Resource< |
| 91 | "GCP.Compute.GlobalAddress", |
| 92 | GlobalAddressProps, |
| 93 | { |
| 94 | /** Address name. */ |
| 95 | addressName: string; |
| 96 | /** Project id. */ |
| 97 | project: string; |
| 98 | /** Reserved IP address or start of the range. */ |
| 99 | address: string | undefined; |
| 100 | /** Server-assigned numeric id. */ |
| 101 | id: string | undefined; |
| 102 | /** Resource self-link. */ |
| 103 | selfLink: string | undefined; |
| 104 | /** `RESERVING`, `RESERVED`, or `IN_USE`. */ |
| 105 | status: string | undefined; |
| 106 | /** `EXTERNAL` or `INTERNAL`. */ |
| 107 | addressType: string | undefined; |
| 108 | /** `IPV4` or `IPV6`. */ |
| 109 | ipVersion: string | undefined; |
| 110 | /** Prefix length of an IP range, if any. */ |
| 111 | prefixLength: number | undefined; |
| 112 | /** Purpose of an internal address, if any. */ |
| 113 | purpose: string | undefined; |
| 114 | /** Network URL for internal addresses, if any. */ |
| 115 | network: string | undefined; |
| 116 | /** Networking tier. */ |
| 117 | networkTier: string | undefined; |
| 118 | /** IPv6 endpoint type, if any. */ |
| 119 | ipv6EndpointType: string | undefined; |
| 120 | /** Description. */ |
| 121 | description: string | undefined; |
| 122 | /** User labels (Alchemy ownership labels stripped). */ |
| 123 | labels: Record<string, string>; |
| 124 | /** RFC3339 creation timestamp. */ |
| 125 | creationTimestamp: string | undefined; |
| 126 | /** Self-links of resources using this address. */ |
| 127 | users: ReadonlyArray<string>; |
| 128 | }, |
| 129 | never, |
| 130 | Providers |
| 131 | >; |
| 132 | |
| 133 | /** |
| 134 | * A global Compute Engine address — a reserved anycast IP for global |
| 135 | * forwarding rules, or an internal range for VPC peering / Private |
| 136 | * Service Connect. |
| 137 | * |
| 138 | * Labels are the only in-place update. Name, IP, type, version, |
| 139 | * purpose, network, prefix length, and description replace the |
| 140 | * address. |
| 141 | * |
| 142 | * ### Creating a Global Address |
| 143 | * **Example:** Generated name |
| 144 | * ```typescript |
| 145 | * const ip = yield* GCP.Compute.GlobalAddress("FrontendIp", {}); |
| 146 | * ``` |
| 147 | * |
| 148 | * **Example:** Named address with labels |
| 149 | * ```typescript |
| 150 | * const ip = yield* GCP.Compute.GlobalAddress("FrontendIp", { |
| 151 | * addressName: "app-lb-ip", |
| 152 | * description: "Global anycast IP for the HTTPS load balancer", |
| 153 | * ipVersion: "IPV4", |
| 154 | * labels: { env: "prod" }, |
| 155 | * }); |
| 156 | * ``` |
| 157 | * |
| 158 | * ### Internal Ranges |
| 159 | * **Example:** VPC peering range |
| 160 | * ```typescript |
| 161 | * const range = yield* GCP.Compute.GlobalAddress("PsaRange", { |
| 162 | * addressType: "INTERNAL", |
| 163 | * purpose: "VPC_PEERING", |
| 164 | * network: "projects/my-project/global/networks/main", |
| 165 | * prefixLength: 16, |
| 166 | * }); |
| 167 | * ``` |
| 168 | * |
| 169 | * @resource |
| 170 | * @category Compute |
| 171 | */ |
| 172 | export const GlobalAddress = Resource<GlobalAddress>("GCP.Compute.GlobalAddress"); |
| 173 | |
| 174 | export class GlobalAddressNotResolved extends Data.TaggedError( |
| 175 | "GCP.Compute.GlobalAddressNotResolved", |
| 176 | )<{ |
| 177 | addressName: string; |
| 178 | }> {} |
| 179 | |
| 180 | export class GlobalAddressPending extends Data.TaggedError("GCP.Compute.GlobalAddressPending")<{ |
| 181 | addressName: string; |
| 182 | status: string; |
| 183 | }> {} |
| 184 | |
| 185 | const userLabels = ( |
| 186 | labels: Record<string, string | undefined> | null | undefined, |
| 187 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 188 | |
| 189 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 190 | Effect.gen(function* () { |
| 191 | if (name !== undefined) return name; |
| 192 | if (existing !== undefined) return existing; |
| 193 | const generated = yield* createPhysicalName({ |
| 194 | id, |
| 195 | maxLength: MAX_NAME_LENGTH, |
| 196 | lowercase: true, |
| 197 | }); |
| 198 | return /^[a-z]/.test(generated) ? generated : `a${generated}`.slice(0, MAX_NAME_LENGTH); |
| 199 | }); |
| 200 | |
| 201 | const toAttrs = (address: compute.Address, project: string) => ({ |
| 202 | addressName: address.name ?? "", |
| 203 | project, |
| 204 | address: address.address, |
| 205 | id: address.id, |
| 206 | selfLink: address.selfLink, |
| 207 | status: address.status, |
| 208 | addressType: address.addressType, |
| 209 | ipVersion: address.ipVersion, |
| 210 | prefixLength: address.prefixLength, |
| 211 | purpose: address.purpose, |
| 212 | network: address.network, |
| 213 | networkTier: address.networkTier, |
| 214 | ipv6EndpointType: address.ipv6EndpointType, |
| 215 | description: address.description, |
| 216 | labels: userLabels(address.labels), |
| 217 | creationTimestamp: address.creationTimestamp, |
| 218 | users: address.users ?? [], |
| 219 | }); |
| 220 | |
| 221 | const addressTypeOf = (value: string | undefined) => |
| 222 | value && value !== "UNSPECIFIED_TYPE" ? value : DEFAULT_ADDRESS_TYPE; |
| 223 | |
| 224 | const ipVersionOf = (value: string | undefined) => |
| 225 | value && value !== "UNSPECIFIED_VERSION" ? value : DEFAULT_IP_VERSION; |
| 226 | |
| 227 | const networkTierOf = (value: string | undefined) => value ?? DEFAULT_NETWORK_TIER; |
| 228 | |
| 229 | const resourceRefOf = (value: string | undefined) => { |
| 230 | if (!value) return ""; |
| 231 | const parts = value.split("/"); |
| 232 | return parts[parts.length - 1] ?? value; |
| 233 | }; |
| 234 | |
| 235 | const getByName = (project: string, address: string) => |
| 236 | compute |
| 237 | .getGlobalAddresses({ project, address }) |
| 238 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 239 | |
| 240 | const waitUntilReady = (project: string, addressName: string) => |
| 241 | getByName(project, addressName).pipe( |
| 242 | Effect.flatMap((address) => { |
| 243 | if (address === undefined || address.status === "RESERVING") { |
| 244 | return Effect.fail( |
| 245 | new GlobalAddressPending({ |
| 246 | addressName, |
| 247 | status: address?.status ?? "MISSING", |
| 248 | }), |
| 249 | ); |
| 250 | } |
| 251 | return Effect.succeed(address); |
| 252 | }), |
| 253 | Effect.retry({ |
| 254 | while: (e) => e._tag === "GCP.Compute.GlobalAddressPending", |
| 255 | times: 10, |
| 256 | schedule: Schedule.spaced("1 second"), |
| 257 | }), |
| 258 | ); |
| 259 | |
| 260 | const waitUntilGone = (project: string, addressName: string) => |
| 261 | getByName(project, addressName).pipe( |
| 262 | Effect.flatMap((address) => |
| 263 | address === undefined |
| 264 | ? Effect.void |
| 265 | : Effect.fail( |
| 266 | new GlobalAddressPending({ |
| 267 | addressName, |
| 268 | status: address.status ?? "EXISTS", |
| 269 | }), |
| 270 | ), |
| 271 | ), |
| 272 | Effect.retry({ |
| 273 | while: (e) => e._tag === "GCP.Compute.GlobalAddressPending", |
| 274 | times: 10, |
| 275 | schedule: Schedule.spaced("1 second"), |
| 276 | }), |
| 277 | Effect.catchTag("GCP.Compute.GlobalAddressPending", () => Effect.void), |
| 278 | ); |
| 279 | |
| 280 | export const GlobalAddressProvider = () => |
| 281 | Provider.succeed(GlobalAddress, { |
| 282 | stables: [ |
| 283 | "addressName", |
| 284 | "project", |
| 285 | "address", |
| 286 | "id", |
| 287 | "selfLink", |
| 288 | "addressType", |
| 289 | "ipVersion", |
| 290 | "prefixLength", |
| 291 | "purpose", |
| 292 | "network", |
| 293 | "networkTier", |
| 294 | "creationTimestamp", |
| 295 | ], |
| 296 | |
| 297 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 298 | if (!isResolved(news)) return undefined; |
| 299 | const previousName = olds.addressName ?? output?.addressName; |
| 300 | const nextName = news.addressName ?? previousName; |
| 301 | const nameChanged = |
| 302 | previousName !== undefined && nextName !== undefined && nextName !== previousName; |
| 303 | |
| 304 | const previousType = addressTypeOf(olds.addressType ?? output?.addressType); |
| 305 | const previousVersion = ipVersionOf(olds.ipVersion ?? output?.ipVersion); |
| 306 | const previousTier = networkTierOf(olds.networkTier ?? output?.networkTier); |
| 307 | const previousNetwork = resourceRefOf(olds.network ?? output?.network); |
| 308 | const previousPurpose = olds.purpose ?? output?.purpose ?? ""; |
| 309 | const previousDescription = olds.description ?? output?.description ?? ""; |
| 310 | const previousPrefix = olds.prefixLength ?? output?.prefixLength; |
| 311 | const previousIpv6 = olds.ipv6EndpointType ?? output?.ipv6EndpointType ?? ""; |
| 312 | |
| 313 | const immutableChanged = |
| 314 | (news.description !== undefined && (news.description ?? "") !== previousDescription) || |
| 315 | (news.address !== undefined && |
| 316 | output?.address !== undefined && |
| 317 | news.address !== output.address) || |
| 318 | (news.addressType !== undefined && addressTypeOf(news.addressType) !== previousType) || |
| 319 | (news.ipVersion !== undefined && ipVersionOf(news.ipVersion) !== previousVersion) || |
| 320 | (news.prefixLength !== undefined && news.prefixLength !== previousPrefix) || |
| 321 | (news.purpose !== undefined && (news.purpose ?? "") !== previousPurpose) || |
| 322 | (news.network !== undefined && resourceRefOf(news.network) !== previousNetwork) || |
| 323 | (news.networkTier !== undefined && networkTierOf(news.networkTier) !== previousTier) || |
| 324 | (news.ipv6EndpointType !== undefined && (news.ipv6EndpointType ?? "") !== previousIpv6); |
| 325 | |
| 326 | if (nameChanged) { |
| 327 | return { action: "replace" as const, deleteFirst: false }; |
| 328 | } |
| 329 | if (immutableChanged) { |
| 330 | return { action: "replace" as const, deleteFirst: true }; |
| 331 | } |
| 332 | return undefined; |
| 333 | }), |
| 334 | |
| 335 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 336 | const env = yield* GcpEnvironment.current; |
| 337 | const addressName = yield* toName(id, olds?.addressName, output?.addressName); |
| 338 | const existing = yield* getByName(env.project, addressName); |
| 339 | if (existing === undefined) return undefined; |
| 340 | const attrs = toAttrs(existing, env.project); |
| 341 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) |
| 342 | ? attrs |
| 343 | : unownedUnlessPrevious(attrs, previous, "addressName"); |
| 344 | }), |
| 345 | |
| 346 | list: () => |
| 347 | Effect.gen(function* () { |
| 348 | const env = yield* GcpEnvironment.current; |
| 349 | return yield* compute.listGlobalAddresses |
| 350 | .items({ project: env.project, maxResults: 500 }) |
| 351 | .pipe( |
| 352 | Stream.filter((address) => |
| 353 | Object.keys(address.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 354 | ), |
| 355 | Stream.map((address) => toAttrs(address, env.project)), |
| 356 | Stream.runCollect, |
| 357 | Effect.map((chunk) => Array.from(chunk)), |
| 358 | ); |
| 359 | }), |
| 360 | |
| 361 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 362 | const env = yield* GcpEnvironment.current; |
| 363 | const addressName = yield* toName(id, news.addressName, output?.addressName); |
| 364 | const desiredLabels = { |
| 365 | ...toLabels(news.labels), |
| 366 | ...(yield* createInternalLabels(id)), |
| 367 | }; |
| 368 | |
| 369 | let current = yield* getByName(env.project, addressName); |
| 370 | |
| 371 | if (current === undefined) { |
| 372 | const created = yield* compute |
| 373 | .insertGlobalAddresses({ |
| 374 | project: env.project, |
| 375 | body: { |
| 376 | name: addressName, |
| 377 | description: news.description, |
| 378 | address: news.address, |
| 379 | addressType: news.addressType, |
| 380 | ipVersion: news.ipVersion, |
| 381 | prefixLength: news.prefixLength, |
| 382 | purpose: news.purpose, |
| 383 | network: news.network, |
| 384 | networkTier: news.networkTier, |
| 385 | ipv6EndpointType: news.ipv6EndpointType, |
| 386 | }, |
| 387 | }) |
| 388 | .pipe( |
| 389 | Effect.flatMap((operation) => |
| 390 | waitGlobalOperation(env.project, operation, { |
| 391 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 392 | }).pipe(Effect.flatMap(() => getByName(env.project, addressName))), |
| 393 | ), |
| 394 | Effect.catchTag("Conflict", () => getByName(env.project, addressName)), |
| 395 | ); |
| 396 | current = created ?? undefined; |
| 397 | } |
| 398 | |
| 399 | if (current === undefined) { |
| 400 | return yield* new GlobalAddressNotResolved({ addressName }); |
| 401 | } |
| 402 | |
| 403 | if (current.status === "RESERVING") { |
| 404 | current = yield* waitUntilReady(env.project, addressName); |
| 405 | } |
| 406 | |
| 407 | const observedLabels = tagRecord(current.labels); |
| 408 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 409 | if (upsert.length > 0 || removed.length > 0) { |
| 410 | yield* compute |
| 411 | .setLabelsGlobalAddresses({ |
| 412 | project: env.project, |
| 413 | resource: addressName, |
| 414 | body: { |
| 415 | labels: desiredLabels, |
| 416 | labelFingerprint: current.labelFingerprint, |
| 417 | }, |
| 418 | }) |
| 419 | .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation))); |
| 420 | current = (yield* getByName(env.project, addressName)) ?? current; |
| 421 | } |
| 422 | |
| 423 | return toAttrs(current, env.project); |
| 424 | }), |
| 425 | |
| 426 | delete: Effect.fn(function* ({ output }) { |
| 427 | const env = yield* GcpEnvironment.current; |
| 428 | yield* compute |
| 429 | .deleteGlobalAddresses({ |
| 430 | project: env.project, |
| 431 | address: output.addressName, |
| 432 | }) |
| 433 | .pipe( |
| 434 | Effect.flatMap((operation) => |
| 435 | waitGlobalOperation(env.project, operation, { |
| 436 | ignore: ["RESOURCE_NOT_FOUND"], |
| 437 | }), |
| 438 | ), |
| 439 | Effect.catchTag("NotFound", () => Effect.void), |
| 440 | Effect.retry({ |
| 441 | while: (e) => e._tag === "Conflict", |
| 442 | times: 8, |
| 443 | schedule: Schedule.spaced("2 seconds"), |
| 444 | }), |
| 445 | ); |
| 446 | yield* waitUntilGone(env.project, output.addressName); |
| 447 | }), |
| 448 | }); |