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 { waitGlobalOperation } from "./operations.ts"; |
| 16 | |
| 17 | const MAX_NAME_LENGTH = 63; |
| 18 | |
| 19 | export type LicenseDuration = compute.Duration; |
| 20 | export type LicenseResourceRequirements = compute.LicenseResourceRequirements; |
| 21 | |
| 22 | export type LicenseProps = { |
| 23 | /** |
| 24 | * License name (RFC1035, 1-63 characters). If omitted, a unique name is |
| 25 | * generated from the stack, stage, and logical id. Immutable — changing |
| 26 | * it replaces the license. |
| 27 | */ |
| 28 | licenseName?: string; |
| 29 | /** |
| 30 | * Optional description. Compute licenses have no labels field, so |
| 31 | * Alchemy ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) |
| 32 | * is stored in a `[alchemy …]` prefix for `list` / nuke. Immutable — |
| 33 | * `licenses.update` rejects it, so changing it replaces the license. |
| 34 | */ |
| 35 | description?: string; |
| 36 | /** |
| 37 | * When `true`, this is an OS license. Only one OS license can be |
| 38 | * attached to a disk or image. Immutable — changing it replaces the |
| 39 | * license. |
| 40 | * @default false |
| 41 | */ |
| 42 | osLicense?: boolean; |
| 43 | /** |
| 44 | * When `false`, licenses are not copied from the source when creating |
| 45 | * an image from a disk (or disk from snapshot, snapshot from disk). |
| 46 | * Immutable — changing it replaces the license. |
| 47 | * @default true |
| 48 | */ |
| 49 | transferable?: boolean; |
| 50 | /** |
| 51 | * When `true`, this license can be appended to an existing disk. |
| 52 | */ |
| 53 | appendableToDisk?: boolean; |
| 54 | /** |
| 55 | * When `true`, this license can be removed from a disk with no |
| 56 | * replacement license. |
| 57 | */ |
| 58 | removableFromDisk?: boolean; |
| 59 | /** |
| 60 | * When `true`, this license can only be used on multi-tenant nodes. |
| 61 | * Immutable — changing it replaces the license. |
| 62 | */ |
| 63 | multiTenantOnly?: boolean; |
| 64 | /** |
| 65 | * When `true`, this license can only be used on sole-tenant nodes. |
| 66 | * Immutable — changing it replaces the license. |
| 67 | */ |
| 68 | soleTenantOnly?: boolean; |
| 69 | /** |
| 70 | * Minimum time this license must stay attached once applied. |
| 71 | */ |
| 72 | minimumRetention?: LicenseDuration; |
| 73 | /** |
| 74 | * License codes that are incompatible with this license. Immutable — |
| 75 | * changing it replaces the license. |
| 76 | */ |
| 77 | incompatibleLicenses?: string[]; |
| 78 | /** |
| 79 | * License codes that can replace this license. |
| 80 | */ |
| 81 | allowedReplacementLicenses?: string[]; |
| 82 | /** |
| 83 | * License codes that must be co-attached with this license. |
| 84 | */ |
| 85 | requiredCoattachedLicenses?: string[]; |
| 86 | /** |
| 87 | * Deprecated resource-requirement hints (cores, ram). |
| 88 | */ |
| 89 | resourceRequirements?: LicenseResourceRequirements; |
| 90 | }; |
| 91 | |
| 92 | export type License = Resource< |
| 93 | "GCP.Compute.License", |
| 94 | LicenseProps, |
| 95 | { |
| 96 | /** License name. */ |
| 97 | licenseName: string; |
| 98 | /** Project id. */ |
| 99 | project: string; |
| 100 | /** User description with the Alchemy ownership prefix stripped. */ |
| 101 | description: string | undefined; |
| 102 | /** Unique code used to attach this license to images and disks. */ |
| 103 | licenseCode: string | undefined; |
| 104 | /** Whether this is an OS license. */ |
| 105 | osLicense: boolean; |
| 106 | /** Whether the license is copied from source resources. */ |
| 107 | transferable: boolean; |
| 108 | /** Whether the license can be appended to an existing disk. */ |
| 109 | appendableToDisk: boolean; |
| 110 | /** Whether the license can be removed from a disk. */ |
| 111 | removableFromDisk: boolean; |
| 112 | /** Whether the license is multi-tenant only. */ |
| 113 | multiTenantOnly: boolean; |
| 114 | /** Whether the license is sole-tenant only. */ |
| 115 | soleTenantOnly: boolean; |
| 116 | /** Minimum retention period. */ |
| 117 | minimumRetention: LicenseDuration | undefined; |
| 118 | /** Incompatible license codes. */ |
| 119 | incompatibleLicenses: ReadonlyArray<string>; |
| 120 | /** Replacement license codes. */ |
| 121 | allowedReplacementLicenses: ReadonlyArray<string>; |
| 122 | /** Required co-attached license codes. */ |
| 123 | requiredCoattachedLicenses: ReadonlyArray<string>; |
| 124 | /** Deprecated resource requirements. */ |
| 125 | resourceRequirements: LicenseResourceRequirements | undefined; |
| 126 | /** Server-assigned numeric id. */ |
| 127 | licenseId: string | undefined; |
| 128 | /** Resource self-link. */ |
| 129 | selfLink: string | undefined; |
| 130 | /** Self-link including the numeric id. */ |
| 131 | selfLinkWithId: string | undefined; |
| 132 | /** RFC3339 creation timestamp. */ |
| 133 | creationTimestamp: string | undefined; |
| 134 | /** RFC3339 last-update timestamp. */ |
| 135 | updateTimestamp: string | undefined; |
| 136 | /** Resource kind. */ |
| 137 | kind: string | undefined; |
| 138 | }, |
| 139 | never, |
| 140 | Providers |
| 141 | >; |
| 142 | |
| 143 | /** |
| 144 | * A global Compute Engine License. |
| 145 | * |
| 146 | * Licenses are intended for third-party partners who publish Cloud |
| 147 | * Marketplace images. Name and `osLicense` are immutable. Description and |
| 148 | * the attachability flags update in place via `licenses.update`. Compute |
| 149 | * License has no labels field — Alchemy stamps ownership into the |
| 150 | * description so nuke can find leaked licenses. |
| 151 | * |
| 152 | * ### Creating a License |
| 153 | * **Example:** Generated name |
| 154 | * ```typescript |
| 155 | * const license = yield* GCP.Compute.License("ImageLicense", { |
| 156 | * description: "marketplace os", |
| 157 | * transferable: true, |
| 158 | * }); |
| 159 | * ``` |
| 160 | * |
| 161 | * **Example:** Named OS license |
| 162 | * ```typescript |
| 163 | * const license = yield* GCP.Compute.License("ImageLicense", { |
| 164 | * licenseName: "app-os", |
| 165 | * osLicense: true, |
| 166 | * transferable: false, |
| 167 | * removableFromDisk: false, |
| 168 | * }); |
| 169 | * ``` |
| 170 | * |
| 171 | * @resource |
| 172 | * @category Compute |
| 173 | */ |
| 174 | export const License = Resource<License>("GCP.Compute.License"); |
| 175 | |
| 176 | export class LicenseNotResolved extends Data.TaggedError("GCP.Compute.LicenseNotResolved")<{ |
| 177 | licenseName: string; |
| 178 | }> {} |
| 179 | |
| 180 | export class LicenseStillExists extends Data.TaggedError("GCP.Compute.LicenseStillExists")<{ |
| 181 | licenseName: string; |
| 182 | }> {} |
| 183 | |
| 184 | const lastSegment = (value: string | undefined): string => { |
| 185 | if (value === undefined || value.length === 0) return ""; |
| 186 | const trimmed = value.replace(/\/+$/, ""); |
| 187 | const parts = trimmed.split("/"); |
| 188 | return parts[parts.length - 1] || trimmed; |
| 189 | }; |
| 190 | |
| 191 | const rfc1035 = (name: string): string => { |
| 192 | let next = name |
| 193 | .toLowerCase() |
| 194 | .replace(/[^a-z0-9-]/g, "-") |
| 195 | .replace(/-+/g, "-") |
| 196 | .replace(/^-+/, "") |
| 197 | .replace(/-+$/, ""); |
| 198 | if (!/^[a-z]/.test(next)) next = `l${next}`; |
| 199 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 200 | return next.length > 0 ? next : "license"; |
| 201 | }; |
| 202 | |
| 203 | const toName = (id: string, name: string | undefined, existing?: string) => |
| 204 | Effect.gen(function* () { |
| 205 | if (name !== undefined) return name; |
| 206 | if (existing !== undefined) return existing; |
| 207 | return rfc1035( |
| 208 | yield* createPhysicalName({ |
| 209 | id, |
| 210 | maxLength: MAX_NAME_LENGTH, |
| 211 | lowercase: true, |
| 212 | }), |
| 213 | ); |
| 214 | }); |
| 215 | |
| 216 | const encodeDescription = ( |
| 217 | labels: Record<string, string>, |
| 218 | description: string | undefined, |
| 219 | ): string => { |
| 220 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 221 | return description ? `${marker}\n${description}` : marker; |
| 222 | }; |
| 223 | |
| 224 | const parseDescription = ( |
| 225 | description: string | undefined, |
| 226 | ): { |
| 227 | labels: Record<string, string>; |
| 228 | description: string | undefined; |
| 229 | } => { |
| 230 | if (!description?.startsWith("[alchemy ")) { |
| 231 | return { labels: {}, description }; |
| 232 | } |
| 233 | const end = description.indexOf("]"); |
| 234 | if (end < 0) return { labels: {}, description }; |
| 235 | const labels: Record<string, string> = {}; |
| 236 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 237 | const eq = part.indexOf("="); |
| 238 | if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 239 | } |
| 240 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 241 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 242 | }; |
| 243 | |
| 244 | const hasOwnershipMarker = (description: string | undefined) => |
| 245 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 246 | |
| 247 | const sorted = (values: ReadonlyArray<string> | undefined) => |
| 248 | [...(values ?? [])].map((value) => lastSegment(value)).sort(); |
| 249 | |
| 250 | const sameJson = (left: unknown, right: unknown) => |
| 251 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 252 | |
| 253 | const immutableChanged = (olds: LicenseProps, news: LicenseProps) => |
| 254 | (olds.description ?? "") !== (news.description ?? "") || |
| 255 | (olds.transferable ?? true) !== (news.transferable ?? true) || |
| 256 | (olds.multiTenantOnly ?? false) !== (news.multiTenantOnly ?? false) || |
| 257 | (olds.soleTenantOnly ?? false) !== (news.soleTenantOnly ?? false) || |
| 258 | sorted(olds.incompatibleLicenses).join(",") !== sorted(news.incompatibleLicenses).join(",") || |
| 259 | sorted(olds.requiredCoattachedLicenses).join(",") !== |
| 260 | sorted(news.requiredCoattachedLicenses).join(","); |
| 261 | |
| 262 | const toAttrs = (license: compute.License, project: string): License["Attributes"] => { |
| 263 | const parsed = parseDescription(license.description); |
| 264 | return { |
| 265 | licenseName: license.name ?? "", |
| 266 | project, |
| 267 | description: parsed.description, |
| 268 | licenseCode: license.licenseCode, |
| 269 | osLicense: license.osLicense === true, |
| 270 | transferable: license.transferable !== false, |
| 271 | appendableToDisk: license.appendableToDisk === true, |
| 272 | removableFromDisk: license.removableFromDisk === true, |
| 273 | multiTenantOnly: license.multiTenantOnly === true, |
| 274 | soleTenantOnly: license.soleTenantOnly === true, |
| 275 | minimumRetention: license.minimumRetention, |
| 276 | incompatibleLicenses: license.incompatibleLicenses ?? [], |
| 277 | allowedReplacementLicenses: license.allowedReplacementLicenses ?? [], |
| 278 | requiredCoattachedLicenses: license.requiredCoattachedLicenses ?? [], |
| 279 | resourceRequirements: license.resourceRequirements, |
| 280 | licenseId: license.id, |
| 281 | selfLink: license.selfLink, |
| 282 | selfLinkWithId: license.selfLinkWithId, |
| 283 | creationTimestamp: license.creationTimestamp, |
| 284 | updateTimestamp: license.updateTimestamp, |
| 285 | kind: license.kind, |
| 286 | }; |
| 287 | }; |
| 288 | |
| 289 | const getByName = (project: string, license: string) => |
| 290 | compute |
| 291 | .getLicenses({ project, license }) |
| 292 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 293 | |
| 294 | const awaitResource = (project: string, licenseName: string) => |
| 295 | getByName(project, licenseName).pipe( |
| 296 | Effect.flatMap((license) => |
| 297 | license !== undefined |
| 298 | ? Effect.succeed(license) |
| 299 | : Effect.fail(new LicenseNotResolved({ licenseName })), |
| 300 | ), |
| 301 | Effect.retry({ |
| 302 | while: (error) => error._tag === "GCP.Compute.LicenseNotResolved", |
| 303 | times: 8, |
| 304 | schedule: Schedule.spaced("1 second"), |
| 305 | }), |
| 306 | ); |
| 307 | |
| 308 | const waitUntilGone = (project: string, licenseName: string) => |
| 309 | getByName(project, licenseName).pipe( |
| 310 | Effect.flatMap((license) => |
| 311 | license === undefined ? Effect.void : Effect.fail(new LicenseStillExists({ licenseName })), |
| 312 | ), |
| 313 | Effect.retry({ |
| 314 | while: (error) => error._tag === "GCP.Compute.LicenseStillExists", |
| 315 | times: 10, |
| 316 | schedule: Schedule.spaced("1 second"), |
| 317 | }), |
| 318 | Effect.catchTag("GCP.Compute.LicenseStillExists", () => Effect.void), |
| 319 | ); |
| 320 | |
| 321 | const runOp = <E extends { readonly _tag: string }, R>( |
| 322 | project: string, |
| 323 | licenseName: string, |
| 324 | start: Effect.Effect<compute.Operation, E, R>, |
| 325 | options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean }, |
| 326 | ) => |
| 327 | start.pipe( |
| 328 | Effect.flatMap((operation) => |
| 329 | waitGlobalOperation(project, operation, { |
| 330 | ignore: ignoredCodes(options), |
| 331 | }), |
| 332 | ), |
| 333 | Effect.retry({ |
| 334 | while: (error) => error._tag === "Conflict", |
| 335 | times: 5, |
| 336 | schedule: Schedule.spaced("1 second"), |
| 337 | }), |
| 338 | ); |
| 339 | |
| 340 | const insertBody = ( |
| 341 | licenseName: string, |
| 342 | news: LicenseProps, |
| 343 | description: string, |
| 344 | ): compute.License => ({ |
| 345 | name: licenseName, |
| 346 | description, |
| 347 | osLicense: news.osLicense === true ? true : undefined, |
| 348 | transferable: news.transferable, |
| 349 | appendableToDisk: news.appendableToDisk, |
| 350 | removableFromDisk: news.removableFromDisk, |
| 351 | multiTenantOnly: news.multiTenantOnly, |
| 352 | soleTenantOnly: news.soleTenantOnly, |
| 353 | minimumRetention: news.minimumRetention, |
| 354 | incompatibleLicenses: news.incompatibleLicenses, |
| 355 | allowedReplacementLicenses: news.allowedReplacementLicenses, |
| 356 | requiredCoattachedLicenses: news.requiredCoattachedLicenses, |
| 357 | resourceRequirements: news.resourceRequirements, |
| 358 | }); |
| 359 | |
| 360 | export const LicenseProvider = () => |
| 361 | Provider.succeed(License, { |
| 362 | stables: [ |
| 363 | "licenseName", |
| 364 | "project", |
| 365 | "licenseId", |
| 366 | "licenseCode", |
| 367 | "osLicense", |
| 368 | "selfLink", |
| 369 | "selfLinkWithId", |
| 370 | "creationTimestamp", |
| 371 | ], |
| 372 | |
| 373 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 374 | if (!isResolved(news)) return undefined; |
| 375 | const previousName = olds?.licenseName ?? output?.licenseName; |
| 376 | const nextName = news.licenseName ?? previousName; |
| 377 | const nameChanged = |
| 378 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 379 | const previousOs = olds?.osLicense ?? output?.osLicense ?? false; |
| 380 | const nextOs = news.osLicense ?? previousOs; |
| 381 | if (nameChanged) { |
| 382 | return { action: "replace" as const, deleteFirst: false }; |
| 383 | } |
| 384 | if (previousOs !== nextOs) { |
| 385 | return { action: "replace" as const, deleteFirst: true }; |
| 386 | } |
| 387 | // `licenses.update` only accepts appendableToDisk, removableFromDisk, |
| 388 | // allowedReplacementLicenses, and minimumRetention; every other field |
| 389 | // is fixed at insert. |
| 390 | if (olds !== undefined && immutableChanged(olds, news)) { |
| 391 | return { |
| 392 | action: "replace" as const, |
| 393 | deleteFirst: news.licenseName !== undefined, |
| 394 | }; |
| 395 | } |
| 396 | return undefined; |
| 397 | }), |
| 398 | |
| 399 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 400 | const env = yield* GcpEnvironment.current; |
| 401 | const licenseName = yield* toName(id, olds?.licenseName, output?.licenseName); |
| 402 | const existing = yield* getByName(env.project, licenseName); |
| 403 | if (existing === undefined) return undefined; |
| 404 | const attrs = toAttrs(existing, env.project); |
| 405 | const { labels } = parseDescription(existing.description); |
| 406 | return (yield* hasAlchemyLabels(id, labels)) |
| 407 | ? attrs |
| 408 | : unownedUnlessPrevious(attrs, previous, "licenseName"); |
| 409 | }), |
| 410 | |
| 411 | list: () => |
| 412 | Effect.gen(function* () { |
| 413 | const env = yield* GcpEnvironment.current; |
| 414 | return yield* compute.listLicenses |
| 415 | .items({ |
| 416 | project: env.project, |
| 417 | maxResults: 500, |
| 418 | }) |
| 419 | .pipe( |
| 420 | Stream.filter((license) => hasOwnershipMarker(license.description)), |
| 421 | Stream.map((license) => toAttrs(license, env.project)), |
| 422 | Stream.runCollect, |
| 423 | Effect.map((items) => Array.from(items)), |
| 424 | Effect.catchTag("NotFound", () => Effect.succeed([] as License["Attributes"][])), |
| 425 | ); |
| 426 | }), |
| 427 | |
| 428 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 429 | const env = yield* GcpEnvironment.current; |
| 430 | const licenseName = yield* toName(id, news.licenseName, output?.licenseName); |
| 431 | const ownership = yield* createInternalLabels(id); |
| 432 | const desiredDescription = encodeDescription(ownership, news.description); |
| 433 | |
| 434 | let current = yield* getByName(env.project, licenseName); |
| 435 | |
| 436 | if (current === undefined) { |
| 437 | yield* compute |
| 438 | .insertLicenses({ |
| 439 | project: env.project, |
| 440 | body: insertBody(licenseName, news, desiredDescription), |
| 441 | }) |
| 442 | .pipe( |
| 443 | Effect.flatMap((operation) => |
| 444 | waitGlobalOperation(env.project, operation, { |
| 445 | ignore: ["RESOURCE_ALREADY_EXISTS"], |
| 446 | }), |
| 447 | ), |
| 448 | Effect.catchTag("Conflict", () => Effect.void), |
| 449 | ); |
| 450 | current = yield* awaitResource(env.project, licenseName); |
| 451 | } |
| 452 | |
| 453 | const appendable = news.appendableToDisk ?? current.appendableToDisk === true; |
| 454 | const removable = news.removableFromDisk ?? current.removableFromDisk === true; |
| 455 | const updateMask = [ |
| 456 | (current.appendableToDisk === true) !== appendable && "appendableToDisk", |
| 457 | (current.removableFromDisk === true) !== removable && "removableFromDisk", |
| 458 | news.allowedReplacementLicenses !== undefined && |
| 459 | sorted(current.allowedReplacementLicenses).join(",") !== |
| 460 | sorted(news.allowedReplacementLicenses).join(",") && |
| 461 | "allowedReplacementLicenses", |
| 462 | news.minimumRetention !== undefined && |
| 463 | !sameJson(current.minimumRetention, news.minimumRetention) && |
| 464 | "minimumRetention", |
| 465 | ].filter((field): field is string => typeof field === "string"); |
| 466 | |
| 467 | if (updateMask.length > 0) { |
| 468 | yield* runOp( |
| 469 | env.project, |
| 470 | licenseName, |
| 471 | compute.updateLicenses({ |
| 472 | project: env.project, |
| 473 | license: licenseName, |
| 474 | updateMask: updateMask.join(","), |
| 475 | body: { |
| 476 | appendableToDisk: appendable, |
| 477 | removableFromDisk: removable, |
| 478 | allowedReplacementLicenses: |
| 479 | news.allowedReplacementLicenses ?? current.allowedReplacementLicenses, |
| 480 | minimumRetention: news.minimumRetention ?? current.minimumRetention, |
| 481 | }, |
| 482 | }), |
| 483 | ); |
| 484 | current = (yield* getByName(env.project, licenseName)) ?? current; |
| 485 | } |
| 486 | |
| 487 | return toAttrs(current, env.project); |
| 488 | }), |
| 489 | |
| 490 | delete: Effect.fn(function* ({ output }) { |
| 491 | if (!output.licenseName) return; |
| 492 | const env = yield* GcpEnvironment.current; |
| 493 | const project = output.project || env.project; |
| 494 | yield* compute |
| 495 | .deleteLicenses({ |
| 496 | project, |
| 497 | license: output.licenseName, |
| 498 | }) |
| 499 | .pipe( |
| 500 | Effect.flatMap((operation) => |
| 501 | waitGlobalOperation(project, operation, { |
| 502 | ignore: ["RESOURCE_NOT_FOUND"], |
| 503 | }), |
| 504 | ), |
| 505 | Effect.catchTag("NotFound", () => Effect.void), |
| 506 | Effect.retry({ |
| 507 | while: (error) => error._tag === "Conflict", |
| 508 | times: 8, |
| 509 | schedule: Schedule.spaced("2 seconds"), |
| 510 | }), |
| 511 | ); |
| 512 | yield* waitUntilGone(project, output.licenseName); |
| 513 | }), |
| 514 | }); |