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 | sameJson, |
| 21 | toPhysicalName, |
| 22 | } from "./internal.ts"; |
| 23 | |
| 24 | export type RegionBackendBucketProps = { |
| 25 | /** |
| 26 | * Name of the backend bucket. If omitted, a unique RFC1035 name is |
| 27 | * generated from the stack, stage, and logical id. Changing this |
| 28 | * replaces the resource. |
| 29 | */ |
| 30 | name?: string; |
| 31 | /** |
| 32 | * Region the backend bucket lives in. Immutable — changing it replaces |
| 33 | * the resource. `US-CENTRAL1` is accepted and normalized to |
| 34 | * `us-central1`. |
| 35 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 36 | */ |
| 37 | region?: string; |
| 38 | /** |
| 39 | * Cloud Storage bucket this backend serves. The bucket must already |
| 40 | * exist in the same project. |
| 41 | */ |
| 42 | bucketName: string; |
| 43 | /** |
| 44 | * Optional textual description. Alchemy ownership is stamped into the |
| 45 | * stored description; this field is the user-facing portion. |
| 46 | */ |
| 47 | description?: string; |
| 48 | /** |
| 49 | * Enable Cloud CDN for this backend bucket. Cannot be true when |
| 50 | * `loadBalancingScheme` is `INTERNAL_MANAGED`. |
| 51 | * @default false |
| 52 | */ |
| 53 | enableCdn?: boolean; |
| 54 | /** |
| 55 | * Compress text responses using Brotli or gzip based on |
| 56 | * `Accept-Encoding`. |
| 57 | */ |
| 58 | compressionMode?: "AUTOMATIC" | "DISABLED"; |
| 59 | /** |
| 60 | * Headers the Application Load Balancer should add to proxied |
| 61 | * responses, e.g. `"X-Frame-Options: DENY"`. |
| 62 | */ |
| 63 | customResponseHeaders?: string[]; |
| 64 | /** |
| 65 | * Load balancing scheme. Regional backend buckets require this field; |
| 66 | * Alchemy defaults it to `EXTERNAL_MANAGED`. Changing this replaces |
| 67 | * the resource. |
| 68 | * @default "EXTERNAL_MANAGED" |
| 69 | */ |
| 70 | loadBalancingScheme?: "EXTERNAL_MANAGED" | "INTERNAL_MANAGED"; |
| 71 | /** |
| 72 | * Cloud CDN policy. Only applied when set; omitted values leave the |
| 73 | * observed policy in place. |
| 74 | */ |
| 75 | cdnPolicy?: compute.BackendBucketCdnPolicy; |
| 76 | }; |
| 77 | |
| 78 | export type RegionBackendBucket = Resource< |
| 79 | "GCP.Compute.RegionBackendBucket", |
| 80 | RegionBackendBucketProps, |
| 81 | { |
| 82 | /** RFC1035 resource name. */ |
| 83 | name: string; |
| 84 | /** Cloud Storage bucket name. */ |
| 85 | bucketName: string; |
| 86 | /** Project id. */ |
| 87 | project: string; |
| 88 | /** Region short name (`us-central1`). */ |
| 89 | region: string; |
| 90 | /** User-facing description (Alchemy ownership marker stripped). */ |
| 91 | description: string | undefined; |
| 92 | /** Whether Cloud CDN is enabled. */ |
| 93 | enableCdn: boolean; |
| 94 | /** Compression mode, if set. */ |
| 95 | compressionMode: string | undefined; |
| 96 | /** Response headers added by the load balancer. */ |
| 97 | customResponseHeaders: string[]; |
| 98 | /** Load balancing scheme, if set. */ |
| 99 | loadBalancingScheme: string | undefined; |
| 100 | /** Cloud CDN policy, if configured. */ |
| 101 | cdnPolicy: compute.BackendBucketCdnPolicy | undefined; |
| 102 | /** Server-defined resource URL. */ |
| 103 | selfLink: string | undefined; |
| 104 | /** RFC3339 creation timestamp. */ |
| 105 | creationTimestamp: string | undefined; |
| 106 | /** Server-assigned numeric id. */ |
| 107 | id: string | undefined; |
| 108 | }, |
| 109 | never, |
| 110 | Providers |
| 111 | >; |
| 112 | |
| 113 | /** |
| 114 | * A regional Compute Engine backend bucket that fronts a Cloud Storage |
| 115 | * bucket for HTTP(S) load balancing. |
| 116 | * |
| 117 | * Compute Engine backend buckets have no labels field, so Alchemy |
| 118 | * stamps ownership into the description (`[alchemy alchemy-stack=… |
| 119 | * alchemy-stage=… alchemy-id=…]`) so `list` / `pnpm nuke:gcp` can find |
| 120 | * them. |
| 121 | * |
| 122 | * ### Creating a Region Backend Bucket |
| 123 | * **Example:** Generated name in front of a Storage bucket |
| 124 | * ```typescript |
| 125 | * const assets = yield* GCP.Storage.Bucket("assets", { |
| 126 | * forceDestroy: true, |
| 127 | * }); |
| 128 | * const backend = yield* GCP.Compute.RegionBackendBucket("cdn", { |
| 129 | * bucketName: assets.bucketName, |
| 130 | * description: "static assets", |
| 131 | * }); |
| 132 | * ``` |
| 133 | * |
| 134 | * **Example:** Explicit name with Cloud CDN |
| 135 | * ```typescript |
| 136 | * const backend = yield* GCP.Compute.RegionBackendBucket("cdn", { |
| 137 | * name: "app-static", |
| 138 | * region: "us-central1", |
| 139 | * bucketName: assets.bucketName, |
| 140 | * enableCdn: true, |
| 141 | * compressionMode: "AUTOMATIC", |
| 142 | * }); |
| 143 | * ``` |
| 144 | * |
| 145 | * @resource |
| 146 | * @category Compute |
| 147 | */ |
| 148 | export const RegionBackendBucket = Resource<RegionBackendBucket>("GCP.Compute.RegionBackendBucket"); |
| 149 | |
| 150 | export class RegionBackendBucketNotResolved extends Data.TaggedError( |
| 151 | "GCP.Compute.RegionBackendBucketNotResolved", |
| 152 | )<{ |
| 153 | resourceName: string; |
| 154 | region: string; |
| 155 | }> {} |
| 156 | |
| 157 | const DEFAULT_LOAD_BALANCING_SCHEME = "EXTERNAL_MANAGED" as const; |
| 158 | |
| 159 | const sameList = ( |
| 160 | left: readonly string[] | undefined, |
| 161 | right: readonly string[] | undefined, |
| 162 | ): boolean => sameJson(left ?? [], right ?? []); |
| 163 | |
| 164 | const normalizeCdnPolicy = ( |
| 165 | policy: compute.BackendBucketCdnPolicy | undefined, |
| 166 | ): compute.BackendBucketCdnPolicy | undefined => { |
| 167 | if (policy === undefined) return undefined; |
| 168 | const { signedUrlKeyNames: _signed, ...rest } = policy; |
| 169 | return rest; |
| 170 | }; |
| 171 | |
| 172 | const toAttrs = ( |
| 173 | bucket: compute.BackendBucket, |
| 174 | project: string, |
| 175 | ): RegionBackendBucket["Attributes"] => { |
| 176 | const parsed = parseDescription(bucket.description); |
| 177 | return { |
| 178 | name: bucket.name ?? lastSegment(bucket.selfLink), |
| 179 | bucketName: bucket.bucketName ?? "", |
| 180 | project, |
| 181 | region: lastSegment(bucket.region).toLowerCase(), |
| 182 | description: parsed.description, |
| 183 | enableCdn: bucket.enableCdn === true, |
| 184 | compressionMode: bucket.compressionMode, |
| 185 | customResponseHeaders: bucket.customResponseHeaders ?? [], |
| 186 | loadBalancingScheme: bucket.loadBalancingScheme, |
| 187 | cdnPolicy: bucket.cdnPolicy, |
| 188 | selfLink: bucket.selfLink, |
| 189 | creationTimestamp: bucket.creationTimestamp, |
| 190 | id: bucket.id, |
| 191 | }; |
| 192 | }; |
| 193 | |
| 194 | const getByName = (project: string, region: string, name: string) => |
| 195 | compute |
| 196 | .getRegionBackendBuckets({ project, region, backendBucket: name }) |
| 197 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 198 | |
| 199 | const awaitResource = (project: string, region: string, name: string) => |
| 200 | getByName(project, region, name).pipe( |
| 201 | Effect.flatMap((bucket) => |
| 202 | bucket !== undefined |
| 203 | ? Effect.succeed(bucket) |
| 204 | : Effect.fail(new RegionBackendBucketNotResolved({ resourceName: name, region })), |
| 205 | ), |
| 206 | Effect.retry({ |
| 207 | while: (error) => error._tag === "GCP.Compute.RegionBackendBucketNotResolved", |
| 208 | times: 8, |
| 209 | schedule: Schedule.spaced("1 second"), |
| 210 | }), |
| 211 | ); |
| 212 | |
| 213 | export const RegionBackendBucketProvider = () => |
| 214 | Provider.succeed(RegionBackendBucket, { |
| 215 | stables: ["name", "project", "region", "selfLink", "creationTimestamp", "id"], |
| 216 | |
| 217 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 218 | if (!isResolved(news)) return undefined; |
| 219 | const env = yield* GcpEnvironment.current; |
| 220 | const previousName = olds?.name ?? output?.name; |
| 221 | const nextName = news.name ?? previousName; |
| 222 | const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 223 | const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region); |
| 224 | const nameChanged = |
| 225 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 226 | const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion; |
| 227 | const previousScheme = olds?.loadBalancingScheme ?? output?.loadBalancingScheme; |
| 228 | const schemeChanged = |
| 229 | news.loadBalancingScheme !== undefined && |
| 230 | (previousScheme ?? "") !== news.loadBalancingScheme; |
| 231 | if (nameChanged || regionChanged || schemeChanged) { |
| 232 | return { |
| 233 | action: "replace" as const, |
| 234 | deleteFirst: !nameChanged || nextName === undefined || nextName === previousName, |
| 235 | }; |
| 236 | } |
| 237 | return undefined; |
| 238 | }), |
| 239 | |
| 240 | read: Effect.fn(function* ({ id, olds, output }) { |
| 241 | const env = yield* GcpEnvironment.current; |
| 242 | const name = yield* toPhysicalName(id, olds?.name, output?.name, "backend"); |
| 243 | const region = normalizeRegion(olds?.region ?? output?.region, env.region); |
| 244 | const existing = yield* getByName(env.project, region, name); |
| 245 | if (existing === undefined) return undefined; |
| 246 | const attrs = toAttrs(existing, env.project); |
| 247 | const { labels } = parseDescription(existing.description); |
| 248 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 249 | }), |
| 250 | |
| 251 | list: () => |
| 252 | Effect.gen(function* () { |
| 253 | const env = yield* GcpEnvironment.current; |
| 254 | const pages = yield* compute.aggregatedListBackendBuckets |
| 255 | .pages({ |
| 256 | project: env.project, |
| 257 | maxResults: 500, |
| 258 | returnPartialSuccess: true, |
| 259 | }) |
| 260 | .pipe( |
| 261 | Stream.runCollect, |
| 262 | Effect.catchTag("NotFound", () => Effect.succeed([] as never[])), |
| 263 | ); |
| 264 | return Array.from(pages as readonly compute.BackendBucketAggregatedList[]).flatMap((page) => |
| 265 | Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => { |
| 266 | if (!scope.startsWith("regions/")) return []; |
| 267 | return (scoped?.backendBuckets ?? []) |
| 268 | .filter((item) => hasOwnershipMarker(item.description)) |
| 269 | .map((item) => toAttrs(item, env.project)); |
| 270 | }), |
| 271 | ); |
| 272 | }), |
| 273 | |
| 274 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 275 | const env = yield* GcpEnvironment.current; |
| 276 | const name = yield* toPhysicalName(id, news.name, output?.name, "backend"); |
| 277 | const region = normalizeRegion(news.region ?? output?.region, env.region); |
| 278 | const ownership = yield* createInternalLabels(id); |
| 279 | const desiredDescription = encodeDescription(ownership, news.description); |
| 280 | const enableCdn = news.enableCdn === true; |
| 281 | const desiredHeaders = news.customResponseHeaders ?? []; |
| 282 | |
| 283 | let current = yield* getByName(env.project, region, name); |
| 284 | |
| 285 | if (current === undefined) { |
| 286 | const insertBody: compute.BackendBucket = { |
| 287 | name, |
| 288 | bucketName: news.bucketName, |
| 289 | description: desiredDescription, |
| 290 | enableCdn, |
| 291 | loadBalancingScheme: news.loadBalancingScheme ?? DEFAULT_LOAD_BALANCING_SCHEME, |
| 292 | }; |
| 293 | if ( |
| 294 | news.compressionMode !== undefined && |
| 295 | (news.loadBalancingScheme ?? DEFAULT_LOAD_BALANCING_SCHEME) !== "EXTERNAL_MANAGED" |
| 296 | ) { |
| 297 | insertBody.compressionMode = news.compressionMode; |
| 298 | } |
| 299 | if ( |
| 300 | desiredHeaders.length > 0 && |
| 301 | (news.loadBalancingScheme ?? DEFAULT_LOAD_BALANCING_SCHEME) !== "EXTERNAL_MANAGED" |
| 302 | ) { |
| 303 | insertBody.customResponseHeaders = desiredHeaders; |
| 304 | } |
| 305 | if (news.cdnPolicy !== undefined) { |
| 306 | insertBody.cdnPolicy = news.cdnPolicy; |
| 307 | } |
| 308 | yield* runRegionOp( |
| 309 | env.project, |
| 310 | region, |
| 311 | compute.insertRegionBackendBuckets({ |
| 312 | project: env.project, |
| 313 | region, |
| 314 | body: insertBody, |
| 315 | }), |
| 316 | { ignoreAlreadyExists: true }, |
| 317 | ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 318 | current = yield* awaitResource(env.project, region, name); |
| 319 | } |
| 320 | |
| 321 | if (current === undefined) { |
| 322 | return yield* new RegionBackendBucketNotResolved({ resourceName: name, region }); |
| 323 | } |
| 324 | |
| 325 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 326 | const bucketChanged = (current.bucketName ?? "") !== news.bucketName; |
| 327 | const cdnChanged = (current.enableCdn === true) !== enableCdn; |
| 328 | const compressionChanged = |
| 329 | news.compressionMode !== undefined && |
| 330 | (current.compressionMode ?? "") !== news.compressionMode; |
| 331 | const headersChanged = !sameList(current.customResponseHeaders, desiredHeaders); |
| 332 | const policyChanged = |
| 333 | news.cdnPolicy !== undefined && |
| 334 | !sameJson(normalizeCdnPolicy(current.cdnPolicy), normalizeCdnPolicy(news.cdnPolicy)); |
| 335 | |
| 336 | if ( |
| 337 | descriptionChanged || |
| 338 | bucketChanged || |
| 339 | cdnChanged || |
| 340 | compressionChanged || |
| 341 | headersChanged || |
| 342 | policyChanged |
| 343 | ) { |
| 344 | const patchBody: compute.BackendBucket = { |
| 345 | bucketName: news.bucketName, |
| 346 | description: desiredDescription, |
| 347 | enableCdn, |
| 348 | }; |
| 349 | if ( |
| 350 | news.compressionMode !== undefined && |
| 351 | (news.loadBalancingScheme ?? DEFAULT_LOAD_BALANCING_SCHEME) !== "EXTERNAL_MANAGED" |
| 352 | ) { |
| 353 | patchBody.compressionMode = news.compressionMode; |
| 354 | } |
| 355 | if ( |
| 356 | desiredHeaders.length > 0 && |
| 357 | (news.loadBalancingScheme ?? DEFAULT_LOAD_BALANCING_SCHEME) !== "EXTERNAL_MANAGED" |
| 358 | ) { |
| 359 | patchBody.customResponseHeaders = desiredHeaders; |
| 360 | } |
| 361 | if (news.cdnPolicy !== undefined) { |
| 362 | patchBody.cdnPolicy = news.cdnPolicy; |
| 363 | } |
| 364 | yield* runRegionOp( |
| 365 | env.project, |
| 366 | region, |
| 367 | compute.patchRegionBackendBuckets({ |
| 368 | project: env.project, |
| 369 | region, |
| 370 | backendBucket: name, |
| 371 | body: patchBody, |
| 372 | }), |
| 373 | ); |
| 374 | current = (yield* getByName(env.project, region, name)) ?? current; |
| 375 | } |
| 376 | |
| 377 | return toAttrs(current, env.project); |
| 378 | }), |
| 379 | |
| 380 | delete: Effect.fn(function* ({ output }) { |
| 381 | const env = yield* GcpEnvironment.current; |
| 382 | const region = normalizeRegion(output.region, env.region); |
| 383 | yield* runRegionOp( |
| 384 | env.project, |
| 385 | region, |
| 386 | compute.deleteRegionBackendBuckets({ |
| 387 | project: env.project, |
| 388 | region, |
| 389 | backendBucket: output.name, |
| 390 | }), |
| 391 | { ignoreNotFound: true }, |
| 392 | ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 393 | }), |
| 394 | }); |