The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { Credentials } from "@distilled.cloud/gcp/Credentials"; |
| 2 | import * as cloudrun from "@distilled.cloud/gcp/run_v2"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import type * as Bundle from "alchemy/Bundle/Bundle"; |
| 5 | import type { PackageInstall } from "alchemy/Bundle/InstalledPackages"; |
| 6 | import { isResolved } from "alchemy/Diff"; |
| 7 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 8 | import { Platform, type Main, type PlatformProps } from "alchemy/Platform"; |
| 9 | import * as Provider from "alchemy/Provider"; |
| 10 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 11 | import { type ServerHost } from "alchemy/Runtime/Process"; |
| 12 | import { tagRecord } from "alchemy/Tags"; |
| 13 | import type { ExtraFile } from "alchemy/Util/extraFiles"; |
| 14 | import * as Data from "effect/Data"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as Schedule from "effect/Schedule"; |
| 17 | import * as Stream from "effect/Stream"; |
| 18 | import { destroyHostImageRepository, makeImageSource } from "../ArtifactRegistry/ImageSource.ts"; |
| 19 | import { GcpEnvironment } from "../Environment.ts"; |
| 20 | import { retryActAs, type AppliedIamGrant, type GcpHostBinding } from "../Host.ts"; |
| 21 | import { |
| 22 | createGcpHostRuntimeContext, |
| 23 | RPC_METHODS_ENV, |
| 24 | type GcpHostRuntimeContext, |
| 25 | } from "../HostContext.ts"; |
| 26 | import { |
| 27 | alchemyRuntimeEnv, |
| 28 | isManagedServiceAccount, |
| 29 | makeGcpBootstrap, |
| 30 | mergeContainerEnv, |
| 31 | mountCloudSqlInstances, |
| 32 | releaseHostIdentity, |
| 33 | resolveHostIdentity, |
| 34 | } from "../HostRuntime.ts"; |
| 35 | import { |
| 36 | createInternalLabels, |
| 37 | diffLabels, |
| 38 | hasAlchemyLabels, |
| 39 | stripInternalLabels, |
| 40 | toLabels, |
| 41 | } from "../Labels.ts"; |
| 42 | import { |
| 43 | type LongRunningOperation, |
| 44 | waitForOperation as waitForLongRunningOperation, |
| 45 | } from "../Operation.ts"; |
| 46 | import type { Providers } from "../Providers.ts"; |
| 47 | import { |
| 48 | boundContainersOf, |
| 49 | directContainerNames, |
| 50 | flattenContainers, |
| 51 | isContainerAttributes, |
| 52 | type BoundContainer, |
| 53 | type Container, |
| 54 | } from "./Container.ts"; |
| 55 | |
| 56 | const DEFAULT_IMAGE = "us-docker.pkg.dev/cloudrun/container/hello"; |
| 57 | const MAX_NAME_LENGTH = 49; |
| 58 | |
| 59 | export type EnvVar = { |
| 60 | /** Environment variable name. */ |
| 61 | name?: string; |
| 62 | /** Literal value. Mutually exclusive with `valueSource`. */ |
| 63 | value?: string; |
| 64 | /** Secret Manager source for the value. */ |
| 65 | valueSource?: { |
| 66 | secretKeyRef?: { |
| 67 | secret?: string; |
| 68 | version?: string; |
| 69 | }; |
| 70 | }; |
| 71 | }; |
| 72 | |
| 73 | export type ContainerPort = { |
| 74 | /** Protocol name (`http1` or `h2c`). */ |
| 75 | name?: string; |
| 76 | /** TCP port the container listens on. */ |
| 77 | containerPort?: number; |
| 78 | }; |
| 79 | |
| 80 | export type ResourceRequirements = { |
| 81 | /** Resource limits. Keys: `cpu`, `memory`, `nvidia.com/gpu`. */ |
| 82 | limits?: Record<string, string>; |
| 83 | /** Allocate CPU only during requests. */ |
| 84 | cpuIdle?: boolean; |
| 85 | /** Boost CPU on startup to reduce cold starts. */ |
| 86 | startupCpuBoost?: boolean; |
| 87 | }; |
| 88 | |
| 89 | export type HttpHeader = { |
| 90 | /** Header name. */ |
| 91 | name: string; |
| 92 | /** Header value. */ |
| 93 | value?: string; |
| 94 | }; |
| 95 | |
| 96 | export type Probe = { |
| 97 | /** |
| 98 | * Perform an HTTP GET; any 2xx–3xx response passes. Exactly one of |
| 99 | * `httpGet`, `tcpSocket`, or `grpc` must be set. |
| 100 | */ |
| 101 | httpGet?: { |
| 102 | /** Request path. @default "/" */ |
| 103 | path?: string; |
| 104 | /** Port to probe. @default the container's `ports[0].containerPort` */ |
| 105 | port?: number; |
| 106 | /** Extra request headers. */ |
| 107 | httpHeaders?: HttpHeader[]; |
| 108 | }; |
| 109 | /** Open a TCP connection; passes once the port accepts it. */ |
| 110 | tcpSocket?: { |
| 111 | /** Port to probe. @default the container's `ports[0].containerPort` */ |
| 112 | port?: number; |
| 113 | }; |
| 114 | /** Call the gRPC health checking protocol. */ |
| 115 | grpc?: { |
| 116 | /** Port to probe. @default the container's `ports[0].containerPort` */ |
| 117 | port?: number; |
| 118 | /** Service name sent in the `HealthCheckRequest`. */ |
| 119 | service?: string; |
| 120 | }; |
| 121 | /** |
| 122 | * Seconds after the container starts before the first probe (max 240 |
| 123 | * for startup probes, 3600 for liveness probes). |
| 124 | * @default 0 |
| 125 | */ |
| 126 | initialDelaySeconds?: number; |
| 127 | /** Seconds before a probe attempt times out. Must be less than `periodSeconds`. @default 1 */ |
| 128 | timeoutSeconds?: number; |
| 129 | /** Seconds between probe attempts (max 240 for startup probes). @default 10 */ |
| 130 | periodSeconds?: number; |
| 131 | /** Consecutive failures before the probe fails. @default 3 */ |
| 132 | failureThreshold?: number; |
| 133 | }; |
| 134 | |
| 135 | export type ContainerSpec = { |
| 136 | /** DNS_LABEL container name. Required to reference it from `dependsOn`. */ |
| 137 | name?: string; |
| 138 | /** |
| 139 | * Container image (Artifact Registry, GCR, or Docker Hub). Required |
| 140 | * unless `template` is omitted, in which case the public Cloud Run hello |
| 141 | * image is used. |
| 142 | */ |
| 143 | image?: string; |
| 144 | /** Entrypoint. */ |
| 145 | command?: string[]; |
| 146 | /** Arguments to the entrypoint. */ |
| 147 | args?: string[]; |
| 148 | /** Environment variables. */ |
| 149 | env?: EnvVar[]; |
| 150 | /** Exposed ports. Only one port may be set. */ |
| 151 | ports?: ContainerPort[]; |
| 152 | /** CPU / memory / GPU requirements. */ |
| 153 | resources?: ResourceRequirements; |
| 154 | /** Working directory. */ |
| 155 | workingDir?: string; |
| 156 | /** Volume mounts. Names must match the template's `volumes`. */ |
| 157 | volumeMounts?: cloudrun.GoogleCloudRunV2VolumeMountList; |
| 158 | /** |
| 159 | * Probe that must pass before the container counts as started. Until it |
| 160 | * does, the revision takes no traffic and containers that `dependsOn` |
| 161 | * this one wait. Omitting it restores Cloud Run's default TCP probe on |
| 162 | * the serving port. |
| 163 | */ |
| 164 | startupProbe?: Probe; |
| 165 | /** |
| 166 | * Probe run for the container's lifetime; Cloud Run restarts the |
| 167 | * container after `failureThreshold` consecutive failures. Omitting it |
| 168 | * removes any liveness probe. |
| 169 | */ |
| 170 | livenessProbe?: Probe; |
| 171 | /** |
| 172 | * Names of containers in the same revision that must start, and pass |
| 173 | * their startup probe, before this one starts. Without it, every |
| 174 | * container starts at once. It only orders startup: a dependency that |
| 175 | * crashes later doesn't stop this container. |
| 176 | * |
| 177 | * A container bound with `GCP.Run.bindContainer` or `GCP.Run.bindPort` |
| 178 | * is added for you. |
| 179 | */ |
| 180 | dependsOn?: string[]; |
| 181 | }; |
| 182 | |
| 183 | export type RevisionScaling = { |
| 184 | /** Minimum serving instances. */ |
| 185 | minInstanceCount?: number; |
| 186 | /** Maximum serving instances. Server default is 100. */ |
| 187 | maxInstanceCount?: number; |
| 188 | /** CPU utilization target in `[0.1, 0.95]`, or `0` to disable. */ |
| 189 | cpuUtilization?: number; |
| 190 | /** Concurrency utilization target in `[0.1, 0.95]`, or `0` to disable. */ |
| 191 | concurrencyUtilization?: number; |
| 192 | }; |
| 193 | |
| 194 | export type RevisionTemplate = { |
| 195 | /** |
| 196 | * Containers that make up the revision. A `GCP.Run.Container` can be |
| 197 | * listed directly: its spec joins the revision, its bindings' roles go to |
| 198 | * the revision's service account, and the sidecars it binds join too. |
| 199 | */ |
| 200 | containers?: (ContainerSpec | Container)[]; |
| 201 | /** Request timeout (e.g. `"300s"`). */ |
| 202 | timeout?: string; |
| 203 | /** Max concurrent requests per instance. `0` uses the server default. */ |
| 204 | maxInstanceRequestConcurrency?: number; |
| 205 | /** Runtime service account email. Defaults to the project Compute SA. */ |
| 206 | serviceAccount?: string; |
| 207 | /** Sandbox (`EXECUTION_ENVIRONMENT_GEN1` or `EXECUTION_ENVIRONMENT_GEN2`). */ |
| 208 | executionEnvironment?: string; |
| 209 | /** Enable session affinity. */ |
| 210 | sessionAffinity?: boolean; |
| 211 | /** Revision-level scaling. */ |
| 212 | scaling?: RevisionScaling; |
| 213 | /** Revision labels. */ |
| 214 | labels?: Record<string, string>; |
| 215 | /** Revision annotations. */ |
| 216 | annotations?: Record<string, string>; |
| 217 | /** Direct VPC egress / connector. */ |
| 218 | vpcAccess?: cloudrun.GoogleCloudRunV2VpcAccess; |
| 219 | /** Volumes available to containers. */ |
| 220 | volumes?: cloudrun.GoogleCloudRunV2VolumeList; |
| 221 | /** CMEK used to encrypt the container image. */ |
| 222 | encryptionKey?: string; |
| 223 | /** Unique revision name. Generated from the service name if omitted. */ |
| 224 | revision?: string; |
| 225 | }; |
| 226 | |
| 227 | export type TrafficTarget = { |
| 228 | /** Allocation type (`TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST` or `_REVISION`). */ |
| 229 | type?: string; |
| 230 | /** Revision to send traffic to when allocating by revision. */ |
| 231 | revision?: string; |
| 232 | /** Percent of traffic (0–100). */ |
| 233 | percent?: number; |
| 234 | /** URI tag for this target. */ |
| 235 | tag?: string; |
| 236 | }; |
| 237 | |
| 238 | export type ServiceScaling = { |
| 239 | /** Minimum instances across all revisions. */ |
| 240 | minInstanceCount?: number; |
| 241 | /** Maximum instances across all revisions. */ |
| 242 | maxInstanceCount?: number; |
| 243 | /** `AUTOMATIC` or `MANUAL`. */ |
| 244 | scalingMode?: string; |
| 245 | /** Instance count in manual scaling mode. */ |
| 246 | manualInstanceCount?: number; |
| 247 | }; |
| 248 | |
| 249 | export type ServiceProps = PlatformProps & { |
| 250 | /** |
| 251 | * Service id (the `{service}` segment of |
| 252 | * `projects/{project}/locations/{location}/services/{service}`). If |
| 253 | * omitted, a unique name is generated from the stack, stage, and logical |
| 254 | * id. Must begin with a letter, not end with a hyphen, and be fewer than |
| 255 | * 50 characters. Immutable — changing it replaces the service. |
| 256 | */ |
| 257 | serviceId?: string; |
| 258 | /** |
| 259 | * Region (`us-central1`, `europe-west1`, …). Immutable — changing it |
| 260 | * replaces the service. `US-CENTRAL1` is accepted and normalized to |
| 261 | * `us-central1`. |
| 262 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 263 | */ |
| 264 | location?: string; |
| 265 | /** |
| 266 | * User labels. Alchemy ownership labels are merged in automatically. |
| 267 | */ |
| 268 | labels?: Record<string, string>; |
| 269 | /** |
| 270 | * Unstructured annotations. Cloud Run rejects `run.googleapis.com` / |
| 271 | * `cloud.googleapis.com` / Knative namespaces. |
| 272 | */ |
| 273 | annotations?: Record<string, string>; |
| 274 | /** |
| 275 | * Human-readable description (max 512 characters). |
| 276 | */ |
| 277 | description?: string; |
| 278 | /** |
| 279 | * Ingress (`INGRESS_TRAFFIC_ALL`, `INGRESS_TRAFFIC_INTERNAL_ONLY`, |
| 280 | * `INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER`, `INGRESS_TRAFFIC_NONE`). |
| 281 | */ |
| 282 | ingress?: cloudrun.GoogleCloudRunV2ServiceIngressEnum | (string & {}); |
| 283 | /** |
| 284 | * Disable the IAM invoker check (`run.routes.invoke`). |
| 285 | * @default false |
| 286 | */ |
| 287 | invokerIamDisabled?: boolean; |
| 288 | /** |
| 289 | * Disable public resolution of the default `*.run.app` URI. |
| 290 | * @default false |
| 291 | */ |
| 292 | defaultUriDisabled?: boolean; |
| 293 | /** |
| 294 | * Enable Identity-Aware Proxy on the service. |
| 295 | */ |
| 296 | iapEnabled?: boolean; |
| 297 | /** |
| 298 | * Custom audiences encoded into ID tokens. |
| 299 | */ |
| 300 | customAudiences?: string[]; |
| 301 | /** |
| 302 | * Service-level scaling. |
| 303 | */ |
| 304 | scaling?: ServiceScaling; |
| 305 | /** |
| 306 | * Traffic split. Empty / omitted sends 100% to the latest Ready |
| 307 | * revision. |
| 308 | */ |
| 309 | traffic?: TrafficTarget[]; |
| 310 | /** |
| 311 | * Revision template. If omitted, a single container runs the public |
| 312 | * Cloud Run hello image. The Effect-native `main` form fills `image` |
| 313 | * for you. |
| 314 | */ |
| 315 | template?: RevisionTemplate; |
| 316 | /** |
| 317 | * Module entrypoint for an Effect-native service (typically |
| 318 | * `import.meta.url`). Alchemy bundles the program, builds a container |
| 319 | * image, pushes it to Artifact Registry, and deploys Cloud Run. |
| 320 | * Bindings attach env + IAM onto the runtime service account. |
| 321 | */ |
| 322 | main?: string; |
| 323 | /** |
| 324 | * Named export to load from `main`. |
| 325 | * @default "default" |
| 326 | */ |
| 327 | handler?: string; |
| 328 | /** |
| 329 | * HTTP port the Effect-native program listens on (Cloud Run injects |
| 330 | * `PORT`). Only used with `main`. |
| 331 | * @default 8080 |
| 332 | */ |
| 333 | port?: number; |
| 334 | /** |
| 335 | * Startup probe for the main container (`template.containers[0]`). |
| 336 | * Shorthand for setting it on the container. |
| 337 | */ |
| 338 | startupProbe?: Probe; |
| 339 | /** |
| 340 | * Liveness probe for the main container (`template.containers[0]`). |
| 341 | * Shorthand for setting it on the container. |
| 342 | */ |
| 343 | livenessProbe?: Probe; |
| 344 | /** |
| 345 | * Additional environment variables for the Effect-native container. |
| 346 | * Merged after binding-injected `env`. |
| 347 | */ |
| 348 | env?: Record<string, any>; |
| 349 | /** |
| 350 | * Bundler configuration for `main`. `install` lists packages |
| 351 | * `npm install`ed into an unbundled Node program image (see |
| 352 | * {@link extraFiles}); Next.js needs `next`. |
| 353 | */ |
| 354 | build?: Bundle.BundleConfig & { install?: PackageInstall }; |
| 355 | /** |
| 356 | * Host files or directories baked into the image next to `main` |
| 357 | * (`dest` is relative to `/app`; `"."` merges into `/app`). When set on |
| 358 | * an external (non-Effect) `main`, the program is not bundled: `main` |
| 359 | * is copied as-is and run by `node` on `node:26-slim`. Content-hashed, |
| 360 | * so a changed file rolls out a new revision. `GCP.Website.*` uses this |
| 361 | * to ship framework build output. |
| 362 | */ |
| 363 | extraFiles?: ReadonlyArray<ExtraFile>; |
| 364 | }; |
| 365 | |
| 366 | export type Service = Resource< |
| 367 | "GCP.Run.Service", |
| 368 | ServiceProps, |
| 369 | { |
| 370 | /** Full resource name `projects/{project}/locations/{location}/services/{service}`. */ |
| 371 | name: string; |
| 372 | /** Service id (last path segment). */ |
| 373 | serviceId: string; |
| 374 | /** Project id. */ |
| 375 | project: string; |
| 376 | /** Region (`us-central1`, …). */ |
| 377 | location: string; |
| 378 | /** User labels (Alchemy ownership labels stripped). */ |
| 379 | labels: Record<string, string>; |
| 380 | /** User annotations. */ |
| 381 | annotations: Record<string, string>; |
| 382 | /** Description. */ |
| 383 | description: string | undefined; |
| 384 | /** Main serving URI. */ |
| 385 | uri: string | undefined; |
| 386 | /** All serving URLs. */ |
| 387 | urls: ReadonlyArray<string>; |
| 388 | /** Server-assigned UUID. */ |
| 389 | uid: string | undefined; |
| 390 | /** Ingress setting. */ |
| 391 | ingress: string | undefined; |
| 392 | /** Whether the IAM invoker check is disabled. */ |
| 393 | invokerIamDisabled: boolean; |
| 394 | /** Latest created revision name. */ |
| 395 | latestCreatedRevision: string | undefined; |
| 396 | /** Latest Ready revision name. */ |
| 397 | latestReadyRevision: string | undefined; |
| 398 | /** Terminal condition state (`CONDITION_SUCCEEDED`, …). */ |
| 399 | terminalConditionState: string | undefined; |
| 400 | /** True while Cloud Run is still reconciling the desired state. */ |
| 401 | reconciling: boolean; |
| 402 | /** Observed generation. */ |
| 403 | generation: string | undefined; |
| 404 | /** RFC3339 creation timestamp. */ |
| 405 | createTime: string | undefined; |
| 406 | /** RFC3339 last-update timestamp. */ |
| 407 | updateTime: string | undefined; |
| 408 | /** Runtime service account email. */ |
| 409 | serviceAccount: string | undefined; |
| 410 | /** |
| 411 | * Numeric unique ID of the runtime service account: the `sub` of the |
| 412 | * Google ID tokens the host fetches. An AWS binding's IAM role trusts |
| 413 | * it, so the host reaches AWS without an access key. |
| 414 | */ |
| 415 | serviceAccountUniqueId: string | undefined; |
| 416 | /** True when Alchemy minted the per-host runtime service account. */ |
| 417 | managedServiceAccount: boolean; |
| 418 | /** IAM roles bindings granted to the runtime service account. */ |
| 419 | iamGrants: AppliedIamGrant[]; |
| 420 | /** Hash of the bundled `main` program and its bootstrap (Effect-native only). */ |
| 421 | codeHash: string | undefined; |
| 422 | }, |
| 423 | GcpHostBinding, |
| 424 | Providers |
| 425 | >; |
| 426 | |
| 427 | export type ServiceRuntimeContext = GcpHostRuntimeContext; |
| 428 | export type ServiceServices = Credentials | GcpEnvironment | ServerHost; |
| 429 | export type ServiceShape = Main<ServiceServices>; |
| 430 | |
| 431 | /** |
| 432 | * A Cloud Run service (Knative serving revision + traffic). |
| 433 | * |
| 434 | * Changing `serviceId` or `location` replaces the service. Updates to |
| 435 | * `template` create a new revision. |
| 436 | * |
| 437 | * This is GCP's effectful HTTP platform — the analog of |
| 438 | * `AWS.Lambda.Function` / `Cloudflare.Worker`. Pass `main` plus an |
| 439 | * Effect implementation; bindings grant IAM onto the runtime service |
| 440 | * account and inject env, the way AWS `policyStatements` land on the |
| 441 | * execution role. |
| 442 | * |
| 443 | * ### Creating a Service |
| 444 | * **Example:** Generated name, default hello image |
| 445 | * ```typescript |
| 446 | * const api = yield* GCP.Run.Service("api", {}); |
| 447 | * ``` |
| 448 | * |
| 449 | * **Example:** Explicit id, image, env, and labels |
| 450 | * ```typescript |
| 451 | * const api = yield* GCP.Run.Service("api", { |
| 452 | * serviceId: "order-api", |
| 453 | * location: "us-central1", |
| 454 | * description: "order HTTP API", |
| 455 | * labels: { env: "prod" }, |
| 456 | * ingress: "INGRESS_TRAFFIC_ALL", |
| 457 | * template: { |
| 458 | * timeout: "60s", |
| 459 | * containers: [ |
| 460 | * { |
| 461 | * image: "us-docker.pkg.dev/cloudrun/container/hello", |
| 462 | * env: [{ name: "ENV", value: "prod" }], |
| 463 | * }, |
| 464 | * ], |
| 465 | * }, |
| 466 | * }); |
| 467 | * ``` |
| 468 | * |
| 469 | * ### Health Probes and Sidecars |
| 470 | * **Example:** HTTP startup probe, with a proxy that starts after the app |
| 471 | * ```typescript |
| 472 | * const api = yield* GCP.Run.Service("api", { |
| 473 | * template: { |
| 474 | * containers: [ |
| 475 | * { |
| 476 | * name: "proxy", |
| 477 | * image: proxyImage, |
| 478 | * ports: [{ name: "h2c", containerPort: 8080 }], |
| 479 | * dependsOn: ["app"], |
| 480 | * }, |
| 481 | * { |
| 482 | * name: "app", |
| 483 | * image: appImage, |
| 484 | * startupProbe: { |
| 485 | * httpGet: { path: "/health", port: 3000 }, |
| 486 | * periodSeconds: 2, |
| 487 | * failureThreshold: 30, |
| 488 | * }, |
| 489 | * livenessProbe: { httpGet: { path: "/health", port: 3000 }, periodSeconds: 10 }, |
| 490 | * }, |
| 491 | * ], |
| 492 | * }, |
| 493 | * }); |
| 494 | * ``` |
| 495 | * |
| 496 | * **Example:** TCP and gRPC probes |
| 497 | * ```typescript |
| 498 | * startupProbe: { tcpSocket: { port: 5432 }, initialDelaySeconds: 5 }, |
| 499 | * livenessProbe: { grpc: { port: 9090, service: "health" }, timeoutSeconds: 3 }, |
| 500 | * ``` |
| 501 | * Changing a probe or `dependsOn` rolls a new revision. Removing |
| 502 | * `startupProbe` restores Cloud Run's default TCP probe. |
| 503 | * |
| 504 | * **Example:** Effect-native service with a sidecar |
| 505 | * ```typescript |
| 506 | * export class Api extends GCP.Run.Service<Api>()( |
| 507 | * "Api", |
| 508 | * { |
| 509 | * main: import.meta.url, |
| 510 | * template: { |
| 511 | * containers: [ |
| 512 | * { |
| 513 | * // image, ports and env are filled in from `main` |
| 514 | * startupProbe: { httpGet: { path: "/health" } }, |
| 515 | * dependsOn: ["cache"], |
| 516 | * }, |
| 517 | * { |
| 518 | * name: "cache", |
| 519 | * image: "docker.io/library/redis:7", |
| 520 | * startupProbe: { tcpSocket: { port: 6379 } }, |
| 521 | * }, |
| 522 | * ], |
| 523 | * }, |
| 524 | * }, |
| 525 | * Effect.gen(function* () { |
| 526 | * return { |
| 527 | * fetch: Effect.gen(function* () { |
| 528 | * const request = yield* HttpServerRequest; |
| 529 | * if (request.url === "/health") return HttpServerResponse.text("ok"); |
| 530 | * return HttpServerResponse.text("hello"); |
| 531 | * }), |
| 532 | * }; |
| 533 | * }), |
| 534 | * ) {} |
| 535 | * ``` |
| 536 | * The first container runs `main`; the rest deploy as sidecars. |
| 537 | * |
| 538 | * **Example:** An image service with an Effect-native sidecar |
| 539 | * ```typescript |
| 540 | * const worker = yield* Worker; // a GCP.Run.Container |
| 541 | * const api = yield* GCP.Run.Service("api", { |
| 542 | * template: { |
| 543 | * containers: [ |
| 544 | * { image: proxyImage, ports: [{ containerPort: 8080 }], dependsOn: [worker.name] }, |
| 545 | * worker, |
| 546 | * ], |
| 547 | * }, |
| 548 | * }); |
| 549 | * ``` |
| 550 | * A listed Container brings its bindings' roles and the sidecars it binds. |
| 551 | * `worker.name` is an Output that resolves to the container's name in the |
| 552 | * revision, so the proxy starts after it. |
| 553 | * |
| 554 | * ### Effect-native Function with bindings |
| 555 | * **Example:** Publish tweets to Pub/Sub, cache in Memorystore |
| 556 | * ```typescript |
| 557 | * const tweets = yield* GCP.PubSub.Topic("tweets", {}); |
| 558 | * const cache = yield* GCP.Redis.Instance("Cache", { memorySizeGb: 1 }); |
| 559 | * |
| 560 | * export class TweetBot extends GCP.Run.Service<TweetBot>()( |
| 561 | * "TweetBot", |
| 562 | * { main: import.meta.url }, |
| 563 | * Effect.gen(function* () { |
| 564 | * const publish = yield* GCP.PubSub.Publish(tweets); |
| 565 | * const redis = yield* GCP.Redis.ReadWriteRedis(cache); |
| 566 | * return { |
| 567 | * fetch: Effect.gen(function* () { |
| 568 | * const text = (yield* redis.get("last-tweet")) ?? "hello twitter"; |
| 569 | * yield* publish({ |
| 570 | * body: { messages: [{ data: btoa(text) }] }, |
| 571 | * }); |
| 572 | * return HttpServerResponse.text("queued"); |
| 573 | * }), |
| 574 | * }; |
| 575 | * }).pipe( |
| 576 | * Effect.provide([ |
| 577 | * GCP.PubSub.PublishHttp, |
| 578 | * GCP.Redis.ReadWriteRedisHttp, |
| 579 | * ]), |
| 580 | * ), |
| 581 | * ) {} |
| 582 | * ``` |
| 583 | * |
| 584 | * ### Calling AWS without keys |
| 585 | * An AWS binding gives the service an IAM role that trusts its runtime |
| 586 | * service account's Google ID tokens. The service assumes the role with |
| 587 | * `AssumeRoleWithWebIdentity`, so no AWS access key is created. |
| 588 | * |
| 589 | * **Example:** Send to an SQS queue |
| 590 | * ```typescript |
| 591 | * const jobs = yield* AWS.SQS.Queue("Jobs"); |
| 592 | * |
| 593 | * export class Api extends GCP.Run.Service<Api>()( |
| 594 | * "Api", |
| 595 | * { main: import.meta.url }, |
| 596 | * Effect.gen(function* () { |
| 597 | * const send = yield* AWS.SQS.SendMessage(jobs); |
| 598 | * return { |
| 599 | * fetch: send({ MessageBody: "hello" }).pipe( |
| 600 | * Effect.as(HttpServerResponse.text("sent")), |
| 601 | * ), |
| 602 | * }; |
| 603 | * }).pipe(Effect.provide(AWS.SQS.SendMessageHttp)), |
| 604 | * ) {} |
| 605 | * ``` |
| 606 | * |
| 607 | * ### Updating a Service |
| 608 | * **Example:** New revision |
| 609 | * ```typescript |
| 610 | * const api = yield* GCP.Run.Service("api", { |
| 611 | * template: { |
| 612 | * timeout: "120s", |
| 613 | * containers: [{ image: "us-docker.pkg.dev/cloudrun/container/hello" }], |
| 614 | * }, |
| 615 | * }); |
| 616 | * ``` |
| 617 | * Template changes create a new revision. The runtime service account is kept. |
| 618 | * |
| 619 | * ### Destroying a Service |
| 620 | * **Example:** `alchemy destroy` deletes the service and the minted `alch-*` service account. |
| 621 | * |
| 622 | * ### Reading a Service |
| 623 | * **Example:** Get the live service |
| 624 | * ```typescript |
| 625 | * const getService = yield* GCP.Run.GetService(api); |
| 626 | * const live = yield* getService(); |
| 627 | * ``` |
| 628 | * |
| 629 | * @resource |
| 630 | * @category Run |
| 631 | */ |
| 632 | export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> = |
| 633 | Platform("GCP.Run.Service", { |
| 634 | createRuntimeContext: createGcpHostRuntimeContext("GCP.Run.Service", { |
| 635 | rpc: "private", |
| 636 | }) as (id: string) => ServiceRuntimeContext, |
| 637 | }); |
| 638 | |
| 639 | export class ServiceNotResolved extends Data.TaggedError("GCP.Run.ServiceNotResolved")<{ |
| 640 | resourceName: string; |
| 641 | }> {} |
| 642 | |
| 643 | export class ServiceNotReady extends Data.TaggedError("GCP.Run.ServiceNotReady")<{ |
| 644 | resourceName: string; |
| 645 | state: string; |
| 646 | message: string; |
| 647 | }> {} |
| 648 | |
| 649 | export class ServiceReconciling extends Data.TaggedError("GCP.Run.ServiceReconciling")<{ |
| 650 | resourceName: string; |
| 651 | state: string; |
| 652 | }> {} |
| 653 | |
| 654 | /** |
| 655 | * The service returns RPC methods but `invokerIamDisabled` is set, so |
| 656 | * anyone could call them. |
| 657 | */ |
| 658 | export class ServiceRpcPublic extends Data.TaggedError("GCP.Run.ServiceRpcPublic")<{ |
| 659 | id: string; |
| 660 | }> { |
| 661 | override get message() { |
| 662 | return `GCP.Run.Service ${this.id} returns RPC methods but sets invokerIamDisabled, so they would be public. Keep the IAM invoker check on and call it with GCP.Run.InvokeService.`; |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | export class ServiceStillExists extends Data.TaggedError("GCP.Run.ServiceStillExists")<{ |
| 667 | resourceName: string; |
| 668 | }> {} |
| 669 | |
| 670 | const lastSegment = (value: string) => { |
| 671 | const trimmed = value.replace(/\/+$/, ""); |
| 672 | const parts = trimmed.split("/"); |
| 673 | return parts[parts.length - 1] || trimmed; |
| 674 | }; |
| 675 | |
| 676 | const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 677 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 678 | |
| 679 | const resourceName = (project: string, location: string, serviceId: string) => |
| 680 | `projects/${project}/locations/${location}/services/${serviceId}`; |
| 681 | |
| 682 | const parseName = (name: string, defaultLocation: string) => { |
| 683 | const parts = name.split("/").filter((part) => part.length > 0); |
| 684 | const servicesAt = parts.lastIndexOf("services"); |
| 685 | const locationsAt = parts.lastIndexOf("locations"); |
| 686 | const projectsAt = parts.lastIndexOf("projects"); |
| 687 | return { |
| 688 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 689 | location: |
| 690 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, |
| 691 | serviceId: |
| 692 | servicesAt >= 0 && parts[servicesAt + 1] ? parts[servicesAt + 1]! : lastSegment(name), |
| 693 | }; |
| 694 | }; |
| 695 | |
| 696 | const userLabels = ( |
| 697 | labels: Record<string, string | undefined> | null | undefined, |
| 698 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 699 | |
| 700 | const userAnnotations = ( |
| 701 | annotations: Record<string, string | undefined> | null | undefined, |
| 702 | ): Record<string, string> => tagRecord(annotations); |
| 703 | |
| 704 | const recordsEqual = (left: Record<string, string>, right: Record<string, string>) => { |
| 705 | const leftKeys = Object.keys(left).sort(); |
| 706 | const rightKeys = Object.keys(right).sort(); |
| 707 | return ( |
| 708 | leftKeys.length === rightKeys.length && |
| 709 | leftKeys.every((key, index) => key === rightKeys[index] && left[key] === right[key]) |
| 710 | ); |
| 711 | }; |
| 712 | |
| 713 | const rfc1035 = (name: string): string => { |
| 714 | let next = name |
| 715 | .toLowerCase() |
| 716 | .replace(/[^a-z0-9-]/g, "-") |
| 717 | .replace(/-+/g, "-") |
| 718 | .replace(/^-+|-+$/g, ""); |
| 719 | if (!/^[a-z]/.test(next)) next = `s${next}`; |
| 720 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 721 | return next.length > 0 ? next : "service"; |
| 722 | }; |
| 723 | |
| 724 | const toId = (id: string, serviceId: string | undefined, existing?: string) => |
| 725 | Effect.gen(function* () { |
| 726 | if (serviceId !== undefined) return serviceId; |
| 727 | if (existing !== undefined) return existing; |
| 728 | return rfc1035( |
| 729 | yield* createPhysicalName({ |
| 730 | id, |
| 731 | maxLength: MAX_NAME_LENGTH, |
| 732 | lowercase: true, |
| 733 | }), |
| 734 | ); |
| 735 | }); |
| 736 | |
| 737 | /** `GCP.Run.Container`s listed in the template, as their resolved attributes. */ |
| 738 | const declaredContainersOf = (news: ServiceProps): BoundContainer[] => |
| 739 | (news.template?.containers ?? []).filter(isContainerAttributes).map((container) => ({ |
| 740 | spec: container.spec, |
| 741 | iam: container.iam, |
| 742 | sidecars: container.sidecars, |
| 743 | })); |
| 744 | |
| 745 | const desiredTemplate = (news: ServiceProps): cloudrun.GoogleCloudRunV2RevisionTemplate => { |
| 746 | const template = news.template ?? {}; |
| 747 | // A listed `GCP.Run.Container` arrives resolved to its attributes, never |
| 748 | // as the resource the prop type names. |
| 749 | const containers = (template.containers ?? []).map((container): ContainerSpec => |
| 750 | isContainerAttributes(container) ? container.spec : (container as ContainerSpec), |
| 751 | ); |
| 752 | const [main = { image: DEFAULT_IMAGE }, ...rest] = containers; |
| 753 | return { |
| 754 | ...template, |
| 755 | containers: [ |
| 756 | { |
| 757 | ...main, |
| 758 | startupProbe: news.startupProbe ?? main.startupProbe, |
| 759 | livenessProbe: news.livenessProbe ?? main.livenessProbe, |
| 760 | }, |
| 761 | ...rest, |
| 762 | ], |
| 763 | }; |
| 764 | }; |
| 765 | |
| 766 | const normalizeDuration = (value: string | undefined) => { |
| 767 | if (value === undefined) return undefined; |
| 768 | const match = /^([0-9]+(?:\.[0-9]+)?)s$/.exec(value.trim()); |
| 769 | if (!match) return value; |
| 770 | return `${Number(match[1])}s`; |
| 771 | }; |
| 772 | |
| 773 | const envFingerprint = (env: cloudrun.GoogleCloudRunV2EnvVarList | undefined) => |
| 774 | JSON.stringify( |
| 775 | [...(env ?? [])] |
| 776 | .map((item) => ({ |
| 777 | name: item.name ?? "", |
| 778 | value: item.value ?? "", |
| 779 | secret: item.valueSource?.secretKeyRef?.secret ?? "", |
| 780 | version: item.valueSource?.secretKeyRef?.version ?? "", |
| 781 | })) |
| 782 | .sort((left, right) => left.name.localeCompare(right.name)), |
| 783 | ); |
| 784 | |
| 785 | // Cloud Run reports an unnamed port as `http1`. |
| 786 | const portsFingerprint = (ports: cloudrun.GoogleCloudRunV2ContainerPortList | undefined) => |
| 787 | JSON.stringify( |
| 788 | (ports ?? []).map((port) => ({ |
| 789 | name: port.name || "http1", |
| 790 | containerPort: port.containerPort ?? 0, |
| 791 | })), |
| 792 | ); |
| 793 | |
| 794 | // Cloud Run gives a serving container without a startup probe this one. |
| 795 | const DEFAULT_STARTUP_PROBE: cloudrun.GoogleCloudRunV2Probe = { |
| 796 | tcpSocket: {}, |
| 797 | timeoutSeconds: 240, |
| 798 | periodSeconds: 240, |
| 799 | failureThreshold: 1, |
| 800 | }; |
| 801 | |
| 802 | const probeFingerprint = ( |
| 803 | probe: cloudrun.GoogleCloudRunV2Probe | undefined, |
| 804 | container: cloudrun.GoogleCloudRunV2Container, |
| 805 | ) => { |
| 806 | if (probe === undefined) return ""; |
| 807 | const defaultPort = container.ports?.[0]?.containerPort ?? 8080; |
| 808 | return JSON.stringify({ |
| 809 | httpGet: |
| 810 | probe.httpGet === undefined |
| 811 | ? null |
| 812 | : { |
| 813 | path: probe.httpGet.path || "/", |
| 814 | port: probe.httpGet.port || defaultPort, |
| 815 | headers: (probe.httpGet.httpHeaders ?? []).map((header) => [ |
| 816 | header.name ?? "", |
| 817 | header.value ?? "", |
| 818 | ]), |
| 819 | }, |
| 820 | tcpSocket: probe.tcpSocket === undefined ? null : { port: probe.tcpSocket.port || defaultPort }, |
| 821 | grpc: |
| 822 | probe.grpc === undefined |
| 823 | ? null |
| 824 | : { port: probe.grpc.port || defaultPort, service: probe.grpc.service ?? "" }, |
| 825 | initialDelaySeconds: probe.initialDelaySeconds ?? 0, |
| 826 | timeoutSeconds: probe.timeoutSeconds ?? 1, |
| 827 | periodSeconds: probe.periodSeconds ?? 10, |
| 828 | failureThreshold: probe.failureThreshold ?? 3, |
| 829 | }); |
| 830 | }; |
| 831 | |
| 832 | // An omitted probe means the Cloud Run default, so a dropped probe still |
| 833 | // rolls a revision that resets it. |
| 834 | const startupProbeNeedsSync = ( |
| 835 | desired: cloudrun.GoogleCloudRunV2Container, |
| 836 | observed: cloudrun.GoogleCloudRunV2Container, |
| 837 | ) => { |
| 838 | const have = probeFingerprint(observed.startupProbe, observed); |
| 839 | if (desired.startupProbe !== undefined) { |
| 840 | return probeFingerprint(desired.startupProbe, desired) !== have; |
| 841 | } |
| 842 | return have !== "" && have !== probeFingerprint(DEFAULT_STARTUP_PROBE, observed); |
| 843 | }; |
| 844 | |
| 845 | const containerNeedsSync = ( |
| 846 | desired: cloudrun.GoogleCloudRunV2ContainerList | undefined, |
| 847 | observed: cloudrun.GoogleCloudRunV2ContainerList | undefined, |
| 848 | ) => { |
| 849 | const want = desired ?? []; |
| 850 | const have = observed ?? []; |
| 851 | if (want.length !== have.length) return true; |
| 852 | return want.some((container, index) => { |
| 853 | const current = have[index]; |
| 854 | if (current === undefined) return true; |
| 855 | if ((container.image ?? "") !== (current.image ?? "")) return true; |
| 856 | if ( |
| 857 | container.command !== undefined && |
| 858 | JSON.stringify(container.command) !== JSON.stringify(current.command ?? []) |
| 859 | ) { |
| 860 | return true; |
| 861 | } |
| 862 | if ( |
| 863 | container.args !== undefined && |
| 864 | JSON.stringify(container.args) !== JSON.stringify(current.args ?? []) |
| 865 | ) { |
| 866 | return true; |
| 867 | } |
| 868 | if (container.workingDir !== undefined && container.workingDir !== (current.workingDir ?? "")) { |
| 869 | return true; |
| 870 | } |
| 871 | if ( |
| 872 | container.env !== undefined && |
| 873 | envFingerprint(container.env) !== envFingerprint(current.env) |
| 874 | ) { |
| 875 | return true; |
| 876 | } |
| 877 | if ( |
| 878 | container.ports !== undefined && |
| 879 | portsFingerprint(container.ports) !== portsFingerprint(current.ports) |
| 880 | ) { |
| 881 | return true; |
| 882 | } |
| 883 | if (container.resources?.limits !== undefined) { |
| 884 | const wantLimits = tagRecord(container.resources.limits); |
| 885 | const haveLimits = tagRecord(current.resources?.limits); |
| 886 | for (const [key, value] of Object.entries(wantLimits)) { |
| 887 | if (haveLimits[key] !== value) return true; |
| 888 | } |
| 889 | } |
| 890 | if ( |
| 891 | container.resources?.cpuIdle !== undefined && |
| 892 | container.resources.cpuIdle !== current.resources?.cpuIdle |
| 893 | ) { |
| 894 | return true; |
| 895 | } |
| 896 | if ( |
| 897 | container.resources?.startupCpuBoost !== undefined && |
| 898 | container.resources.startupCpuBoost !== current.resources?.startupCpuBoost |
| 899 | ) { |
| 900 | return true; |
| 901 | } |
| 902 | if (container.name !== undefined && container.name !== (current.name ?? "")) { |
| 903 | return true; |
| 904 | } |
| 905 | if (startupProbeNeedsSync(container, current)) return true; |
| 906 | if ( |
| 907 | probeFingerprint(container.livenessProbe, container) !== |
| 908 | probeFingerprint(current.livenessProbe, current) |
| 909 | ) { |
| 910 | return true; |
| 911 | } |
| 912 | if (JSON.stringify(container.dependsOn ?? []) !== JSON.stringify(current.dependsOn ?? [])) { |
| 913 | return true; |
| 914 | } |
| 915 | if ( |
| 916 | container.volumeMounts !== undefined && |
| 917 | JSON.stringify( |
| 918 | container.volumeMounts.map((mount) => ({ |
| 919 | name: mount.name ?? "", |
| 920 | mountPath: mount.mountPath ?? "", |
| 921 | })), |
| 922 | ) !== |
| 923 | JSON.stringify( |
| 924 | (current.volumeMounts ?? []).map((mount) => ({ |
| 925 | name: mount.name ?? "", |
| 926 | mountPath: mount.mountPath ?? "", |
| 927 | })), |
| 928 | ) |
| 929 | ) { |
| 930 | return true; |
| 931 | } |
| 932 | return false; |
| 933 | }); |
| 934 | }; |
| 935 | |
| 936 | const scalingFingerprint = (scaling: ServiceScaling | undefined) => |
| 937 | JSON.stringify({ |
| 938 | min: scaling?.minInstanceCount ?? null, |
| 939 | max: scaling?.maxInstanceCount ?? null, |
| 940 | mode: scaling?.scalingMode ?? "", |
| 941 | manual: scaling?.manualInstanceCount ?? null, |
| 942 | }); |
| 943 | |
| 944 | const trafficFingerprint = (traffic: TrafficTarget[] | undefined) => |
| 945 | JSON.stringify( |
| 946 | (traffic ?? []).map((target) => ({ |
| 947 | type: target.type ?? "", |
| 948 | revision: target.revision ?? "", |
| 949 | percent: target.percent ?? 0, |
| 950 | tag: target.tag ?? "", |
| 951 | })), |
| 952 | ); |
| 953 | |
| 954 | const audiencesFingerprint = (audiences: string[] | undefined) => |
| 955 | JSON.stringify([...(audiences ?? [])].sort()); |
| 956 | |
| 957 | const templateNeedsSync = ( |
| 958 | desired: cloudrun.GoogleCloudRunV2RevisionTemplate, |
| 959 | observed: cloudrun.GoogleCloudRunV2RevisionTemplate | undefined, |
| 960 | ) => { |
| 961 | const current = observed ?? {}; |
| 962 | if (containerNeedsSync(desired.containers, current.containers)) { |
| 963 | return true; |
| 964 | } |
| 965 | if ( |
| 966 | desired.timeout !== undefined && |
| 967 | normalizeDuration(desired.timeout) !== normalizeDuration(current.timeout) |
| 968 | ) { |
| 969 | return true; |
| 970 | } |
| 971 | if ( |
| 972 | desired.maxInstanceRequestConcurrency !== undefined && |
| 973 | desired.maxInstanceRequestConcurrency !== (current.maxInstanceRequestConcurrency ?? 0) |
| 974 | ) { |
| 975 | return true; |
| 976 | } |
| 977 | if ( |
| 978 | desired.serviceAccount !== undefined && |
| 979 | desired.serviceAccount !== (current.serviceAccount ?? "") |
| 980 | ) { |
| 981 | return true; |
| 982 | } |
| 983 | if ( |
| 984 | desired.executionEnvironment !== undefined && |
| 985 | desired.executionEnvironment !== (current.executionEnvironment ?? "") |
| 986 | ) { |
| 987 | return true; |
| 988 | } |
| 989 | if ( |
| 990 | desired.sessionAffinity !== undefined && |
| 991 | desired.sessionAffinity !== (current.sessionAffinity === true) |
| 992 | ) { |
| 993 | return true; |
| 994 | } |
| 995 | if ( |
| 996 | desired.encryptionKey !== undefined && |
| 997 | desired.encryptionKey !== (current.encryptionKey ?? "") |
| 998 | ) { |
| 999 | return true; |
| 1000 | } |
| 1001 | if (desired.revision !== undefined && desired.revision !== (current.revision ?? "")) { |
| 1002 | return true; |
| 1003 | } |
| 1004 | if ( |
| 1005 | desired.scaling !== undefined && |
| 1006 | scalingFingerprint(desired.scaling) !== scalingFingerprint(current.scaling) |
| 1007 | ) { |
| 1008 | return true; |
| 1009 | } |
| 1010 | if ( |
| 1011 | desired.vpcAccess !== undefined && |
| 1012 | JSON.stringify(desired.vpcAccess) !== JSON.stringify(current.vpcAccess ?? {}) |
| 1013 | ) { |
| 1014 | return true; |
| 1015 | } |
| 1016 | if ( |
| 1017 | desired.volumes !== undefined && |
| 1018 | JSON.stringify(desired.volumes) !== JSON.stringify(current.volumes ?? []) |
| 1019 | ) { |
| 1020 | return true; |
| 1021 | } |
| 1022 | if ( |
| 1023 | desired.labels !== undefined && |
| 1024 | !recordsEqual(userAnnotations(desired.labels), userAnnotations(current.labels)) |
| 1025 | ) { |
| 1026 | return true; |
| 1027 | } |
| 1028 | if ( |
| 1029 | desired.annotations !== undefined && |
| 1030 | !recordsEqual(userAnnotations(desired.annotations), userAnnotations(current.annotations)) |
| 1031 | ) { |
| 1032 | return true; |
| 1033 | } |
| 1034 | return false; |
| 1035 | }; |
| 1036 | |
| 1037 | const HOST_TYPE = "GCP.Run.Service"; |
| 1038 | |
| 1039 | const toAttrs = ( |
| 1040 | service: cloudrun.GoogleCloudRunV2Service, |
| 1041 | project: string, |
| 1042 | region: string, |
| 1043 | extras: { |
| 1044 | iamGrants?: AppliedIamGrant[]; |
| 1045 | codeHash?: string; |
| 1046 | serviceAccountUniqueId?: string; |
| 1047 | } = {}, |
| 1048 | ): Service["Attributes"] => { |
| 1049 | const name = service.name ?? ""; |
| 1050 | const parsed = parseName(name, region); |
| 1051 | return { |
| 1052 | name, |
| 1053 | serviceId: parsed.serviceId, |
| 1054 | project: parsed.project || project, |
| 1055 | location: parsed.location, |
| 1056 | labels: userLabels(service.labels), |
| 1057 | annotations: userAnnotations(service.annotations), |
| 1058 | description: service.description, |
| 1059 | uri: service.uri, |
| 1060 | urls: service.urls ?? [], |
| 1061 | uid: service.uid, |
| 1062 | ingress: service.ingress, |
| 1063 | invokerIamDisabled: service.invokerIamDisabled === true, |
| 1064 | latestCreatedRevision: service.latestCreatedRevision, |
| 1065 | latestReadyRevision: service.latestReadyRevision, |
| 1066 | terminalConditionState: service.terminalCondition?.state, |
| 1067 | reconciling: service.reconciling === true, |
| 1068 | generation: service.generation, |
| 1069 | createTime: service.createTime, |
| 1070 | updateTime: service.updateTime, |
| 1071 | serviceAccount: service.template?.serviceAccount, |
| 1072 | managedServiceAccount: isManagedServiceAccount({ |
| 1073 | project: parsed.project || project, |
| 1074 | hostType: HOST_TYPE, |
| 1075 | resourceName: name, |
| 1076 | serviceAccount: service.template?.serviceAccount, |
| 1077 | }), |
| 1078 | serviceAccountUniqueId: extras.serviceAccountUniqueId, |
| 1079 | iamGrants: extras.iamGrants ?? [], |
| 1080 | codeHash: extras.codeHash, |
| 1081 | }; |
| 1082 | }; |
| 1083 | |
| 1084 | const bootstrapFor = (news: ServiceProps) => |
| 1085 | makeGcpBootstrap("CloudRun", news.handler ?? "default"); |
| 1086 | |
| 1087 | const sourceOf = (news: ServiceProps, main: string) => ({ |
| 1088 | main, |
| 1089 | handler: news.handler ?? "default", |
| 1090 | build: news.build, |
| 1091 | extraFiles: news.extraFiles, |
| 1092 | install: news.build?.install, |
| 1093 | }); |
| 1094 | |
| 1095 | const getByName = (name: string) => |
| 1096 | cloudrun |
| 1097 | .getProjectsLocationsServices({ name }) |
| 1098 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 1099 | |
| 1100 | /** Waits on a Cloud Run long-running operation (revisions roll out in minutes). */ |
| 1101 | const waitForOperation = ( |
| 1102 | operation: cloudrun.GoogleLongrunningOperation, |
| 1103 | options?: { notFoundOk?: boolean }, |
| 1104 | ) => |
| 1105 | waitForLongRunningOperation( |
| 1106 | operation, |
| 1107 | (name) => { |
| 1108 | const get = cloudrun.getProjectsLocationsOperations({ name }); |
| 1109 | return options?.notFoundOk === true |
| 1110 | ? get.pipe( |
| 1111 | Effect.catchTag("NotFound", () => |
| 1112 | Effect.succeed<LongRunningOperation>({ name, done: true }), |
| 1113 | ), |
| 1114 | ) |
| 1115 | : get.pipe( |
| 1116 | // A just-returned operation can briefly 404 on read. |
| 1117 | Effect.retry({ |
| 1118 | while: (error) => error._tag === "NotFound", |
| 1119 | times: 5, |
| 1120 | schedule: Schedule.exponential("250 millis"), |
| 1121 | }), |
| 1122 | ); |
| 1123 | }, |
| 1124 | { budget: "10 minutes" }, |
| 1125 | ).pipe( |
| 1126 | // google.rpc.Code NOT_FOUND: the resource was already gone. |
| 1127 | Effect.catchTag("GCP.OperationFailed", (error) => |
| 1128 | options?.notFoundOk === true && error.code === 5 |
| 1129 | ? Effect.succeed<LongRunningOperation>(operation) |
| 1130 | : Effect.fail(error), |
| 1131 | ), |
| 1132 | ); |
| 1133 | |
| 1134 | const isPendingService = (service: cloudrun.GoogleCloudRunV2Service) => { |
| 1135 | const state = service.terminalCondition?.state ?? ""; |
| 1136 | return ( |
| 1137 | service.reconciling === true || |
| 1138 | state === "CONDITION_PENDING" || |
| 1139 | state === "CONDITION_RECONCILING" || |
| 1140 | state === "" || |
| 1141 | state === "STATE_UNSPECIFIED" |
| 1142 | ); |
| 1143 | }; |
| 1144 | |
| 1145 | const waitUntilReady = (name: string) => |
| 1146 | getByName(name).pipe( |
| 1147 | Effect.filterOrFail( |
| 1148 | (service): service is cloudrun.GoogleCloudRunV2Service => |
| 1149 | service !== undefined && service.deleteTime === undefined, |
| 1150 | () => new ServiceNotResolved({ resourceName: name }), |
| 1151 | ), |
| 1152 | Effect.filterOrFail( |
| 1153 | (service) => (service.terminalCondition?.state ?? "") !== "CONDITION_FAILED", |
| 1154 | (service) => |
| 1155 | new ServiceNotReady({ |
| 1156 | resourceName: name, |
| 1157 | state: service.terminalCondition?.state ?? "", |
| 1158 | message: service.terminalCondition?.message ?? "revision failed", |
| 1159 | }), |
| 1160 | ), |
| 1161 | Effect.filterOrFail( |
| 1162 | (service) => !isPendingService(service), |
| 1163 | (service) => |
| 1164 | new ServiceReconciling({ |
| 1165 | resourceName: name, |
| 1166 | state: service.terminalCondition?.state || "reconciling", |
| 1167 | }), |
| 1168 | ), |
| 1169 | Effect.retry({ |
| 1170 | while: (error) => |
| 1171 | error._tag === "GCP.Run.ServiceReconciling" || error._tag === "GCP.Run.ServiceNotResolved", |
| 1172 | times: 10, |
| 1173 | schedule: Schedule.spaced("4 seconds"), |
| 1174 | }), |
| 1175 | ); |
| 1176 | |
| 1177 | const waitUntilGone = (name: string) => |
| 1178 | getByName(name).pipe( |
| 1179 | Effect.flatMap((service) => |
| 1180 | service === undefined |
| 1181 | ? Effect.void |
| 1182 | : Effect.fail(new ServiceStillExists({ resourceName: name })), |
| 1183 | ), |
| 1184 | Effect.retry({ |
| 1185 | while: (error) => error._tag === "GCP.Run.ServiceStillExists", |
| 1186 | times: 10, |
| 1187 | schedule: Schedule.spaced("2 seconds"), |
| 1188 | }), |
| 1189 | ); |
| 1190 | |
| 1191 | const toCreateBody = ( |
| 1192 | news: ServiceProps, |
| 1193 | labels: Record<string, string>, |
| 1194 | template: cloudrun.GoogleCloudRunV2RevisionTemplate, |
| 1195 | ): cloudrun.GoogleCloudRunV2Service => ({ |
| 1196 | labels, |
| 1197 | annotations: news.annotations, |
| 1198 | description: news.description, |
| 1199 | ingress: news.ingress, |
| 1200 | invokerIamDisabled: news.invokerIamDisabled, |
| 1201 | defaultUriDisabled: news.defaultUriDisabled, |
| 1202 | iapEnabled: news.iapEnabled, |
| 1203 | customAudiences: news.customAudiences, |
| 1204 | scaling: news.scaling, |
| 1205 | traffic: news.traffic, |
| 1206 | template, |
| 1207 | }); |
| 1208 | |
| 1209 | export const ServiceProvider = () => |
| 1210 | Provider.succeed(Service, { |
| 1211 | stables: ["name", "serviceId", "project", "location", "uid", "createTime"], |
| 1212 | |
| 1213 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 1214 | if (!isResolved(news)) return undefined; |
| 1215 | const env = yield* GcpEnvironment.current; |
| 1216 | const previousId = olds?.serviceId ?? output?.serviceId; |
| 1217 | const nextId = news.serviceId ?? previousId; |
| 1218 | const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 1219 | const nextLocation = normalizeLocation(news.location ?? output?.location, env.region); |
| 1220 | const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId; |
| 1221 | const locationChanged = previousLocation !== nextLocation; |
| 1222 | if (idChanged || locationChanged) { |
| 1223 | return { action: "replace" as const, deleteFirst: false }; |
| 1224 | } |
| 1225 | // A code-only change leaves the props untouched; hash the bundled |
| 1226 | // program (and bootstrap) so it still surfaces as an update. |
| 1227 | if (output !== undefined && news.main !== undefined) { |
| 1228 | const images = yield* makeImageSource; |
| 1229 | const hash = yield* images.hash({ |
| 1230 | source: sourceOf(news, news.main), |
| 1231 | port: news.port ?? 8080, |
| 1232 | isExternal: news.isExternal, |
| 1233 | bootstrap: bootstrapFor(news), |
| 1234 | }); |
| 1235 | if (hash !== undefined && hash !== output.codeHash) { |
| 1236 | return { action: "update" as const }; |
| 1237 | } |
| 1238 | } |
| 1239 | return undefined; |
| 1240 | }), |
| 1241 | |
| 1242 | read: Effect.fn(function* ({ id, olds, output }) { |
| 1243 | const env = yield* GcpEnvironment.current; |
| 1244 | const serviceId = yield* toId(id, olds?.serviceId, output?.serviceId); |
| 1245 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 1246 | const name = output?.name ?? resourceName(env.project, location, serviceId); |
| 1247 | const existing = yield* getByName(name); |
| 1248 | if (existing === undefined || existing.deleteTime !== undefined) { |
| 1249 | return undefined; |
| 1250 | } |
| 1251 | const attrs = toAttrs(existing, env.project, env.region, { |
| 1252 | iamGrants: output?.iamGrants, |
| 1253 | codeHash: output?.codeHash, |
| 1254 | serviceAccountUniqueId: output?.serviceAccountUniqueId, |
| 1255 | }); |
| 1256 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 1257 | }), |
| 1258 | |
| 1259 | list: () => |
| 1260 | Effect.gen(function* () { |
| 1261 | const env = yield* GcpEnvironment.current; |
| 1262 | return yield* cloudrun.listProjectsLocationsServices |
| 1263 | .pages({ |
| 1264 | parent: `projects/${env.project}/locations/-`, |
| 1265 | pageSize: 1000, |
| 1266 | }) |
| 1267 | .pipe( |
| 1268 | Stream.flatMap((page) => Stream.fromIterable(page.services ?? [])), |
| 1269 | Stream.filter( |
| 1270 | (service) => |
| 1271 | service.deleteTime === undefined && |
| 1272 | Object.keys(service.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 1273 | ), |
| 1274 | Stream.map((service) => toAttrs(service, env.project, env.region)), |
| 1275 | Stream.runCollect, |
| 1276 | Effect.map((chunk) => Array.from(chunk)), |
| 1277 | ); |
| 1278 | }), |
| 1279 | |
| 1280 | reconcile: Effect.fn(function* ({ id, news, output, bindings, session }) { |
| 1281 | if (news.invokerIamDisabled === true && news.env?.[RPC_METHODS_ENV] !== undefined) { |
| 1282 | return yield* new ServiceRpcPublic({ id }); |
| 1283 | } |
| 1284 | const env = yield* GcpEnvironment.current; |
| 1285 | const serviceId = yield* toId(id, news.serviceId, output?.serviceId); |
| 1286 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 1287 | const name = resourceName(env.project, location, serviceId); |
| 1288 | const parent = `projects/${env.project}/locations/${location}`; |
| 1289 | const desiredLabels = { |
| 1290 | ...toLabels(news.labels), |
| 1291 | ...(yield* createInternalLabels(id)), |
| 1292 | }; |
| 1293 | const desiredAnnotations = news.annotations; |
| 1294 | const template = desiredTemplate(news); |
| 1295 | const hostBindings = bindings as ResourceBinding<GcpHostBinding>[]; |
| 1296 | // Bound sidecars run as this service's account, so their bindings' |
| 1297 | // roles are granted to it. |
| 1298 | // Bound sidecars, plus the sidecars of Containers listed in the |
| 1299 | // template. Listed Containers are already in `template`. |
| 1300 | const declaredContainers = declaredContainersOf(news); |
| 1301 | const declaredNames = new Set(declaredContainers.map((container) => container.spec.name)); |
| 1302 | const boundContainers = flattenContainers([ |
| 1303 | ...boundContainersOf(hostBindings), |
| 1304 | ...declaredContainers.flatMap((container) => container.sidecars), |
| 1305 | ]).filter((container) => !declaredNames.has(container.spec.name)); |
| 1306 | const identity = yield* resolveHostIdentity({ |
| 1307 | project: env.project, |
| 1308 | hostType: HOST_TYPE, |
| 1309 | resourceName: name, |
| 1310 | userServiceAccount: template.serviceAccount, |
| 1311 | effectNative: news.main !== undefined, |
| 1312 | bindings: [ |
| 1313 | ...hostBindings, |
| 1314 | ...[...declaredContainers, ...boundContainers].map((container) => ({ |
| 1315 | sid: `GCP.Run.Container(${container.spec.name})`, |
| 1316 | data: { iam: container.iam }, |
| 1317 | })), |
| 1318 | ], |
| 1319 | output, |
| 1320 | }); |
| 1321 | template.serviceAccount = identity.serviceAccount; |
| 1322 | let codeHash: string | undefined; |
| 1323 | if (news.main !== undefined) { |
| 1324 | const images = yield* makeImageSource; |
| 1325 | const port = news.port ?? 8080; |
| 1326 | const image = yield* images |
| 1327 | .resolve({ |
| 1328 | id, |
| 1329 | source: sourceOf(news, news.main), |
| 1330 | repositoryName: rfc1035(`${serviceId}-src`), |
| 1331 | location, |
| 1332 | port, |
| 1333 | isExternal: news.isExternal, |
| 1334 | bootstrap: bootstrapFor(news), |
| 1335 | session, |
| 1336 | }) |
| 1337 | .pipe(Effect.onError(() => identity.cleanup)); |
| 1338 | codeHash = image.codeHash; |
| 1339 | const [container = {}, ...sidecars] = template.containers ?? []; |
| 1340 | template.containers = [ |
| 1341 | { |
| 1342 | ...container, |
| 1343 | image: image.imageUri, |
| 1344 | ports: container.ports ?? [{ containerPort: port }], |
| 1345 | env: mergeContainerEnv(container.env, identity.env, yield* alchemyRuntimeEnv, news.env), |
| 1346 | }, |
| 1347 | ...sidecars, |
| 1348 | ]; |
| 1349 | } else { |
| 1350 | const runtimeEnv = { ...identity.env, ...news.env }; |
| 1351 | if (Object.keys(runtimeEnv).length > 0 && template.containers) { |
| 1352 | template.containers = template.containers.map((container, index) => |
| 1353 | index === 0 |
| 1354 | ? { |
| 1355 | ...container, |
| 1356 | env: mergeContainerEnv(container.env, runtimeEnv), |
| 1357 | } |
| 1358 | : container, |
| 1359 | ); |
| 1360 | } |
| 1361 | } |
| 1362 | |
| 1363 | if (boundContainers.length > 0) { |
| 1364 | const [main = {}, ...rest] = template.containers ?? []; |
| 1365 | const declared = new Set(rest.map((container) => container.name)); |
| 1366 | const dependsOn = [ |
| 1367 | ...new Set([...(main.dependsOn ?? []), ...directContainerNames(hostBindings)]), |
| 1368 | ]; |
| 1369 | template.containers = [ |
| 1370 | { ...main, dependsOn }, |
| 1371 | ...rest, |
| 1372 | ...boundContainers |
| 1373 | .filter((container) => !declared.has(container.spec.name)) |
| 1374 | .map((container) => container.spec), |
| 1375 | ]; |
| 1376 | } |
| 1377 | |
| 1378 | const mounted = mountCloudSqlInstances(template, hostBindings); |
| 1379 | template.volumes = mounted.volumes; |
| 1380 | template.containers = mounted.containers; |
| 1381 | |
| 1382 | let current = yield* getByName(name); |
| 1383 | if (current?.deleteTime !== undefined) { |
| 1384 | yield* waitUntilGone(name); |
| 1385 | current = undefined; |
| 1386 | } |
| 1387 | |
| 1388 | if (current === undefined) { |
| 1389 | const created = yield* cloudrun |
| 1390 | .createProjectsLocationsServices({ |
| 1391 | parent, |
| 1392 | serviceId, |
| 1393 | body: toCreateBody(news, desiredLabels, template), |
| 1394 | }) |
| 1395 | .pipe( |
| 1396 | retryActAs, |
| 1397 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 1398 | Effect.onError(() => identity.cleanup), |
| 1399 | ); |
| 1400 | if (created !== undefined) { |
| 1401 | yield* waitForOperation(created); |
| 1402 | } |
| 1403 | current = yield* waitUntilReady(name); |
| 1404 | } |
| 1405 | |
| 1406 | if (current === undefined) { |
| 1407 | return yield* new ServiceNotResolved({ resourceName: name }); |
| 1408 | } |
| 1409 | |
| 1410 | const observedLabels = tagRecord(current.labels); |
| 1411 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 1412 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 1413 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 1414 | const annotationsChanged = |
| 1415 | desiredAnnotations !== undefined && |
| 1416 | !recordsEqual(userAnnotations(current.annotations), userAnnotations(desiredAnnotations)); |
| 1417 | const ingressChanged = news.ingress !== undefined && (current.ingress ?? "") !== news.ingress; |
| 1418 | const invokerChanged = |
| 1419 | news.invokerIamDisabled !== undefined && |
| 1420 | (current.invokerIamDisabled === true) !== news.invokerIamDisabled; |
| 1421 | const defaultUriChanged = |
| 1422 | news.defaultUriDisabled !== undefined && |
| 1423 | (current.defaultUriDisabled === true) !== news.defaultUriDisabled; |
| 1424 | const iapChanged = |
| 1425 | news.iapEnabled !== undefined && (current.iapEnabled === true) !== news.iapEnabled; |
| 1426 | const audiencesChanged = |
| 1427 | news.customAudiences !== undefined && |
| 1428 | audiencesFingerprint(current.customAudiences) !== |
| 1429 | audiencesFingerprint(news.customAudiences); |
| 1430 | const scalingChanged = |
| 1431 | news.scaling !== undefined && |
| 1432 | scalingFingerprint(current.scaling) !== scalingFingerprint(news.scaling); |
| 1433 | const trafficChanged = |
| 1434 | news.traffic !== undefined && |
| 1435 | trafficFingerprint(current.traffic) !== trafficFingerprint(news.traffic); |
| 1436 | const templateChanged = templateNeedsSync(template, current.template); |
| 1437 | |
| 1438 | if ( |
| 1439 | labelsChanged || |
| 1440 | descriptionChanged || |
| 1441 | annotationsChanged || |
| 1442 | ingressChanged || |
| 1443 | invokerChanged || |
| 1444 | defaultUriChanged || |
| 1445 | iapChanged || |
| 1446 | audiencesChanged || |
| 1447 | scalingChanged || |
| 1448 | trafficChanged || |
| 1449 | templateChanged |
| 1450 | ) { |
| 1451 | const updateMask = [ |
| 1452 | labelsChanged ? "labels" : undefined, |
| 1453 | descriptionChanged ? "description" : undefined, |
| 1454 | annotationsChanged ? "annotations" : undefined, |
| 1455 | ingressChanged ? "ingress" : undefined, |
| 1456 | invokerChanged ? "invokerIamDisabled" : undefined, |
| 1457 | defaultUriChanged ? "defaultUriDisabled" : undefined, |
| 1458 | iapChanged ? "iapEnabled" : undefined, |
| 1459 | audiencesChanged ? "customAudiences" : undefined, |
| 1460 | scalingChanged ? "scaling" : undefined, |
| 1461 | trafficChanged ? "traffic" : undefined, |
| 1462 | templateChanged ? "template" : undefined, |
| 1463 | ].filter((field): field is string => field !== undefined); |
| 1464 | |
| 1465 | const patched = yield* cloudrun.patchProjectsLocationsServices({ |
| 1466 | name, |
| 1467 | updateMask: updateMask.join(","), |
| 1468 | body: { |
| 1469 | name, |
| 1470 | labels: desiredLabels, |
| 1471 | description: news.description, |
| 1472 | annotations: desiredAnnotations, |
| 1473 | ingress: news.ingress, |
| 1474 | invokerIamDisabled: news.invokerIamDisabled, |
| 1475 | defaultUriDisabled: news.defaultUriDisabled, |
| 1476 | iapEnabled: news.iapEnabled, |
| 1477 | customAudiences: news.customAudiences, |
| 1478 | scaling: news.scaling, |
| 1479 | traffic: news.traffic, |
| 1480 | template, |
| 1481 | }, |
| 1482 | }); |
| 1483 | yield* waitForOperation(patched); |
| 1484 | current = yield* waitUntilReady(name); |
| 1485 | } |
| 1486 | |
| 1487 | if (current === undefined) { |
| 1488 | return yield* new ServiceNotResolved({ resourceName: name }); |
| 1489 | } |
| 1490 | |
| 1491 | return toAttrs(current, env.project, env.region, { |
| 1492 | iamGrants: identity.grants, |
| 1493 | codeHash, |
| 1494 | serviceAccountUniqueId: identity.uniqueId, |
| 1495 | }); |
| 1496 | }), |
| 1497 | |
| 1498 | delete: Effect.fn(function* ({ id, output }) { |
| 1499 | const operation = yield* cloudrun.deleteProjectsLocationsServices({ name: output.name }).pipe( |
| 1500 | Effect.retry({ |
| 1501 | while: (error) => error._tag === "Conflict", |
| 1502 | times: 8, |
| 1503 | schedule: Schedule.spaced("2 seconds"), |
| 1504 | }), |
| 1505 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 1506 | ); |
| 1507 | if (operation !== undefined) { |
| 1508 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 1509 | } |
| 1510 | yield* waitUntilGone(output.name); |
| 1511 | // Effect-native hosts build into a per-host repository on reconcile. |
| 1512 | yield* destroyHostImageRepository(id, output, rfc1035(`${output.serviceId}-src`)); |
| 1513 | yield* releaseHostIdentity(output); |
| 1514 | }), |
| 1515 | }); |