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