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 { waitZoneOperation } from "./operations.ts"; |
| 15 | |
| 16 | const DEFAULT_ZONE = "us-central1-a"; |
| 17 | |
| 18 | export type FutureReservationTimeWindow = compute.FutureReservationTimeWindow; |
| 19 | export type FutureReservationSpecificSKUProperties = compute.FutureReservationSpecificSKUProperties; |
| 20 | export type FutureReservationCommitmentInfo = compute.FutureReservationCommitmentInfo; |
| 21 | |
| 22 | export type FutureReservationProps = { |
| 23 | /** |
| 24 | * Future reservation name (RFC1035, 1-63 chars). If omitted, a unique |
| 25 | * name is generated from the stack, stage, and logical id. Changing it |
| 26 | * replaces the reservation. |
| 27 | */ |
| 28 | futureReservationName?: string; |
| 29 | /** |
| 30 | * Zone of the reservation (e.g. `us-central1-a`). Immutable — changing |
| 31 | * it replaces the reservation. |
| 32 | * @default "us-central1-a" |
| 33 | */ |
| 34 | zone?: string; |
| 35 | /** |
| 36 | * Optional description. Future reservations have no labels field — |
| 37 | * Alchemy ownership is stored in a `[alchemy …]` prefix for `list` / |
| 38 | * nuke. |
| 39 | */ |
| 40 | description?: string; |
| 41 | /** |
| 42 | * Delivery window (`startTime` RFC3339 plus `endTime` or `duration`). |
| 43 | */ |
| 44 | timeWindow?: FutureReservationTimeWindow; |
| 45 | /** |
| 46 | * Specific SKU properties (machine type + total count). Mutually |
| 47 | * exclusive with aggregate accelerator reservations. |
| 48 | */ |
| 49 | specificSkuProperties?: FutureReservationSpecificSKUProperties; |
| 50 | /** |
| 51 | * Planning state. `DRAFT` keeps the reservation off the procurement |
| 52 | * queue; `SUBMITTED` starts evaluation. |
| 53 | * @default "DRAFT" |
| 54 | */ |
| 55 | planningStatus?: compute.FutureReservationPlanningStatusEnum | (string & {}); |
| 56 | /** |
| 57 | * Name prefix for auto-created reservations at delivery (max 20 chars). |
| 58 | */ |
| 59 | namePrefix?: string; |
| 60 | /** |
| 61 | * Existing reservation name that receives capacity at delivery. |
| 62 | */ |
| 63 | reservationName?: string; |
| 64 | /** |
| 65 | * Auto-delete auto-created reservations at end time. Compute requires this |
| 66 | * field on insert. |
| 67 | * @default false |
| 68 | */ |
| 69 | autoDeleteAutoCreatedReservations?: boolean; |
| 70 | /** |
| 71 | * Only VMs that target the reservation by name can consume it. |
| 72 | */ |
| 73 | specificReservationRequired?: boolean; |
| 74 | /** |
| 75 | * Reservation mode (`DEFAULT` or `CALENDAR`). |
| 76 | */ |
| 77 | reservationMode?: compute.FutureReservationReservationModeEnum | (string & {}); |
| 78 | /** |
| 79 | * Deployment type (`DENSE` or unspecified). |
| 80 | */ |
| 81 | deploymentType?: compute.FutureReservationDeploymentTypeEnum | (string & {}); |
| 82 | /** |
| 83 | * Maintenance scheduling (`INDEPENDENT` or `GROUPED`). |
| 84 | */ |
| 85 | schedulingType?: compute.FutureReservationSchedulingTypeEnum | (string & {}); |
| 86 | /** |
| 87 | * Commitment attached at delivery, if any. |
| 88 | */ |
| 89 | commitmentInfo?: FutureReservationCommitmentInfo; |
| 90 | }; |
| 91 | |
| 92 | export type FutureReservation = Resource< |
| 93 | "GCP.Compute.FutureReservation", |
| 94 | FutureReservationProps, |
| 95 | { |
| 96 | /** Future reservation name. */ |
| 97 | futureReservationName: string; |
| 98 | /** Project id. */ |
| 99 | project: string; |
| 100 | /** Zone short name. */ |
| 101 | zone: string; |
| 102 | /** User description with the Alchemy ownership prefix stripped. */ |
| 103 | description: string | undefined; |
| 104 | /** Delivery window. */ |
| 105 | timeWindow: FutureReservationTimeWindow | undefined; |
| 106 | /** Specific SKU properties. */ |
| 107 | specificSkuProperties: FutureReservationSpecificSKUProperties | undefined; |
| 108 | /** Planning status. */ |
| 109 | planningStatus: string | undefined; |
| 110 | /** Name prefix for auto-created reservations. */ |
| 111 | namePrefix: string | undefined; |
| 112 | /** Target reservation name. */ |
| 113 | reservationName: string | undefined; |
| 114 | /** Procurement / amendment status. */ |
| 115 | status: compute.FutureReservationStatus | undefined; |
| 116 | /** Server-assigned numeric id. */ |
| 117 | futureReservationId: string | undefined; |
| 118 | /** Server-defined URL. */ |
| 119 | selfLink: string | undefined; |
| 120 | /** RFC3339 creation timestamp. */ |
| 121 | creationTimestamp: string | undefined; |
| 122 | }, |
| 123 | never, |
| 124 | Providers |
| 125 | >; |
| 126 | |
| 127 | /** |
| 128 | * A zonal Compute Engine future reservation. |
| 129 | * |
| 130 | * Future reservations lock capacity for a later delivery window. Name and |
| 131 | * zone replace the resource; description, planning status, and the time |
| 132 | * window update in place via `futureReservations.patch`. Compute has no |
| 133 | * labels field, so Alchemy stamps ownership into the description. |
| 134 | * |
| 135 | * Creating a reservation typically requires quota and, for `CALENDAR` |
| 136 | * mode, GPU/TPU SKUs. Draft reservations (`planningStatus: "DRAFT"`) stay |
| 137 | * off the procurement queue. |
| 138 | * |
| 139 | * ### Creating a Future Reservation |
| 140 | * **Example:** Draft n2 capacity |
| 141 | * ```typescript |
| 142 | * const reservation = yield* GCP.Compute.FutureReservation("burst", { |
| 143 | * planningStatus: "DRAFT", |
| 144 | * timeWindow: { |
| 145 | * startTime: "2030-06-01T00:00:00Z", |
| 146 | * endTime: "2030-06-08T00:00:00Z", |
| 147 | * }, |
| 148 | * specificSkuProperties: { |
| 149 | * totalCount: "1", |
| 150 | * instanceProperties: { machineType: "n2-standard-2" }, |
| 151 | * }, |
| 152 | * }); |
| 153 | * ``` |
| 154 | * |
| 155 | * @resource |
| 156 | * @category Compute |
| 157 | */ |
| 158 | export const FutureReservation = Resource<FutureReservation>("GCP.Compute.FutureReservation"); |
| 159 | |
| 160 | export class FutureReservationNotResolved extends Data.TaggedError( |
| 161 | "GCP.Compute.FutureReservationNotResolved", |
| 162 | )<{ |
| 163 | futureReservationName: string; |
| 164 | zone: string; |
| 165 | }> {} |
| 166 | |
| 167 | const lastSegment = (value: string | undefined): string => { |
| 168 | if (value === undefined || value.length === 0) return ""; |
| 169 | const parts = value.replace(/\/+$/, "").split("/"); |
| 170 | return parts[parts.length - 1] || value; |
| 171 | }; |
| 172 | |
| 173 | const zoneOf = (value: string | undefined): string => lastSegment(value) || DEFAULT_ZONE; |
| 174 | |
| 175 | const rfc1035 = (name: string): string => { |
| 176 | let next = name |
| 177 | .toLowerCase() |
| 178 | .replace(/[^a-z0-9-]/g, "-") |
| 179 | .replace(/-+/g, "-") |
| 180 | .replace(/^-+/, "") |
| 181 | .replace(/-+$/, ""); |
| 182 | if (!/^[a-z]/.test(next)) { |
| 183 | next = `f${next}`; |
| 184 | } |
| 185 | next = next.slice(0, 63).replace(/-+$/, ""); |
| 186 | return next.length > 0 ? next : "futurereservation"; |
| 187 | }; |
| 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 | return rfc1035( |
| 194 | yield* createPhysicalName({ |
| 195 | id, |
| 196 | maxLength: 63, |
| 197 | lowercase: true, |
| 198 | }), |
| 199 | ); |
| 200 | }); |
| 201 | |
| 202 | const encodeDescription = ( |
| 203 | labels: Record<string, string>, |
| 204 | description: string | undefined, |
| 205 | ): string => { |
| 206 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 207 | return description ? `${marker}\n${description}` : marker; |
| 208 | }; |
| 209 | |
| 210 | const parseDescription = ( |
| 211 | description: string | undefined, |
| 212 | ): { |
| 213 | labels: Record<string, string>; |
| 214 | description: string | undefined; |
| 215 | } => { |
| 216 | if (!description?.startsWith("[alchemy ")) { |
| 217 | return { labels: {}, description }; |
| 218 | } |
| 219 | const end = description.indexOf("]"); |
| 220 | if (end < 0) return { labels: {}, description }; |
| 221 | const labels: Record<string, string> = {}; |
| 222 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 223 | const eq = part.indexOf("="); |
| 224 | if (eq > 0) { |
| 225 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 226 | } |
| 227 | } |
| 228 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 229 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 230 | }; |
| 231 | |
| 232 | const jsonOf = (value: unknown) => JSON.stringify(value ?? null); |
| 233 | |
| 234 | const toBody = ( |
| 235 | name: string, |
| 236 | props: FutureReservationProps, |
| 237 | ownership: Record<string, string>, |
| 238 | ): compute.FutureReservation => ({ |
| 239 | name, |
| 240 | description: encodeDescription(ownership, props.description), |
| 241 | timeWindow: props.timeWindow, |
| 242 | specificSkuProperties: props.specificSkuProperties, |
| 243 | planningStatus: props.planningStatus ?? "DRAFT", |
| 244 | namePrefix: props.namePrefix, |
| 245 | reservationName: props.reservationName, |
| 246 | autoDeleteAutoCreatedReservations: props.autoDeleteAutoCreatedReservations ?? false, |
| 247 | specificReservationRequired: props.specificReservationRequired, |
| 248 | reservationMode: props.reservationMode, |
| 249 | deploymentType: props.deploymentType, |
| 250 | schedulingType: props.schedulingType, |
| 251 | commitmentInfo: props.commitmentInfo, |
| 252 | }); |
| 253 | |
| 254 | const toAttrs = ( |
| 255 | reservation: compute.FutureReservation, |
| 256 | project: string, |
| 257 | ): FutureReservation["Attributes"] => { |
| 258 | const parsed = parseDescription(reservation.description); |
| 259 | return { |
| 260 | futureReservationName: reservation.name ?? reservation.id ?? "", |
| 261 | project, |
| 262 | zone: zoneOf(reservation.zone), |
| 263 | description: parsed.description, |
| 264 | timeWindow: reservation.timeWindow, |
| 265 | specificSkuProperties: reservation.specificSkuProperties, |
| 266 | planningStatus: reservation.planningStatus, |
| 267 | namePrefix: reservation.namePrefix, |
| 268 | reservationName: reservation.reservationName, |
| 269 | status: reservation.status, |
| 270 | futureReservationId: reservation.id, |
| 271 | selfLink: reservation.selfLink, |
| 272 | creationTimestamp: reservation.creationTimestamp, |
| 273 | }; |
| 274 | }; |
| 275 | |
| 276 | const needsUpdate = (current: compute.FutureReservation, desired: compute.FutureReservation) => { |
| 277 | if ((current.description ?? "") !== (desired.description ?? "")) return true; |
| 278 | if ((current.planningStatus ?? "DRAFT") !== (desired.planningStatus ?? "DRAFT")) { |
| 279 | return true; |
| 280 | } |
| 281 | if (jsonOf(current.timeWindow) !== jsonOf(desired.timeWindow)) return true; |
| 282 | if (jsonOf(current.specificSkuProperties) !== jsonOf(desired.specificSkuProperties)) { |
| 283 | return true; |
| 284 | } |
| 285 | if ((current.namePrefix ?? "") !== (desired.namePrefix ?? "")) return true; |
| 286 | if ((current.reservationName ?? "") !== (desired.reservationName ?? "")) { |
| 287 | return true; |
| 288 | } |
| 289 | if ( |
| 290 | (current.autoDeleteAutoCreatedReservations ?? false) !== |
| 291 | (desired.autoDeleteAutoCreatedReservations ?? false) |
| 292 | ) { |
| 293 | return true; |
| 294 | } |
| 295 | if ( |
| 296 | (current.specificReservationRequired ?? false) !== |
| 297 | (desired.specificReservationRequired ?? false) |
| 298 | ) { |
| 299 | return true; |
| 300 | } |
| 301 | return false; |
| 302 | }; |
| 303 | |
| 304 | const getByName = (project: string, zone: string, futureReservation: string) => |
| 305 | compute |
| 306 | .getFutureReservations({ project, zone, futureReservation }) |
| 307 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 308 | |
| 309 | const awaitResource = (project: string, zone: string, futureReservationName: string) => |
| 310 | getByName(project, zone, futureReservationName).pipe( |
| 311 | Effect.repeat({ |
| 312 | schedule: Schedule.spaced("1 second"), |
| 313 | until: (item) => item !== undefined, |
| 314 | times: 8, |
| 315 | }), |
| 316 | ); |
| 317 | |
| 318 | export const FutureReservationProvider = () => |
| 319 | Provider.succeed(FutureReservation, { |
| 320 | stables: [ |
| 321 | "futureReservationName", |
| 322 | "project", |
| 323 | "zone", |
| 324 | "futureReservationId", |
| 325 | "selfLink", |
| 326 | "creationTimestamp", |
| 327 | ], |
| 328 | |
| 329 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 330 | if (!isResolved(news)) return undefined; |
| 331 | const previousName = olds?.futureReservationName ?? output?.futureReservationName; |
| 332 | const nextName = news.futureReservationName; |
| 333 | const previousZone = zoneOf(olds?.zone ?? output?.zone); |
| 334 | const nextZone = zoneOf(news.zone ?? output?.zone); |
| 335 | if ( |
| 336 | (previousName !== undefined && nextName !== undefined && previousName !== nextName) || |
| 337 | previousZone !== nextZone |
| 338 | ) { |
| 339 | return { |
| 340 | action: "replace" as const, |
| 341 | deleteFirst: |
| 342 | previousName !== undefined && |
| 343 | nextName !== undefined && |
| 344 | previousName === nextName && |
| 345 | previousZone === nextZone, |
| 346 | }; |
| 347 | } |
| 348 | return undefined; |
| 349 | }), |
| 350 | |
| 351 | read: Effect.fn(function* ({ id, olds, output }) { |
| 352 | const env = yield* GcpEnvironment.current; |
| 353 | const futureReservationName = yield* toName( |
| 354 | id, |
| 355 | olds?.futureReservationName, |
| 356 | output?.futureReservationName, |
| 357 | ); |
| 358 | const zone = zoneOf(olds?.zone ?? output?.zone); |
| 359 | const existing = yield* getByName(env.project, zone, futureReservationName); |
| 360 | if (existing === undefined) return undefined; |
| 361 | const attrs = toAttrs(existing, env.project); |
| 362 | const { labels } = parseDescription(existing.description); |
| 363 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 364 | }), |
| 365 | |
| 366 | list: () => |
| 367 | Effect.gen(function* () { |
| 368 | const env = yield* GcpEnvironment.current; |
| 369 | const pages = yield* compute.aggregatedListFutureReservations |
| 370 | .pages({ |
| 371 | project: env.project, |
| 372 | returnPartialSuccess: true, |
| 373 | maxResults: 500, |
| 374 | }) |
| 375 | .pipe(Stream.runCollect); |
| 376 | return Array.from(pages).flatMap((page) => |
| 377 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 378 | (scoped?.futureReservations ?? []) |
| 379 | .filter((item) => { |
| 380 | const { labels } = parseDescription(item.description); |
| 381 | return Object.keys(labels).some((key) => key.startsWith("alchemy-")); |
| 382 | }) |
| 383 | .map((item) => toAttrs(item, env.project)), |
| 384 | ), |
| 385 | ); |
| 386 | }), |
| 387 | |
| 388 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 389 | const env = yield* GcpEnvironment.current; |
| 390 | const futureReservationName = yield* toName( |
| 391 | id, |
| 392 | news.futureReservationName, |
| 393 | output?.futureReservationName, |
| 394 | ); |
| 395 | const zone = zoneOf(news.zone ?? output?.zone); |
| 396 | const ownership = yield* createInternalLabels(id); |
| 397 | const desired = toBody(futureReservationName, news, ownership); |
| 398 | |
| 399 | let current = yield* getByName(env.project, zone, futureReservationName); |
| 400 | |
| 401 | if (current === undefined) { |
| 402 | yield* compute |
| 403 | .insertFutureReservations({ |
| 404 | project: env.project, |
| 405 | zone, |
| 406 | body: desired, |
| 407 | }) |
| 408 | .pipe( |
| 409 | Effect.flatMap((operation) => |
| 410 | waitZoneOperation(env.project, zone, operation, { |
| 411 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 412 | }), |
| 413 | ), |
| 414 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 415 | ); |
| 416 | current = yield* awaitResource(env.project, zone, futureReservationName); |
| 417 | } |
| 418 | |
| 419 | if (current === undefined) { |
| 420 | return yield* new FutureReservationNotResolved({ |
| 421 | futureReservationName, |
| 422 | zone, |
| 423 | }); |
| 424 | } |
| 425 | |
| 426 | if (needsUpdate(current, desired)) { |
| 427 | yield* compute |
| 428 | .updateFutureReservations({ |
| 429 | project: env.project, |
| 430 | zone, |
| 431 | futureReservation: futureReservationName, |
| 432 | body: desired, |
| 433 | }) |
| 434 | .pipe(Effect.flatMap((operation) => waitZoneOperation(env.project, zone, operation))); |
| 435 | current = yield* getByName(env.project, zone, futureReservationName); |
| 436 | if (current === undefined) { |
| 437 | return yield* new FutureReservationNotResolved({ |
| 438 | futureReservationName, |
| 439 | zone, |
| 440 | }); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | return toAttrs(current, env.project); |
| 445 | }), |
| 446 | |
| 447 | delete: Effect.fn(function* ({ output }) { |
| 448 | const env = yield* GcpEnvironment.current; |
| 449 | const zone = zoneOf(output.zone); |
| 450 | const operation = yield* compute |
| 451 | .deleteFutureReservations({ |
| 452 | project: env.project, |
| 453 | zone, |
| 454 | futureReservation: output.futureReservationName, |
| 455 | }) |
| 456 | .pipe( |
| 457 | Effect.retry({ |
| 458 | while: (error) => error._tag === "Conflict", |
| 459 | schedule: Schedule.spaced("2 seconds"), |
| 460 | times: 8, |
| 461 | }), |
| 462 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 463 | ); |
| 464 | if (operation !== undefined) { |
| 465 | yield* waitZoneOperation(env.project, zone, operation).pipe( |
| 466 | Effect.catchTag("NotFound", () => Effect.void), |
| 467 | ); |
| 468 | } |
| 469 | }), |
| 470 | }); |