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 { 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 { waitZoneOperation } from "./operations.ts"; |
| 22 | |
| 23 | export type DiskProps = { |
| 24 | /** |
| 25 | * Disk name (RFC1035, 1-63 characters). If omitted, a unique name is |
| 26 | * generated from the stack, stage, and logical id. Changing the name |
| 27 | * replaces the disk. |
| 28 | */ |
| 29 | diskName?: string; |
| 30 | /** |
| 31 | * Zone the disk lives in (e.g. `us-central1-a`). Immutable — changing it |
| 32 | * replaces the disk. |
| 33 | * @default "us-central1-a" |
| 34 | */ |
| 35 | zone?: string; |
| 36 | /** |
| 37 | * Persistent disk type (`pd-standard`, `pd-balanced`, `pd-ssd`, |
| 38 | * `pd-extreme`, `hyperdisk-balanced`, …). Immutable — changing it |
| 39 | * replaces the disk. |
| 40 | * @default "pd-standard" |
| 41 | */ |
| 42 | type?: string; |
| 43 | /** |
| 44 | * Size in GB. May only grow in place; shrinking replaces the disk. |
| 45 | * @default 10 |
| 46 | */ |
| 47 | sizeGb?: number; |
| 48 | /** |
| 49 | * Optional description. |
| 50 | */ |
| 51 | description?: string; |
| 52 | /** |
| 53 | * User labels. Alchemy ownership labels are merged in automatically. |
| 54 | */ |
| 55 | labels?: Record<string, string>; |
| 56 | /** |
| 57 | * Source image used to create the disk. Immutable — changing it replaces |
| 58 | * the disk. |
| 59 | */ |
| 60 | sourceImage?: string; |
| 61 | /** |
| 62 | * Source snapshot used to create the disk. Immutable — changing it |
| 63 | * replaces the disk. |
| 64 | */ |
| 65 | sourceSnapshot?: string; |
| 66 | /** |
| 67 | * Source disk used to create this disk. Immutable — changing it replaces |
| 68 | * the disk. |
| 69 | */ |
| 70 | sourceDisk?: string; |
| 71 | /** |
| 72 | * CPU architecture (`ARM64` or `X86_64`). Immutable — changing it |
| 73 | * replaces the disk. |
| 74 | */ |
| 75 | architecture?: string; |
| 76 | /** |
| 77 | * Physical block size in bytes (typically `4096`). Immutable — changing |
| 78 | * it replaces the disk. |
| 79 | */ |
| 80 | physicalBlockSizeBytes?: number; |
| 81 | /** |
| 82 | * Provisioned IOPS (Extreme PD / Hyperdisk). Mutable in place. |
| 83 | */ |
| 84 | provisionedIops?: number; |
| 85 | /** |
| 86 | * Provisioned throughput in MB/s (Hyperdisk). Mutable in place. |
| 87 | */ |
| 88 | provisionedThroughput?: number; |
| 89 | /** |
| 90 | * Whether confidential compute is enabled. Immutable — changing it |
| 91 | * replaces the disk. |
| 92 | */ |
| 93 | enableConfidentialCompute?: boolean; |
| 94 | }; |
| 95 | |
| 96 | export type Disk = Resource< |
| 97 | "GCP.Compute.Disk", |
| 98 | DiskProps, |
| 99 | { |
| 100 | /** Disk name. */ |
| 101 | diskName: string; |
| 102 | /** Server-assigned numeric id. */ |
| 103 | diskId: string | undefined; |
| 104 | /** Project id. */ |
| 105 | project: string; |
| 106 | /** Zone (short name, e.g. `us-central1-a`). */ |
| 107 | zone: string; |
| 108 | /** Disk type (short name, e.g. `pd-standard`). */ |
| 109 | type: string; |
| 110 | /** Size in GB. */ |
| 111 | sizeGb: number; |
| 112 | /** Server-reported status (`READY`, `CREATING`, …). */ |
| 113 | status: string | undefined; |
| 114 | /** User labels (Alchemy ownership labels stripped). */ |
| 115 | labels: Record<string, string>; |
| 116 | /** Optional description. */ |
| 117 | description: string | undefined; |
| 118 | /** Compute Engine self-link. */ |
| 119 | selfLink: string | undefined; |
| 120 | /** RFC3339 creation timestamp. */ |
| 121 | creationTimestamp: string | undefined; |
| 122 | /** Source image, if any. */ |
| 123 | sourceImage: string | undefined; |
| 124 | /** Source snapshot, if any. */ |
| 125 | sourceSnapshot: string | undefined; |
| 126 | /** Source disk, if any. */ |
| 127 | sourceDisk: string | undefined; |
| 128 | /** Attached instance URLs. */ |
| 129 | users: ReadonlyArray<string>; |
| 130 | }, |
| 131 | never, |
| 132 | Providers |
| 133 | >; |
| 134 | |
| 135 | /** |
| 136 | * A zonal Compute Engine persistent disk. |
| 137 | * |
| 138 | * Changing `zone`, `type`, `diskName`, `sourceImage`, `sourceSnapshot`, |
| 139 | * `sourceDisk`, `architecture`, `physicalBlockSizeBytes`, or |
| 140 | * `enableConfidentialCompute` replaces the disk. Growing `sizeGb` is |
| 141 | * applied in place via `disks.resize`; shrinking it replaces the disk. |
| 142 | * |
| 143 | * ### Creating a Disk |
| 144 | * **Example:** Generated name |
| 145 | * ```typescript |
| 146 | * const disk = yield* GCP.Compute.Disk("data", {}); |
| 147 | * ``` |
| 148 | * |
| 149 | * **Example:** Explicit name, type, size, and labels |
| 150 | * ```typescript |
| 151 | * const disk = yield* GCP.Compute.Disk("data", { |
| 152 | * diskName: "app-data", |
| 153 | * zone: "us-central1-a", |
| 154 | * type: "pd-balanced", |
| 155 | * sizeGb: 20, |
| 156 | * labels: { env: "prod" }, |
| 157 | * }); |
| 158 | * ``` |
| 159 | * |
| 160 | * ### Resizing a Disk |
| 161 | * **Example:** Grow in place |
| 162 | * ```typescript |
| 163 | * const disk = yield* GCP.Compute.Disk("data", { |
| 164 | * diskName: "app-data", |
| 165 | * sizeGb: 50, |
| 166 | * }); |
| 167 | * ``` |
| 168 | * |
| 169 | * @resource |
| 170 | * @category Compute |
| 171 | */ |
| 172 | export const Disk = Resource<Disk>("GCP.Compute.Disk"); |
| 173 | |
| 174 | export class DiskNotResolved extends Data.TaggedError("GCP.Compute.DiskNotResolved")<{ |
| 175 | diskName: string; |
| 176 | zone: string; |
| 177 | }> {} |
| 178 | |
| 179 | export class DiskNotReady extends Data.TaggedError("GCP.Compute.DiskNotReady")<{ |
| 180 | diskName: string; |
| 181 | status: string; |
| 182 | }> {} |
| 183 | |
| 184 | export class DiskFailed extends Data.TaggedError("GCP.Compute.DiskFailed")<{ |
| 185 | diskName: string; |
| 186 | status: string; |
| 187 | }> {} |
| 188 | |
| 189 | export class DiskStillExists extends Data.TaggedError("GCP.Compute.DiskStillExists")<{ |
| 190 | diskName: string; |
| 191 | status: string; |
| 192 | }> {} |
| 193 | |
| 194 | const DEFAULT_ZONE = "us-central1-a"; |
| 195 | const DEFAULT_TYPE = "pd-standard"; |
| 196 | const DEFAULT_SIZE_GB = 10; |
| 197 | |
| 198 | const lastSegment = (value: string | undefined): string | undefined => { |
| 199 | if (value === undefined || value.length === 0) return undefined; |
| 200 | const parts = value.split("/"); |
| 201 | return parts[parts.length - 1] || value; |
| 202 | }; |
| 203 | |
| 204 | const userLabels = ( |
| 205 | labels: Record<string, string | undefined> | null | undefined, |
| 206 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 207 | |
| 208 | const parseSizeGb = (value: string | undefined): number => { |
| 209 | const parsed = Number(value); |
| 210 | return Number.isFinite(parsed) ? parsed : 0; |
| 211 | }; |
| 212 | |
| 213 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 214 | Effect.gen(function* () { |
| 215 | if (name !== undefined) return name; |
| 216 | if (existing !== undefined) return existing; |
| 217 | const generated = yield* createPhysicalName({ |
| 218 | id, |
| 219 | maxLength: 63, |
| 220 | lowercase: true, |
| 221 | }); |
| 222 | // RFC1035: disk names must start with a letter. |
| 223 | return /^[a-z]/.test(generated) ? generated : `d${generated}`.slice(0, 63); |
| 224 | }); |
| 225 | |
| 226 | const toAttrs = (disk: compute.Disk, project: string) => ({ |
| 227 | diskName: disk.name ?? disk.id ?? "", |
| 228 | diskId: disk.id, |
| 229 | project, |
| 230 | zone: lastSegment(disk.zone) ?? DEFAULT_ZONE, |
| 231 | type: lastSegment(disk.type) ?? DEFAULT_TYPE, |
| 232 | sizeGb: parseSizeGb(disk.sizeGb), |
| 233 | status: disk.status, |
| 234 | labels: userLabels(disk.labels), |
| 235 | description: disk.description, |
| 236 | selfLink: disk.selfLink, |
| 237 | creationTimestamp: disk.creationTimestamp, |
| 238 | sourceImage: disk.sourceImage, |
| 239 | sourceSnapshot: disk.sourceSnapshot, |
| 240 | sourceDisk: disk.sourceDisk, |
| 241 | users: disk.users ?? [], |
| 242 | }); |
| 243 | |
| 244 | const getByName = (project: string, zone: string, disk: string) => |
| 245 | compute |
| 246 | .getDisks({ project, zone, disk }) |
| 247 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 248 | |
| 249 | const waitDiskReady = (project: string, zone: string, diskName: string) => |
| 250 | getByName(project, zone, diskName).pipe( |
| 251 | Effect.flatMap((disk) => |
| 252 | disk?.status === "FAILED" |
| 253 | ? Effect.fail(new DiskFailed({ diskName, status: "FAILED" })) |
| 254 | : Effect.succeed(disk), |
| 255 | ), |
| 256 | Effect.filterOrFail( |
| 257 | (disk): disk is compute.Disk => disk !== undefined && disk.status === "READY", |
| 258 | (disk) => |
| 259 | new DiskNotReady({ |
| 260 | diskName, |
| 261 | status: disk?.status ?? "MISSING", |
| 262 | }), |
| 263 | ), |
| 264 | Effect.retry({ |
| 265 | while: (error) => error._tag === "GCP.Compute.DiskNotReady", |
| 266 | times: 10, |
| 267 | schedule: Schedule.spaced("2 seconds"), |
| 268 | }), |
| 269 | ); |
| 270 | |
| 271 | const waitDiskGone = (project: string, zone: string, diskName: string) => |
| 272 | getByName(project, zone, diskName).pipe( |
| 273 | Effect.flatMap((disk) => |
| 274 | disk === undefined |
| 275 | ? Effect.void |
| 276 | : Effect.fail( |
| 277 | new DiskStillExists({ |
| 278 | diskName, |
| 279 | status: disk.status ?? "UNKNOWN", |
| 280 | }), |
| 281 | ), |
| 282 | ), |
| 283 | Effect.retry({ |
| 284 | while: (error) => error instanceof DiskStillExists, |
| 285 | times: 10, |
| 286 | schedule: Schedule.spaced("3 seconds"), |
| 287 | }), |
| 288 | ); |
| 289 | |
| 290 | const diskTypeUrl = (project: string, zone: string, type: string) => |
| 291 | `projects/${project}/zones/${zone}/diskTypes/${type}`; |
| 292 | |
| 293 | export const DiskProvider = () => |
| 294 | Provider.succeed(Disk, { |
| 295 | stables: [ |
| 296 | "diskName", |
| 297 | "diskId", |
| 298 | "project", |
| 299 | "zone", |
| 300 | "type", |
| 301 | "selfLink", |
| 302 | "creationTimestamp", |
| 303 | "sourceImage", |
| 304 | "sourceSnapshot", |
| 305 | "sourceDisk", |
| 306 | ], |
| 307 | |
| 308 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 309 | if (!isResolved(news)) return undefined; |
| 310 | |
| 311 | const previousZone = lastSegment(olds?.zone) ?? lastSegment(output?.zone) ?? DEFAULT_ZONE; |
| 312 | const nextZone = lastSegment(news.zone) ?? DEFAULT_ZONE; |
| 313 | const previousType = lastSegment(olds?.type) ?? lastSegment(output?.type) ?? DEFAULT_TYPE; |
| 314 | const nextType = lastSegment(news.type) ?? DEFAULT_TYPE; |
| 315 | const previousName = olds?.diskName ?? output?.diskName; |
| 316 | const nextName = news.diskName ?? previousName; |
| 317 | const previousSize = olds?.sizeGb ?? output?.sizeGb; |
| 318 | const nextSize = news.sizeGb ?? DEFAULT_SIZE_GB; |
| 319 | |
| 320 | const replace = |
| 321 | previousZone !== nextZone || |
| 322 | previousType !== nextType || |
| 323 | (previousName !== undefined && nextName !== undefined && previousName !== nextName) || |
| 324 | (olds?.sourceImage ?? undefined) !== (news.sourceImage ?? undefined) || |
| 325 | (olds?.sourceSnapshot ?? undefined) !== (news.sourceSnapshot ?? undefined) || |
| 326 | (olds?.sourceDisk ?? undefined) !== (news.sourceDisk ?? undefined) || |
| 327 | (olds?.architecture ?? undefined) !== (news.architecture ?? undefined) || |
| 328 | (olds?.physicalBlockSizeBytes ?? undefined) !== |
| 329 | (news.physicalBlockSizeBytes ?? undefined) || |
| 330 | (olds?.enableConfidentialCompute ?? undefined) !== |
| 331 | (news.enableConfidentialCompute ?? undefined) || |
| 332 | (previousSize !== undefined && nextSize < previousSize); |
| 333 | |
| 334 | if (!replace) return undefined; |
| 335 | return { |
| 336 | action: "replace" as const, |
| 337 | deleteFirst: |
| 338 | previousName !== undefined && nextName === previousName && previousZone === nextZone, |
| 339 | }; |
| 340 | }), |
| 341 | |
| 342 | read: Effect.fn(function* ({ id, olds, output }) { |
| 343 | const env = yield* GcpEnvironment.current; |
| 344 | const diskName = yield* toName(id, olds?.diskName, output?.diskName); |
| 345 | const zone = lastSegment(olds?.zone) ?? lastSegment(output?.zone) ?? DEFAULT_ZONE; |
| 346 | const existing = yield* getByName(env.project, zone, diskName); |
| 347 | if (existing === undefined) return undefined; |
| 348 | const attrs = toAttrs(existing, env.project); |
| 349 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 350 | }), |
| 351 | |
| 352 | list: () => |
| 353 | Effect.gen(function* () { |
| 354 | const env = yield* GcpEnvironment.current; |
| 355 | const pages = yield* compute.aggregatedListDisks |
| 356 | .pages({ |
| 357 | project: env.project, |
| 358 | filter: "labels.alchemy-id:*", |
| 359 | returnPartialSuccess: true, |
| 360 | maxResults: 500, |
| 361 | }) |
| 362 | .pipe(Stream.runCollect); |
| 363 | return Array.from(pages).flatMap((page) => |
| 364 | Object.values(page.items ?? {}).flatMap((scoped) => |
| 365 | (scoped?.disks ?? []) |
| 366 | .filter((disk) => |
| 367 | Object.keys(disk.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 368 | ) |
| 369 | .map((disk) => toAttrs(disk, env.project)), |
| 370 | ), |
| 371 | ); |
| 372 | }), |
| 373 | |
| 374 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 375 | const env = yield* GcpEnvironment.current; |
| 376 | const diskName = yield* toName(id, news.diskName, output?.diskName); |
| 377 | const zone = lastSegment(news.zone) ?? lastSegment(output?.zone) ?? DEFAULT_ZONE; |
| 378 | const diskType = lastSegment(news.type) ?? DEFAULT_TYPE; |
| 379 | const sizeGb = news.sizeGb ?? DEFAULT_SIZE_GB; |
| 380 | const desiredLabels = { |
| 381 | ...toLabels(news.labels), |
| 382 | ...(yield* createInternalLabels(id)), |
| 383 | }; |
| 384 | |
| 385 | let current = yield* getByName(env.project, zone, diskName); |
| 386 | if (current?.status === "DELETING") { |
| 387 | yield* waitDiskGone(env.project, zone, diskName); |
| 388 | current = undefined; |
| 389 | } |
| 390 | |
| 391 | if (current === undefined) { |
| 392 | const inserted = yield* compute |
| 393 | .insertDisks({ |
| 394 | project: env.project, |
| 395 | zone, |
| 396 | body: { |
| 397 | name: diskName, |
| 398 | sizeGb: String(sizeGb), |
| 399 | type: diskTypeUrl(env.project, zone, diskType), |
| 400 | description: news.description, |
| 401 | labels: desiredLabels, |
| 402 | sourceImage: news.sourceImage, |
| 403 | sourceSnapshot: news.sourceSnapshot, |
| 404 | sourceDisk: news.sourceDisk, |
| 405 | architecture: news.architecture, |
| 406 | physicalBlockSizeBytes: |
| 407 | news.physicalBlockSizeBytes !== undefined |
| 408 | ? String(news.physicalBlockSizeBytes) |
| 409 | : undefined, |
| 410 | provisionedIops: |
| 411 | news.provisionedIops !== undefined ? String(news.provisionedIops) : undefined, |
| 412 | provisionedThroughput: |
| 413 | news.provisionedThroughput !== undefined |
| 414 | ? String(news.provisionedThroughput) |
| 415 | : undefined, |
| 416 | enableConfidentialCompute: news.enableConfidentialCompute, |
| 417 | }, |
| 418 | }) |
| 419 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 420 | if (inserted !== undefined) { |
| 421 | yield* waitZoneOperation(env.project, zone, inserted, { |
| 422 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 423 | }); |
| 424 | } |
| 425 | current = yield* waitDiskReady(env.project, zone, diskName); |
| 426 | } |
| 427 | |
| 428 | if (current === undefined) { |
| 429 | return yield* new DiskNotResolved({ diskName, zone }); |
| 430 | } |
| 431 | |
| 432 | const observedSize = parseSizeGb(current.sizeGb); |
| 433 | if (sizeGb > observedSize) { |
| 434 | const resized = yield* compute.resizeDisks({ |
| 435 | project: env.project, |
| 436 | zone, |
| 437 | disk: diskName, |
| 438 | body: { sizeGb: String(sizeGb) }, |
| 439 | }); |
| 440 | yield* waitZoneOperation(env.project, zone, resized); |
| 441 | current = yield* waitDiskReady(env.project, zone, diskName); |
| 442 | } |
| 443 | |
| 444 | if (current === undefined) { |
| 445 | return yield* new DiskNotResolved({ diskName, zone }); |
| 446 | } |
| 447 | |
| 448 | const observedLabels = tagRecord(current.labels); |
| 449 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 450 | if (upsert.length > 0 || removed.length > 0) { |
| 451 | const labeled = yield* compute.setLabelsDisks({ |
| 452 | project: env.project, |
| 453 | zone, |
| 454 | resource: diskName, |
| 455 | body: { |
| 456 | labels: desiredLabels, |
| 457 | labelFingerprint: current.labelFingerprint, |
| 458 | }, |
| 459 | }); |
| 460 | yield* waitZoneOperation(env.project, zone, labeled); |
| 461 | current = yield* getByName(env.project, zone, diskName); |
| 462 | } |
| 463 | |
| 464 | if (current === undefined) { |
| 465 | return yield* new DiskNotResolved({ diskName, zone }); |
| 466 | } |
| 467 | |
| 468 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 469 | const iopsChanged = |
| 470 | news.provisionedIops !== undefined && |
| 471 | String(news.provisionedIops) !== (current.provisionedIops ?? ""); |
| 472 | const throughputChanged = |
| 473 | news.provisionedThroughput !== undefined && |
| 474 | String(news.provisionedThroughput) !== (current.provisionedThroughput ?? ""); |
| 475 | |
| 476 | if (descriptionChanged || iopsChanged || throughputChanged) { |
| 477 | const updated = yield* compute.updateDisks({ |
| 478 | project: env.project, |
| 479 | zone, |
| 480 | disk: diskName, |
| 481 | updateMask: [ |
| 482 | descriptionChanged ? "description" : undefined, |
| 483 | iopsChanged ? "provisionedIops" : undefined, |
| 484 | throughputChanged ? "provisionedThroughput" : undefined, |
| 485 | ] |
| 486 | .filter((field): field is string => field !== undefined) |
| 487 | .join(","), |
| 488 | body: { |
| 489 | description: news.description, |
| 490 | provisionedIops: |
| 491 | news.provisionedIops !== undefined ? String(news.provisionedIops) : undefined, |
| 492 | provisionedThroughput: |
| 493 | news.provisionedThroughput !== undefined |
| 494 | ? String(news.provisionedThroughput) |
| 495 | : undefined, |
| 496 | }, |
| 497 | }); |
| 498 | yield* waitZoneOperation(env.project, zone, updated); |
| 499 | current = yield* getByName(env.project, zone, diskName); |
| 500 | } |
| 501 | |
| 502 | if (current === undefined) { |
| 503 | return yield* new DiskNotResolved({ diskName, zone }); |
| 504 | } |
| 505 | |
| 506 | return toAttrs(current, env.project); |
| 507 | }), |
| 508 | |
| 509 | delete: Effect.fn(function* ({ output }) { |
| 510 | const deleted = yield* compute |
| 511 | .deleteDisks({ |
| 512 | project: output.project, |
| 513 | zone: output.zone, |
| 514 | disk: output.diskName, |
| 515 | }) |
| 516 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 517 | if (deleted !== undefined) { |
| 518 | yield* waitZoneOperation(output.project, output.zone, deleted, { |
| 519 | ignore: ["RESOURCE_NOT_FOUND"], |
| 520 | }); |
| 521 | } |
| 522 | yield* waitDiskGone(output.project, output.zone, output.diskName); |
| 523 | }), |
| 524 | }); |