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 * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | encodeDescription, |
| 15 | hasOwnershipMarker, |
| 16 | lastSegment, |
| 17 | normalizeRegion, |
| 18 | parseDescription, |
| 19 | runRegionOp, |
| 20 | toPhysicalName, |
| 21 | } from "./internal.ts"; |
| 22 | |
| 23 | export type RegionInstanceGroupManagerResizeRequestDuration = { |
| 24 | /** Whole seconds. */ |
| 25 | seconds?: string; |
| 26 | /** Fractional seconds at nanosecond resolution. */ |
| 27 | nanos?: number; |
| 28 | }; |
| 29 | |
| 30 | export type RegionInstanceGroupManagerResizeRequestProps = { |
| 31 | /** |
| 32 | * Resize-request name (RFC1035, 1-63 characters). If omitted, a unique |
| 33 | * name is generated from the stack, stage, and logical id. Changing it |
| 34 | * replaces the request. |
| 35 | */ |
| 36 | requestName?: string; |
| 37 | /** |
| 38 | * Region of the parent managed instance group. Immutable. `US-CENTRAL1` |
| 39 | * is accepted and normalized to `us-central1`. |
| 40 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 41 | */ |
| 42 | region?: string; |
| 43 | /** |
| 44 | * Parent regional managed instance group name or URL. Immutable — |
| 45 | * changing it replaces the request. |
| 46 | */ |
| 47 | instanceGroupManager: string; |
| 48 | /** |
| 49 | * Number of instances to create. The group's target size increases by |
| 50 | * this number. Immutable — changing it replaces the request. |
| 51 | */ |
| 52 | resizeBy: number; |
| 53 | /** |
| 54 | * Optional description. Resize requests have no labels field, so |
| 55 | * Alchemy ownership is stored in a `[alchemy …]` prefix for `list` / |
| 56 | * nuke. |
| 57 | */ |
| 58 | description?: string; |
| 59 | /** |
| 60 | * Requested run duration for VMs created by this request. At the end of |
| 61 | * the duration the instance is deleted. Compute requires it on insert. |
| 62 | * Immutable. |
| 63 | */ |
| 64 | requestedRunDuration: RegionInstanceGroupManagerResizeRequestDuration; |
| 65 | }; |
| 66 | |
| 67 | export type RegionInstanceGroupManagerResizeRequest = Resource< |
| 68 | "GCP.Compute.RegionInstanceGroupManagerResizeRequest", |
| 69 | RegionInstanceGroupManagerResizeRequestProps, |
| 70 | { |
| 71 | /** Resize-request name. */ |
| 72 | requestName: string; |
| 73 | /** Project id. */ |
| 74 | project: string; |
| 75 | /** Region short name (`us-central1`). */ |
| 76 | region: string; |
| 77 | /** Parent managed instance group name. */ |
| 78 | instanceGroupManager: string; |
| 79 | /** Requested instance count delta. */ |
| 80 | resizeBy: number; |
| 81 | /** User description with the Alchemy ownership prefix stripped. */ |
| 82 | description: string | undefined; |
| 83 | /** Requested run duration, if set. */ |
| 84 | requestedRunDuration: RegionInstanceGroupManagerResizeRequestDuration | undefined; |
| 85 | /** Current request state. */ |
| 86 | state: string | undefined; |
| 87 | /** Server-defined URL. */ |
| 88 | selfLink: string | undefined; |
| 89 | /** Server-defined URL including the numeric id. */ |
| 90 | selfLinkWithId: string | undefined; |
| 91 | /** Server-assigned numeric id. */ |
| 92 | requestId: string | undefined; |
| 93 | /** RFC3339 creation timestamp. */ |
| 94 | creationTimestamp: string | undefined; |
| 95 | /** Resource kind. */ |
| 96 | kind: string | undefined; |
| 97 | }, |
| 98 | never, |
| 99 | Providers |
| 100 | >; |
| 101 | |
| 102 | /** |
| 103 | * A regional managed instance group resize request. |
| 104 | * |
| 105 | * Resize requests provision (or queue) additional VMs on a regional MIG. |
| 106 | * They are immutable after create — changing `resizeBy`, duration, the |
| 107 | * parent group, or the name replaces the request. Delete cancels an |
| 108 | * in-flight request first when the API requires it. |
| 109 | * |
| 110 | * ### Creating a Resize Request |
| 111 | * **Example:** Queue one extra VM |
| 112 | * ```typescript |
| 113 | * const request = yield* GCP.Compute.RegionInstanceGroupManagerResizeRequest( |
| 114 | * "Burst", |
| 115 | * { |
| 116 | * instanceGroupManager: manager.managerName, |
| 117 | * resizeBy: 1, |
| 118 | * requestedRunDuration: { seconds: "3600" }, |
| 119 | * description: "burst capacity", |
| 120 | * }, |
| 121 | * ); |
| 122 | * ``` |
| 123 | * |
| 124 | * **Example:** Timed run |
| 125 | * ```typescript |
| 126 | * const request = yield* GCP.Compute.RegionInstanceGroupManagerResizeRequest( |
| 127 | * "Burst", |
| 128 | * { |
| 129 | * instanceGroupManager: manager.managerName, |
| 130 | * resizeBy: 1, |
| 131 | * requestedRunDuration: { seconds: "3600" }, |
| 132 | * }, |
| 133 | * ); |
| 134 | * ``` |
| 135 | * |
| 136 | * @resource |
| 137 | * @category Compute |
| 138 | */ |
| 139 | export const RegionInstanceGroupManagerResizeRequest = |
| 140 | Resource<RegionInstanceGroupManagerResizeRequest>( |
| 141 | "GCP.Compute.RegionInstanceGroupManagerResizeRequest", |
| 142 | ); |
| 143 | |
| 144 | export class RegionInstanceGroupManagerResizeRequestNotResolved extends Data.TaggedError( |
| 145 | "GCP.Compute.RegionInstanceGroupManagerResizeRequestNotResolved", |
| 146 | )<{ |
| 147 | requestName: string; |
| 148 | instanceGroupManager: string; |
| 149 | region: string; |
| 150 | }> {} |
| 151 | |
| 152 | const managerNameOf = (value: string) => lastSegment(value); |
| 153 | |
| 154 | const toAttrs = ( |
| 155 | request: compute.InstanceGroupManagerResizeRequest, |
| 156 | project: string, |
| 157 | instanceGroupManager: string, |
| 158 | ): RegionInstanceGroupManagerResizeRequest["Attributes"] => { |
| 159 | const parsed = parseDescription(request.description); |
| 160 | return { |
| 161 | requestName: request.name ?? lastSegment(request.selfLink), |
| 162 | project, |
| 163 | region: lastSegment(request.region).toLowerCase(), |
| 164 | instanceGroupManager: managerNameOf(instanceGroupManager), |
| 165 | resizeBy: request.resizeBy ?? 0, |
| 166 | description: parsed.description, |
| 167 | requestedRunDuration: request.requestedRunDuration, |
| 168 | state: request.state, |
| 169 | selfLink: request.selfLink, |
| 170 | selfLinkWithId: request.selfLinkWithId, |
| 171 | requestId: request.id, |
| 172 | creationTimestamp: request.creationTimestamp, |
| 173 | kind: request.kind, |
| 174 | }; |
| 175 | }; |
| 176 | |
| 177 | const getByName = ( |
| 178 | project: string, |
| 179 | region: string, |
| 180 | instanceGroupManager: string, |
| 181 | resizeRequest: string, |
| 182 | ) => |
| 183 | compute |
| 184 | .getRegionInstanceGroupManagerResizeRequests({ |
| 185 | project, |
| 186 | region, |
| 187 | instanceGroupManager, |
| 188 | resizeRequest, |
| 189 | }) |
| 190 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 191 | |
| 192 | const awaitResource = ( |
| 193 | project: string, |
| 194 | region: string, |
| 195 | instanceGroupManager: string, |
| 196 | requestName: string, |
| 197 | ) => |
| 198 | getByName(project, region, instanceGroupManager, requestName).pipe( |
| 199 | Effect.flatMap((request) => |
| 200 | request !== undefined |
| 201 | ? Effect.succeed(request) |
| 202 | : Effect.fail( |
| 203 | new RegionInstanceGroupManagerResizeRequestNotResolved({ |
| 204 | requestName, |
| 205 | instanceGroupManager, |
| 206 | region, |
| 207 | }), |
| 208 | ), |
| 209 | ), |
| 210 | Effect.retry({ |
| 211 | while: (error) => |
| 212 | error._tag === "GCP.Compute.RegionInstanceGroupManagerResizeRequestNotResolved", |
| 213 | times: 8, |
| 214 | schedule: Schedule.spaced("1 second"), |
| 215 | }), |
| 216 | ); |
| 217 | |
| 218 | const needsCancel = (state: string | undefined) => { |
| 219 | const current = (state ?? "").toUpperCase(); |
| 220 | return current === "ACCEPTED" || current === "CREATING"; |
| 221 | }; |
| 222 | |
| 223 | export const RegionInstanceGroupManagerResizeRequestProvider = () => |
| 224 | Provider.succeed(RegionInstanceGroupManagerResizeRequest, { |
| 225 | stables: [ |
| 226 | "requestName", |
| 227 | "project", |
| 228 | "region", |
| 229 | "instanceGroupManager", |
| 230 | "requestId", |
| 231 | "selfLink", |
| 232 | "creationTimestamp", |
| 233 | ], |
| 234 | |
| 235 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 236 | if (!isResolved(news)) return undefined; |
| 237 | const env = yield* GcpEnvironment.current; |
| 238 | const previousName = olds?.requestName ?? output?.requestName; |
| 239 | const nextName = news.requestName ?? previousName; |
| 240 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 241 | const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region); |
| 242 | const previousManager = managerNameOf( |
| 243 | olds?.instanceGroupManager ?? output?.instanceGroupManager ?? "", |
| 244 | ); |
| 245 | const nextManager = managerNameOf(news.instanceGroupManager); |
| 246 | const nameChanged = |
| 247 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 248 | const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion; |
| 249 | const managerChanged = previousManager.length > 0 && previousManager !== nextManager; |
| 250 | const resizeChanged = |
| 251 | (olds?.resizeBy ?? output?.resizeBy) !== undefined && |
| 252 | news.resizeBy !== (olds?.resizeBy ?? output?.resizeBy); |
| 253 | if (nameChanged || regionChanged || managerChanged || resizeChanged) { |
| 254 | return { |
| 255 | action: "replace" as const, |
| 256 | deleteFirst: !nameChanged || nextName === undefined || nextName === previousName, |
| 257 | }; |
| 258 | } |
| 259 | return undefined; |
| 260 | }), |
| 261 | |
| 262 | read: Effect.fn(function* ({ id, olds, output }) { |
| 263 | const env = yield* GcpEnvironment.current; |
| 264 | const requestName = yield* toPhysicalName( |
| 265 | id, |
| 266 | olds?.requestName, |
| 267 | output?.requestName, |
| 268 | "resize", |
| 269 | ); |
| 270 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 271 | const instanceGroupManager = managerNameOf( |
| 272 | olds?.instanceGroupManager ?? output?.instanceGroupManager ?? "", |
| 273 | ); |
| 274 | if (instanceGroupManager.length === 0) return undefined; |
| 275 | const existing = yield* getByName(env.project, region, instanceGroupManager, requestName); |
| 276 | if (existing === undefined) return undefined; |
| 277 | const attrs = toAttrs(existing, env.project, instanceGroupManager); |
| 278 | const { labels } = parseDescription(existing.description); |
| 279 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 280 | }), |
| 281 | |
| 282 | list: () => |
| 283 | Effect.gen(function* () { |
| 284 | const env = yield* GcpEnvironment.current; |
| 285 | const pages = yield* compute.aggregatedListInstanceGroupManagers |
| 286 | .pages({ |
| 287 | project: env.project, |
| 288 | maxResults: 500, |
| 289 | returnPartialSuccess: true, |
| 290 | }) |
| 291 | .pipe( |
| 292 | Stream.runCollect, |
| 293 | Effect.catchTag("NotFound", () => Effect.succeed([] as never[])), |
| 294 | ); |
| 295 | const managers = Array.from( |
| 296 | pages as readonly compute.InstanceGroupManagerAggregatedList[], |
| 297 | ).flatMap((page) => |
| 298 | Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => { |
| 299 | if (!scope.startsWith("regions/")) return []; |
| 300 | return (scoped?.instanceGroupManagers ?? []) |
| 301 | .filter((manager) => lastSegment(manager.region).length > 0) |
| 302 | .map((manager) => ({ |
| 303 | name: manager.name ?? lastSegment(manager.selfLink), |
| 304 | region: lastSegment(manager.region).toLowerCase(), |
| 305 | })); |
| 306 | }), |
| 307 | ); |
| 308 | const listed: RegionInstanceGroupManagerResizeRequest["Attributes"][] = []; |
| 309 | for (const manager of managers) { |
| 310 | const chunk = yield* compute.listRegionInstanceGroupManagerResizeRequests |
| 311 | .items({ |
| 312 | project: env.project, |
| 313 | region: manager.region, |
| 314 | instanceGroupManager: manager.name, |
| 315 | maxResults: 500, |
| 316 | returnPartialSuccess: true, |
| 317 | }) |
| 318 | .pipe( |
| 319 | Stream.filter((item) => hasOwnershipMarker(item.description)), |
| 320 | Stream.map((item) => toAttrs(item, env.project, manager.name)), |
| 321 | Stream.runCollect, |
| 322 | Effect.map((items) => Array.from(items)), |
| 323 | Effect.catchTag("NotFound", () => |
| 324 | Effect.succeed([] as RegionInstanceGroupManagerResizeRequest["Attributes"][]), |
| 325 | ), |
| 326 | ); |
| 327 | listed.push(...chunk); |
| 328 | } |
| 329 | return listed; |
| 330 | }), |
| 331 | |
| 332 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 333 | const env = yield* GcpEnvironment.current; |
| 334 | const requestName = yield* toPhysicalName( |
| 335 | id, |
| 336 | news.requestName, |
| 337 | output?.requestName, |
| 338 | "resize", |
| 339 | ); |
| 340 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 341 | const instanceGroupManager = managerNameOf(news.instanceGroupManager); |
| 342 | const ownership = yield* createInternalLabels(id); |
| 343 | const desiredDescription = encodeDescription(ownership, news.description); |
| 344 | |
| 345 | let current = yield* getByName(env.project, region, instanceGroupManager, requestName); |
| 346 | |
| 347 | if (current === undefined) { |
| 348 | yield* runRegionOp( |
| 349 | env.project, |
| 350 | region, |
| 351 | compute.insertRegionInstanceGroupManagerResizeRequests({ |
| 352 | project: env.project, |
| 353 | region, |
| 354 | instanceGroupManager, |
| 355 | body: { |
| 356 | name: requestName, |
| 357 | description: desiredDescription, |
| 358 | resizeBy: news.resizeBy, |
| 359 | requestedRunDuration: news.requestedRunDuration, |
| 360 | }, |
| 361 | }), |
| 362 | { ignoreAlreadyExists: true }, |
| 363 | ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 364 | current = yield* awaitResource(env.project, region, instanceGroupManager, requestName); |
| 365 | } |
| 366 | |
| 367 | if (current === undefined) { |
| 368 | return yield* new RegionInstanceGroupManagerResizeRequestNotResolved({ |
| 369 | requestName, |
| 370 | instanceGroupManager, |
| 371 | region, |
| 372 | }); |
| 373 | } |
| 374 | |
| 375 | return toAttrs(current, env.project, instanceGroupManager); |
| 376 | }), |
| 377 | |
| 378 | delete: Effect.fn(function* ({ output }) { |
| 379 | const env = yield* GcpEnvironment.current; |
| 380 | const region = normalizeRegion(output.region, env.region); |
| 381 | const instanceGroupManager = managerNameOf(output.instanceGroupManager); |
| 382 | const current = yield* getByName( |
| 383 | env.project, |
| 384 | region, |
| 385 | instanceGroupManager, |
| 386 | output.requestName, |
| 387 | ); |
| 388 | if (current !== undefined && needsCancel(current.state)) { |
| 389 | yield* runRegionOp( |
| 390 | env.project, |
| 391 | region, |
| 392 | compute.cancelRegionInstanceGroupManagerResizeRequests({ |
| 393 | project: env.project, |
| 394 | region, |
| 395 | instanceGroupManager, |
| 396 | resizeRequest: output.requestName, |
| 397 | }), |
| 398 | { ignoreNotFound: true }, |
| 399 | ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 400 | } |
| 401 | yield* runRegionOp( |
| 402 | env.project, |
| 403 | region, |
| 404 | compute.deleteRegionInstanceGroupManagerResizeRequests({ |
| 405 | project: env.project, |
| 406 | region, |
| 407 | instanceGroupManager, |
| 408 | resizeRequest: output.requestName, |
| 409 | }), |
| 410 | { ignoreNotFound: true }, |
| 411 | ).pipe( |
| 412 | Effect.retry({ |
| 413 | while: (error) => error._tag === "Conflict", |
| 414 | times: 8, |
| 415 | schedule: Schedule.spaced("2 seconds"), |
| 416 | }), |
| 417 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 418 | ); |
| 419 | }), |
| 420 | }); |