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 { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { tagRecord } from "alchemy/Tags"; |
| 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 { |
| 13 | createInternalLabels, |
| 14 | hasAlchemyLabels, |
| 15 | stripInternalLabels, |
| 16 | toLabels, |
| 17 | } from "../Labels.ts"; |
| 18 | import type { Providers } from "../Providers.ts"; |
| 19 | import type { |
| 20 | InstanceTemplateAccessConfig, |
| 21 | InstanceTemplateDisk, |
| 22 | InstanceTemplateNetworkInterface, |
| 23 | InstanceTemplateScheduling, |
| 24 | InstanceTemplateServiceAccount, |
| 25 | } from "./InstanceTemplate.ts"; |
| 26 | import { lastSegment, normalizeRegion, runRegionOp, sameJson, toPhysicalName } from "./internal.ts"; |
| 27 | |
| 28 | const DEFAULT_MACHINE_TYPE = "e2-micro"; |
| 29 | const DEFAULT_SOURCE_IMAGE = "projects/debian-cloud/global/images/family/debian-12"; |
| 30 | const DEFAULT_DISK_SIZE_GB = "10"; |
| 31 | const DEFAULT_NETWORK = "global/networks/default"; |
| 32 | |
| 33 | export type RegionInstanceTemplateAccessConfig = InstanceTemplateAccessConfig; |
| 34 | export type RegionInstanceTemplateDisk = InstanceTemplateDisk; |
| 35 | export type RegionInstanceTemplateNetworkInterface = InstanceTemplateNetworkInterface; |
| 36 | export type RegionInstanceTemplateServiceAccount = InstanceTemplateServiceAccount; |
| 37 | export type RegionInstanceTemplateScheduling = InstanceTemplateScheduling; |
| 38 | |
| 39 | export type RegionInstanceTemplateProps = { |
| 40 | /** |
| 41 | * Template name. If omitted, a unique RFC1035 name is generated from the |
| 42 | * stack, stage, and logical id. Changing it replaces the template. |
| 43 | */ |
| 44 | templateName?: string; |
| 45 | /** |
| 46 | * Region the template lives in. Immutable — changing it replaces the |
| 47 | * template. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 48 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 49 | */ |
| 50 | region?: string; |
| 51 | /** |
| 52 | * Optional description. Changing it replaces the template. |
| 53 | */ |
| 54 | description?: string; |
| 55 | /** |
| 56 | * Machine type name (not a URL), e.g. `e2-micro`. Regional instance |
| 57 | * templates are immutable — changing this replaces the template. |
| 58 | * @default "e2-micro" |
| 59 | */ |
| 60 | machineType?: string; |
| 61 | /** |
| 62 | * Allow sending/receiving packets with non-instance IPs. |
| 63 | * @default false |
| 64 | */ |
| 65 | canIpForward?: boolean; |
| 66 | /** |
| 67 | * Labels applied to instances created from this template. Alchemy |
| 68 | * ownership labels are merged in automatically. Changing labels replaces |
| 69 | * the template (no in-place update API). |
| 70 | */ |
| 71 | labels?: Record<string, string>; |
| 72 | /** |
| 73 | * Network tags applied to instances created from this template. |
| 74 | */ |
| 75 | networkTags?: string[]; |
| 76 | /** |
| 77 | * Instance metadata key/value pairs. |
| 78 | */ |
| 79 | metadata?: Record<string, string>; |
| 80 | /** |
| 81 | * Attached disks. If omitted, a 10 GB Debian 12 boot disk is used. |
| 82 | */ |
| 83 | disks?: RegionInstanceTemplateDisk[]; |
| 84 | /** |
| 85 | * Network interfaces. |
| 86 | * @default [{ network: "global/networks/default" }] |
| 87 | */ |
| 88 | networkInterfaces?: RegionInstanceTemplateNetworkInterface[]; |
| 89 | /** |
| 90 | * Service accounts and scopes for created instances. |
| 91 | */ |
| 92 | serviceAccounts?: RegionInstanceTemplateServiceAccount[]; |
| 93 | /** |
| 94 | * Scheduling options for created instances. |
| 95 | */ |
| 96 | scheduling?: RegionInstanceTemplateScheduling; |
| 97 | }; |
| 98 | |
| 99 | export type RegionInstanceTemplate = Resource< |
| 100 | "GCP.Compute.RegionInstanceTemplate", |
| 101 | RegionInstanceTemplateProps, |
| 102 | { |
| 103 | /** Template name. */ |
| 104 | templateName: string; |
| 105 | /** Project id. */ |
| 106 | project: string; |
| 107 | /** Region short name (`us-central1`). */ |
| 108 | region: string; |
| 109 | /** Description. */ |
| 110 | description: string | undefined; |
| 111 | /** Machine type name. */ |
| 112 | machineType: string | undefined; |
| 113 | /** User labels (Alchemy ownership labels stripped). */ |
| 114 | labels: Record<string, string>; |
| 115 | /** Network tags. */ |
| 116 | networkTags: string[]; |
| 117 | /** Whether IP forwarding is enabled. */ |
| 118 | canIpForward: boolean; |
| 119 | /** Boot-disk source image, if set. */ |
| 120 | sourceImage: string | undefined; |
| 121 | /** Server-defined URL. */ |
| 122 | selfLink: string | undefined; |
| 123 | /** Server-assigned numeric id. */ |
| 124 | templateId: string | undefined; |
| 125 | /** RFC3339 creation timestamp. */ |
| 126 | creationTimestamp: string | undefined; |
| 127 | }, |
| 128 | never, |
| 129 | Providers |
| 130 | >; |
| 131 | |
| 132 | /** |
| 133 | * A regional Compute Engine instance template. |
| 134 | * |
| 135 | * Regional instance templates are immutable. Changing machine type, disks, |
| 136 | * labels, network interfaces, or other properties replaces the template. |
| 137 | * Use the template to create regional managed instance groups. |
| 138 | * |
| 139 | * ### Creating a Regional Template |
| 140 | * **Example:** Generated name with defaults |
| 141 | * ```typescript |
| 142 | * const template = yield* GCP.Compute.RegionInstanceTemplate("web", {}); |
| 143 | * ``` |
| 144 | * |
| 145 | * **Example:** Explicit machine type, disk, and labels |
| 146 | * ```typescript |
| 147 | * const template = yield* GCP.Compute.RegionInstanceTemplate("web", { |
| 148 | * region: "us-central1", |
| 149 | * machineType: "e2-micro", |
| 150 | * labels: { env: "prod" }, |
| 151 | * disks: [ |
| 152 | * { |
| 153 | * boot: true, |
| 154 | * autoDelete: true, |
| 155 | * sourceImage: |
| 156 | * "projects/debian-cloud/global/images/family/debian-12", |
| 157 | * diskSizeGb: 10, |
| 158 | * }, |
| 159 | * ], |
| 160 | * }); |
| 161 | * ``` |
| 162 | * |
| 163 | * @resource |
| 164 | * @category Compute |
| 165 | */ |
| 166 | export const RegionInstanceTemplate = Resource<RegionInstanceTemplate>( |
| 167 | "GCP.Compute.RegionInstanceTemplate", |
| 168 | ); |
| 169 | |
| 170 | export class RegionInstanceTemplateNotResolved extends Data.TaggedError( |
| 171 | "GCP.Compute.RegionInstanceTemplateNotResolved", |
| 172 | )<{ |
| 173 | templateName: string; |
| 174 | region: string; |
| 175 | }> {} |
| 176 | |
| 177 | const DEFAULT_DISKS: RegionInstanceTemplateDisk[] = [ |
| 178 | { |
| 179 | boot: true, |
| 180 | autoDelete: true, |
| 181 | type: "PERSISTENT", |
| 182 | sourceImage: DEFAULT_SOURCE_IMAGE, |
| 183 | diskSizeGb: DEFAULT_DISK_SIZE_GB, |
| 184 | }, |
| 185 | ]; |
| 186 | |
| 187 | const DEFAULT_NICS: RegionInstanceTemplateNetworkInterface[] = [{ network: DEFAULT_NETWORK }]; |
| 188 | |
| 189 | const userLabels = ( |
| 190 | labels: Record<string, string | undefined> | null | undefined, |
| 191 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 192 | |
| 193 | const sortedRecord = (labels: Record<string, string> | undefined): Record<string, string> => |
| 194 | Object.fromEntries( |
| 195 | Object.entries(labels ?? {}).sort(([left], [right]) => left.localeCompare(right)), |
| 196 | ); |
| 197 | |
| 198 | const resolvedDisks = (props: RegionInstanceTemplateProps) => |
| 199 | props.disks !== undefined && props.disks.length > 0 ? props.disks : DEFAULT_DISKS; |
| 200 | |
| 201 | const resolvedNics = (props: RegionInstanceTemplateProps) => |
| 202 | props.networkInterfaces !== undefined && props.networkInterfaces.length > 0 |
| 203 | ? props.networkInterfaces |
| 204 | : DEFAULT_NICS; |
| 205 | |
| 206 | const fingerprint = (props: RegionInstanceTemplateProps): string => |
| 207 | JSON.stringify({ |
| 208 | templateName: props.templateName ?? "", |
| 209 | region: props.region ? lastSegment(props.region).toLowerCase() : "", |
| 210 | description: props.description ?? "", |
| 211 | machineType: props.machineType ?? DEFAULT_MACHINE_TYPE, |
| 212 | canIpForward: props.canIpForward === true, |
| 213 | labels: sortedRecord(props.labels), |
| 214 | networkTags: [...(props.networkTags ?? [])].sort(), |
| 215 | metadata: sortedRecord(props.metadata), |
| 216 | disks: resolvedDisks(props).map((disk) => ({ |
| 217 | boot: disk.boot === true, |
| 218 | autoDelete: disk.autoDelete, |
| 219 | deviceName: disk.deviceName ?? "", |
| 220 | type: disk.type ?? "", |
| 221 | mode: disk.mode ?? "", |
| 222 | diskInterface: disk.diskInterface ?? "", |
| 223 | diskSizeGb: disk.diskSizeGb !== undefined ? String(disk.diskSizeGb) : "", |
| 224 | diskType: disk.diskType ?? "", |
| 225 | sourceImage: disk.sourceImage ?? "", |
| 226 | sourceSnapshot: disk.sourceSnapshot ?? "", |
| 227 | source: disk.source ?? "", |
| 228 | diskName: disk.diskName ?? "", |
| 229 | labels: sortedRecord(disk.labels), |
| 230 | })), |
| 231 | networkInterfaces: resolvedNics(props).map((nic) => ({ |
| 232 | network: nic.network ?? "", |
| 233 | subnetwork: nic.subnetwork ?? "", |
| 234 | networkIP: nic.networkIP ?? "", |
| 235 | nicType: nic.nicType ?? "", |
| 236 | stackType: nic.stackType ?? "", |
| 237 | accessConfigs: nic.accessConfigs ?? [], |
| 238 | })), |
| 239 | serviceAccounts: props.serviceAccounts ?? [], |
| 240 | scheduling: props.scheduling ?? {}, |
| 241 | }); |
| 242 | |
| 243 | const initializeParamsOf = ( |
| 244 | disk: RegionInstanceTemplateDisk, |
| 245 | ): compute.AttachedDiskInitializeParams | undefined => { |
| 246 | if ( |
| 247 | disk.sourceImage === undefined && |
| 248 | disk.sourceSnapshot === undefined && |
| 249 | disk.diskType === undefined && |
| 250 | disk.diskName === undefined && |
| 251 | disk.labels === undefined && |
| 252 | disk.diskSizeGb === undefined |
| 253 | ) { |
| 254 | return undefined; |
| 255 | } |
| 256 | return { |
| 257 | sourceImage: disk.sourceImage, |
| 258 | sourceSnapshot: disk.sourceSnapshot, |
| 259 | diskType: disk.diskType, |
| 260 | diskName: disk.diskName, |
| 261 | labels: disk.labels, |
| 262 | diskSizeGb: disk.diskSizeGb !== undefined ? String(disk.diskSizeGb) : undefined, |
| 263 | }; |
| 264 | }; |
| 265 | |
| 266 | const toDisks = (disks: RegionInstanceTemplateDisk[]): compute.AttachedDisk[] => |
| 267 | disks.map((disk) => ({ |
| 268 | boot: disk.boot, |
| 269 | autoDelete: disk.autoDelete, |
| 270 | deviceName: disk.deviceName, |
| 271 | type: disk.type, |
| 272 | mode: disk.mode, |
| 273 | interface: disk.diskInterface, |
| 274 | source: disk.source, |
| 275 | initializeParams: disk.source ? undefined : initializeParamsOf(disk), |
| 276 | })); |
| 277 | |
| 278 | const toNics = (nics: RegionInstanceTemplateNetworkInterface[]): compute.NetworkInterface[] => |
| 279 | nics.map((nic) => ({ |
| 280 | network: nic.network, |
| 281 | subnetwork: nic.subnetwork, |
| 282 | networkIP: nic.networkIP, |
| 283 | nicType: nic.nicType, |
| 284 | stackType: nic.stackType, |
| 285 | accessConfigs: nic.accessConfigs, |
| 286 | })); |
| 287 | |
| 288 | const toProperties = ( |
| 289 | news: RegionInstanceTemplateProps, |
| 290 | labels: Record<string, string>, |
| 291 | ): compute.InstanceProperties => ({ |
| 292 | machineType: news.machineType ?? DEFAULT_MACHINE_TYPE, |
| 293 | canIpForward: news.canIpForward, |
| 294 | labels, |
| 295 | tags: news.networkTags !== undefined ? { items: news.networkTags } : undefined, |
| 296 | metadata: |
| 297 | news.metadata !== undefined |
| 298 | ? { |
| 299 | items: Object.entries(news.metadata).map(([key, value]) => ({ |
| 300 | key, |
| 301 | value, |
| 302 | })), |
| 303 | } |
| 304 | : undefined, |
| 305 | disks: toDisks(resolvedDisks(news)), |
| 306 | networkInterfaces: toNics(resolvedNics(news)), |
| 307 | serviceAccounts: news.serviceAccounts, |
| 308 | scheduling: news.scheduling, |
| 309 | }); |
| 310 | |
| 311 | const bootSourceImage = (template: compute.InstanceTemplate) => { |
| 312 | const boot = (template.properties?.disks ?? []).find((disk) => disk.boot === true); |
| 313 | return boot?.initializeParams?.sourceImage; |
| 314 | }; |
| 315 | |
| 316 | const toAttrs = ( |
| 317 | template: compute.InstanceTemplate, |
| 318 | project: string, |
| 319 | ): RegionInstanceTemplate["Attributes"] => ({ |
| 320 | templateName: template.name ?? lastSegment(template.selfLink), |
| 321 | project, |
| 322 | region: lastSegment(template.region).toLowerCase(), |
| 323 | description: template.description, |
| 324 | machineType: template.properties?.machineType, |
| 325 | labels: userLabels(template.properties?.labels), |
| 326 | networkTags: template.properties?.tags?.items ?? [], |
| 327 | canIpForward: template.properties?.canIpForward === true, |
| 328 | sourceImage: bootSourceImage(template), |
| 329 | selfLink: template.selfLink, |
| 330 | templateId: template.id, |
| 331 | creationTimestamp: template.creationTimestamp, |
| 332 | }); |
| 333 | |
| 334 | const getByName = (project: string, region: string, instanceTemplate: string) => |
| 335 | compute |
| 336 | .getRegionInstanceTemplates({ project, region, instanceTemplate }) |
| 337 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 338 | |
| 339 | const awaitResource = (project: string, region: string, templateName: string) => |
| 340 | getByName(project, region, templateName).pipe( |
| 341 | Effect.flatMap((template) => |
| 342 | template !== undefined |
| 343 | ? Effect.succeed(template) |
| 344 | : Effect.fail(new RegionInstanceTemplateNotResolved({ templateName, region })), |
| 345 | ), |
| 346 | Effect.retry({ |
| 347 | while: (error) => error._tag === "GCP.Compute.RegionInstanceTemplateNotResolved", |
| 348 | times: 8, |
| 349 | schedule: Schedule.spaced("1 second"), |
| 350 | }), |
| 351 | ); |
| 352 | |
| 353 | export const RegionInstanceTemplateProvider = () => |
| 354 | Provider.succeed(RegionInstanceTemplate, { |
| 355 | stables: ["templateName", "project", "region", "templateId", "selfLink", "creationTimestamp"], |
| 356 | |
| 357 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 358 | if (!isResolved(news)) return undefined; |
| 359 | const env = yield* GcpEnvironment.current; |
| 360 | const previousName = olds?.templateName ?? output?.templateName; |
| 361 | const nextName = news.templateName ?? previousName; |
| 362 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 363 | const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region); |
| 364 | if (previousName === undefined && output === undefined) { |
| 365 | return undefined; |
| 366 | } |
| 367 | const nameChanged = |
| 368 | news.templateName !== undefined && |
| 369 | previousName !== undefined && |
| 370 | news.templateName !== previousName; |
| 371 | const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion; |
| 372 | const propsChanged = olds !== undefined && fingerprint(news) !== fingerprint(olds); |
| 373 | const adoptedChanged = |
| 374 | olds === undefined && |
| 375 | output !== undefined && |
| 376 | ((news.machineType ?? DEFAULT_MACHINE_TYPE) !== |
| 377 | (output.machineType ?? DEFAULT_MACHINE_TYPE) || |
| 378 | (news.description ?? "") !== (output.description ?? "") || |
| 379 | (news.canIpForward === true) !== output.canIpForward || |
| 380 | !sameJson(sortedRecord(news.labels), sortedRecord(output.labels))); |
| 381 | if (!nameChanged && !regionChanged && !propsChanged && !adoptedChanged) { |
| 382 | return undefined; |
| 383 | } |
| 384 | return { |
| 385 | action: "replace" as const, |
| 386 | deleteFirst: |
| 387 | previousName !== undefined && nextName !== undefined && nextName === previousName, |
| 388 | }; |
| 389 | }), |
| 390 | |
| 391 | read: Effect.fn(function* ({ id, olds, output }) { |
| 392 | const env = yield* GcpEnvironment.current; |
| 393 | const templateName = yield* toPhysicalName( |
| 394 | id, |
| 395 | olds?.templateName, |
| 396 | output?.templateName, |
| 397 | "template", |
| 398 | ); |
| 399 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 400 | const existing = yield* getByName(env.project, region, templateName); |
| 401 | if (existing === undefined) return undefined; |
| 402 | const attrs = toAttrs(existing, env.project); |
| 403 | return (yield* hasAlchemyLabels(id, tagRecord(existing.properties?.labels))) |
| 404 | ? attrs |
| 405 | : Unowned(attrs); |
| 406 | }), |
| 407 | |
| 408 | list: () => |
| 409 | Effect.gen(function* () { |
| 410 | const env = yield* GcpEnvironment.current; |
| 411 | const pages = yield* compute.aggregatedListInstanceTemplates |
| 412 | .pages({ |
| 413 | project: env.project, |
| 414 | maxResults: 500, |
| 415 | returnPartialSuccess: true, |
| 416 | }) |
| 417 | .pipe( |
| 418 | Stream.runCollect, |
| 419 | Effect.catchTag("NotFound", () => Effect.succeed([] as never[])), |
| 420 | ); |
| 421 | return Array.from(pages as readonly compute.InstanceTemplateAggregatedList[]).flatMap( |
| 422 | (page) => |
| 423 | Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => { |
| 424 | if (!scope.startsWith("regions/")) return []; |
| 425 | return (scoped?.instanceTemplates ?? []) |
| 426 | .filter((template) => |
| 427 | Object.keys(template.properties?.labels ?? {}).some((key) => |
| 428 | key.startsWith("alchemy-"), |
| 429 | ), |
| 430 | ) |
| 431 | .map((template) => toAttrs(template, env.project)); |
| 432 | }), |
| 433 | ); |
| 434 | }), |
| 435 | |
| 436 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 437 | const env = yield* GcpEnvironment.current; |
| 438 | const templateName = yield* toPhysicalName( |
| 439 | id, |
| 440 | news.templateName, |
| 441 | output?.templateName, |
| 442 | "template", |
| 443 | ); |
| 444 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 445 | const desiredLabels = { |
| 446 | ...toLabels(news.labels), |
| 447 | ...(yield* createInternalLabels(id)), |
| 448 | }; |
| 449 | |
| 450 | let current = yield* getByName(env.project, region, templateName); |
| 451 | |
| 452 | if (current === undefined) { |
| 453 | yield* runRegionOp( |
| 454 | env.project, |
| 455 | region, |
| 456 | compute.insertRegionInstanceTemplates({ |
| 457 | project: env.project, |
| 458 | region, |
| 459 | body: { |
| 460 | name: templateName, |
| 461 | description: news.description, |
| 462 | properties: toProperties(news, desiredLabels), |
| 463 | }, |
| 464 | }), |
| 465 | { ignoreAlreadyExists: true }, |
| 466 | ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 467 | current = yield* awaitResource(env.project, region, templateName); |
| 468 | } |
| 469 | |
| 470 | if (current === undefined) { |
| 471 | return yield* new RegionInstanceTemplateNotResolved({ |
| 472 | templateName, |
| 473 | region, |
| 474 | }); |
| 475 | } |
| 476 | |
| 477 | return toAttrs(current, env.project); |
| 478 | }), |
| 479 | |
| 480 | delete: Effect.fn(function* ({ output }) { |
| 481 | const env = yield* GcpEnvironment.current; |
| 482 | const region = normalizeRegion(output.region, env.region); |
| 483 | yield* runRegionOp( |
| 484 | env.project, |
| 485 | region, |
| 486 | compute.deleteRegionInstanceTemplates({ |
| 487 | project: env.project, |
| 488 | region, |
| 489 | instanceTemplate: output.templateName, |
| 490 | }), |
| 491 | { ignoreNotFound: true }, |
| 492 | ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 493 | }), |
| 494 | }); |