The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as firebaseapphosting from "@distilled.cloud/gcp/firebaseapphosting_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | defaultServiceAccount, |
| 14 | fieldMask, |
| 15 | fingerprint, |
| 16 | listAtLocation, |
| 17 | listLabeledPages, |
| 18 | MAX_BACKEND_ID_LENGTH, |
| 19 | normalizeLocation, |
| 20 | normalizeServingLocality, |
| 21 | parentOf, |
| 22 | parseName, |
| 23 | replaceOnIdentity, |
| 24 | ResourceNotResolved, |
| 25 | sameBool, |
| 26 | sameText, |
| 27 | stringMap, |
| 28 | toPhysicalId, |
| 29 | userLabels, |
| 30 | waitForDeleteOperation, |
| 31 | waitForOperation, |
| 32 | waitUntilExists, |
| 33 | waitUntilGone, |
| 34 | } from "./internal.ts"; |
| 35 | |
| 36 | export type Codebase = { |
| 37 | /** |
| 38 | * Developer Connect gitRepositoryLink resource name |
| 39 | * `projects/{project}/locations/{location}/connections/{connection}/gitRepositoryLinks/{repositoryLink}`. |
| 40 | * The connection must use the Firebase App Hosting GitHub App. |
| 41 | */ |
| 42 | repository?: string; |
| 43 | /** |
| 44 | * Directory relative to the repository root used as the web app root. |
| 45 | * Defaults to the repository root. For a monorepo this is the directory |
| 46 | * that contains `package.json` or `apphosting.yaml`. |
| 47 | */ |
| 48 | rootDirectory?: string; |
| 49 | }; |
| 50 | |
| 51 | export type RunService = { |
| 52 | /** |
| 53 | * Cloud Run service name |
| 54 | * `projects/{project}/locations/{location}/services/{serviceId}`. |
| 55 | */ |
| 56 | service?: string; |
| 57 | }; |
| 58 | |
| 59 | export type ManagedResource = { |
| 60 | /** Cloud Run service managed by App Hosting. */ |
| 61 | runService?: RunService; |
| 62 | }; |
| 63 | |
| 64 | export type BackendProps = { |
| 65 | /** |
| 66 | * Backend id (the `{backendId}` segment of |
| 67 | * `projects/{project}/locations/{location}/backends/{backendId}`). |
| 68 | * Also used as the Cloud Run service id and as part of the default |
| 69 | * domain name. If omitted, a unique RFC1035 name is generated from the |
| 70 | * stack, stage, and logical id. Immutable — changing it replaces the |
| 71 | * backend. Must start with a letter, contain only lowercase letters, |
| 72 | * digits, and hyphens, and be at most 49 characters. |
| 73 | */ |
| 74 | backendId?: string; |
| 75 | /** |
| 76 | * Region (`us-central1`, `us-east1`, …). Immutable — changing it |
| 77 | * replaces the backend. `US-CENTRAL1` is accepted and normalized to |
| 78 | * `us-central1`. |
| 79 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 80 | */ |
| 81 | location?: string; |
| 82 | /** |
| 83 | * Service account used for Cloud Build and Cloud Run. Should have |
| 84 | * `roles/firebaseapphosting.computeRunner` (or equivalent). Defaults |
| 85 | * to `firebase-app-hosting-compute@{project}.iam.gserviceaccount.com`. |
| 86 | */ |
| 87 | serviceAccount?: string; |
| 88 | /** |
| 89 | * How App Hosting serves this backend. `REGIONAL_STRICT` keeps |
| 90 | * traffic in one region; `GLOBAL_ACCESS` uses App Hosting's |
| 91 | * global-replicated serving. Immutable — changing it replaces the |
| 92 | * backend. |
| 93 | * @default "GLOBAL_ACCESS" |
| 94 | */ |
| 95 | servingLocality?: firebaseapphosting.BackendServingLocalityEnum | (string & {}); |
| 96 | /** |
| 97 | * Human-readable name. 63 character limit. |
| 98 | */ |
| 99 | displayName?: string; |
| 100 | /** |
| 101 | * Git repository connection used for event-driven updates. |
| 102 | */ |
| 103 | codebase?: Codebase; |
| 104 | /** |
| 105 | * Firebase Web App id associated with this backend. |
| 106 | */ |
| 107 | appId?: string; |
| 108 | /** |
| 109 | * Environment name used to load environment-specific configuration. |
| 110 | */ |
| 111 | environment?: string; |
| 112 | /** |
| 113 | * When true, incoming request logs are disabled. Logs are enabled by |
| 114 | * default. |
| 115 | * @default false |
| 116 | */ |
| 117 | requestLogsDisabled?: boolean; |
| 118 | /** |
| 119 | * User annotations (preserved by external tools). |
| 120 | */ |
| 121 | annotations?: Record<string, string>; |
| 122 | /** |
| 123 | * User labels. Alchemy ownership labels are merged in automatically. |
| 124 | */ |
| 125 | labels?: Record<string, string>; |
| 126 | }; |
| 127 | |
| 128 | export type Backend = Resource< |
| 129 | "GCP.FirebaseAppHosting.Backend", |
| 130 | BackendProps, |
| 131 | { |
| 132 | /** Full resource name. */ |
| 133 | name: string; |
| 134 | /** Backend id (last path segment). */ |
| 135 | backendId: string; |
| 136 | /** Project id. */ |
| 137 | project: string; |
| 138 | /** Location id. */ |
| 139 | location: string; |
| 140 | /** Service account email. */ |
| 141 | serviceAccount: string | undefined; |
| 142 | /** Serving locality. */ |
| 143 | servingLocality: string | undefined; |
| 144 | /** Human-readable name. */ |
| 145 | displayName: string | undefined; |
| 146 | /** Git repository connection. */ |
| 147 | codebase: Codebase | undefined; |
| 148 | /** Associated Firebase Web App id. */ |
| 149 | appId: string | undefined; |
| 150 | /** Environment name. */ |
| 151 | environment: string | undefined; |
| 152 | /** Whether incoming request logs are disabled. */ |
| 153 | requestLogsDisabled: boolean; |
| 154 | /** Primary URI used to reach the backend. */ |
| 155 | uri: string | undefined; |
| 156 | /** Cloud resources managed by this backend. */ |
| 157 | managedResources: ManagedResource[] | undefined; |
| 158 | /** True while App Hosting is applying an LRO. */ |
| 159 | reconciling: boolean; |
| 160 | /** User annotations. */ |
| 161 | annotations: Record<string, string>; |
| 162 | /** User labels (Alchemy ownership labels stripped). */ |
| 163 | labels: Record<string, string>; |
| 164 | /** Server-generated resource uid. */ |
| 165 | uid: string | undefined; |
| 166 | /** RFC3339 creation timestamp. */ |
| 167 | createTime: string | undefined; |
| 168 | /** RFC3339 last-update timestamp. */ |
| 169 | updateTime: string | undefined; |
| 170 | /** Server-computed etag. */ |
| 171 | etag: string | undefined; |
| 172 | }, |
| 173 | never, |
| 174 | Providers |
| 175 | >; |
| 176 | |
| 177 | /** |
| 178 | * A Firebase App Hosting backend — the primary resource that provisions |
| 179 | * a Cloud Run service and default domain for a web app. |
| 180 | * |
| 181 | * Changing `backendId`, `location`, or `servingLocality` replaces the |
| 182 | * backend. Display name, codebase, app id, environment, request logs, |
| 183 | * service account, labels, and annotations update in place. |
| 184 | * |
| 185 | * ### Creating a Backend |
| 186 | * **Example:** Generated name |
| 187 | * ```typescript |
| 188 | * const backend = yield* GCP.FirebaseAppHosting.Backend("Web", { |
| 189 | * labels: { env: "test" }, |
| 190 | * }); |
| 191 | * ``` |
| 192 | * |
| 193 | * **Example:** Explicit id and regional serving |
| 194 | * ```typescript |
| 195 | * const backend = yield* GCP.FirebaseAppHosting.Backend("Web", { |
| 196 | * backendId: "web-prod", |
| 197 | * servingLocality: "REGIONAL_STRICT", |
| 198 | * serviceAccount: "firebase-app-hosting-compute@my-project.iam.gserviceaccount.com", |
| 199 | * displayName: "production web", |
| 200 | * labels: { env: "prod" }, |
| 201 | * }); |
| 202 | * ``` |
| 203 | * |
| 204 | * ### Updating a Backend |
| 205 | * **Example:** Display name and labels |
| 206 | * ```typescript |
| 207 | * const backend = yield* GCP.FirebaseAppHosting.Backend("Web", { |
| 208 | * displayName: "production web v2", |
| 209 | * labels: { env: "prod", team: "web" }, |
| 210 | * }); |
| 211 | * ``` |
| 212 | * |
| 213 | * @resource |
| 214 | * @category FirebaseAppHosting |
| 215 | */ |
| 216 | export const Backend = Resource<Backend>("GCP.FirebaseAppHosting.Backend"); |
| 217 | |
| 218 | const resourceName = (project: string, location: string, backendId: string) => |
| 219 | `projects/${project}/locations/${location}/backends/${backendId}`; |
| 220 | |
| 221 | const toCodebase = (value: firebaseapphosting.Codebase | undefined): Codebase | undefined => |
| 222 | value === undefined |
| 223 | ? undefined |
| 224 | : { |
| 225 | repository: value.repository, |
| 226 | rootDirectory: value.rootDirectory, |
| 227 | }; |
| 228 | |
| 229 | const toManagedResources = ( |
| 230 | value: firebaseapphosting.ManagedResourceList | undefined, |
| 231 | ): ManagedResource[] | undefined => |
| 232 | value === undefined |
| 233 | ? undefined |
| 234 | : value.map((item) => ({ |
| 235 | runService: item.runService ? { service: item.runService.service } : undefined, |
| 236 | })); |
| 237 | |
| 238 | const toAttrs = (item: firebaseapphosting.Backend, project: string) => { |
| 239 | const name = item.name ?? ""; |
| 240 | const parsed = parseName(name, "backends"); |
| 241 | return { |
| 242 | name, |
| 243 | backendId: parsed.id, |
| 244 | project: parsed.project || project, |
| 245 | location: parsed.location, |
| 246 | serviceAccount: item.serviceAccount, |
| 247 | servingLocality: item.servingLocality, |
| 248 | displayName: item.displayName, |
| 249 | codebase: toCodebase(item.codebase), |
| 250 | appId: item.appId, |
| 251 | environment: item.environment, |
| 252 | requestLogsDisabled: item.requestLogsDisabled === true, |
| 253 | uri: item.uri, |
| 254 | managedResources: toManagedResources(item.managedResources), |
| 255 | reconciling: item.reconciling === true, |
| 256 | annotations: stringMap(item.annotations), |
| 257 | labels: userLabels(item.labels), |
| 258 | uid: item.uid, |
| 259 | createTime: item.createTime, |
| 260 | updateTime: item.updateTime, |
| 261 | etag: item.etag, |
| 262 | }; |
| 263 | }; |
| 264 | |
| 265 | const getByName = (name: string) => |
| 266 | firebaseapphosting |
| 267 | .getProjectsLocationsBackends({ name }) |
| 268 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 269 | |
| 270 | const listOwned = (project: string) => |
| 271 | listAtLocation(project, (parent) => |
| 272 | listLabeledPages( |
| 273 | firebaseapphosting.listProjectsLocationsBackends.pages({ |
| 274 | parent, |
| 275 | pageSize: 1000, |
| 276 | }), |
| 277 | (page) => page.backends, |
| 278 | (item) => item.labels, |
| 279 | ), |
| 280 | ); |
| 281 | |
| 282 | export const BackendProvider = () => |
| 283 | Provider.succeed(Backend, { |
| 284 | stables: ["name", "backendId", "project", "location", "uid", "createTime", "servingLocality"], |
| 285 | |
| 286 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 287 | if (!isResolved(news)) return undefined; |
| 288 | const env = yield* GcpEnvironment.current; |
| 289 | const previousServing = normalizeServingLocality( |
| 290 | olds?.servingLocality ?? output?.servingLocality, |
| 291 | ); |
| 292 | const nextServing = normalizeServingLocality( |
| 293 | news.servingLocality ?? olds?.servingLocality ?? output?.servingLocality, |
| 294 | ); |
| 295 | return replaceOnIdentity({ |
| 296 | previousId: olds?.backendId ?? output?.backendId, |
| 297 | nextId: news.backendId ?? olds?.backendId ?? output?.backendId, |
| 298 | previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region), |
| 299 | nextLocation: normalizeLocation( |
| 300 | news.location ?? olds?.location ?? output?.location, |
| 301 | env.region, |
| 302 | ), |
| 303 | extra: |
| 304 | (olds?.servingLocality ?? output?.servingLocality) !== undefined && |
| 305 | previousServing !== nextServing, |
| 306 | }); |
| 307 | }), |
| 308 | |
| 309 | read: Effect.fn(function* ({ id, olds, output }) { |
| 310 | const env = yield* GcpEnvironment.current; |
| 311 | const backendId = yield* toPhysicalId( |
| 312 | id, |
| 313 | olds?.backendId, |
| 314 | output?.backendId, |
| 315 | "backend", |
| 316 | MAX_BACKEND_ID_LENGTH, |
| 317 | ); |
| 318 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 319 | const name = output?.name ?? resourceName(env.project, location, backendId); |
| 320 | const existing = yield* getByName(name); |
| 321 | if (existing === undefined) return undefined; |
| 322 | const attrs = toAttrs(existing, env.project); |
| 323 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 324 | }), |
| 325 | |
| 326 | list: () => |
| 327 | Effect.gen(function* () { |
| 328 | const env = yield* GcpEnvironment.current; |
| 329 | const items = yield* listOwned(env.project); |
| 330 | return items.map((item) => toAttrs(item, env.project)); |
| 331 | }), |
| 332 | |
| 333 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 334 | const env = yield* GcpEnvironment.current; |
| 335 | const backendId = yield* toPhysicalId( |
| 336 | id, |
| 337 | news.backendId, |
| 338 | output?.backendId, |
| 339 | "backend", |
| 340 | MAX_BACKEND_ID_LENGTH, |
| 341 | ); |
| 342 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 343 | const name = resourceName(env.project, location, backendId); |
| 344 | const desiredLabels = { |
| 345 | ...toLabels(news.labels), |
| 346 | ...(yield* createInternalLabels(id)), |
| 347 | }; |
| 348 | const desiredAnnotations = news.annotations ?? {}; |
| 349 | const desiredServing = normalizeServingLocality(news.servingLocality); |
| 350 | const desiredServiceAccount = news.serviceAccount ?? defaultServiceAccount(env.project); |
| 351 | const desiredLogsDisabled = news.requestLogsDisabled === true; |
| 352 | |
| 353 | let current = yield* getByName(output?.name ?? name); |
| 354 | |
| 355 | if (current === undefined) { |
| 356 | const created = yield* firebaseapphosting |
| 357 | .createProjectsLocationsBackends({ |
| 358 | parent: parentOf(env.project, location), |
| 359 | backendId, |
| 360 | body: { |
| 361 | servingLocality: desiredServing as firebaseapphosting.BackendServingLocalityEnum, |
| 362 | serviceAccount: desiredServiceAccount, |
| 363 | displayName: news.displayName, |
| 364 | codebase: news.codebase, |
| 365 | appId: news.appId, |
| 366 | environment: news.environment, |
| 367 | requestLogsDisabled: desiredLogsDisabled, |
| 368 | annotations: desiredAnnotations, |
| 369 | labels: desiredLabels, |
| 370 | }, |
| 371 | }) |
| 372 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 373 | if (created !== undefined) { |
| 374 | yield* waitForOperation(created); |
| 375 | } |
| 376 | current = yield* waitUntilExists(getByName(name), name); |
| 377 | } |
| 378 | |
| 379 | if (current === undefined) { |
| 380 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 381 | } |
| 382 | |
| 383 | const observedLabels = tagRecord(current.labels); |
| 384 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 385 | const mask = fieldMask([ |
| 386 | (upsert.length > 0 || removed.length > 0) && "labels", |
| 387 | fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) && |
| 388 | "annotations", |
| 389 | !sameText(current.displayName, news.displayName) && "displayName", |
| 390 | !sameText(current.serviceAccount, desiredServiceAccount) && "serviceAccount", |
| 391 | !sameText(current.appId, news.appId) && "appId", |
| 392 | !sameText(current.environment, news.environment) && "environment", |
| 393 | !sameBool(current.requestLogsDisabled, desiredLogsDisabled) && "requestLogsDisabled", |
| 394 | fingerprint(toCodebase(current.codebase)) !== fingerprint(news.codebase) && "codebase", |
| 395 | ]); |
| 396 | |
| 397 | if (mask.length > 0) { |
| 398 | const operation = yield* firebaseapphosting.patchProjectsLocationsBackends({ |
| 399 | name: current.name ?? name, |
| 400 | updateMask: mask, |
| 401 | body: { |
| 402 | etag: current.etag, |
| 403 | displayName: news.displayName, |
| 404 | serviceAccount: desiredServiceAccount, |
| 405 | codebase: news.codebase, |
| 406 | appId: news.appId, |
| 407 | environment: news.environment, |
| 408 | requestLogsDisabled: desiredLogsDisabled, |
| 409 | annotations: desiredAnnotations, |
| 410 | labels: desiredLabels, |
| 411 | }, |
| 412 | }); |
| 413 | yield* waitForOperation(operation); |
| 414 | current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name); |
| 415 | } |
| 416 | |
| 417 | return toAttrs(current, env.project); |
| 418 | }), |
| 419 | |
| 420 | delete: Effect.fn(function* ({ output }) { |
| 421 | const operation = yield* firebaseapphosting |
| 422 | .deleteProjectsLocationsBackends({ |
| 423 | name: output.name, |
| 424 | force: true, |
| 425 | }) |
| 426 | .pipe( |
| 427 | Effect.retry({ |
| 428 | while: (error) => error._tag === "Conflict", |
| 429 | times: 8, |
| 430 | schedule: Schedule.spaced("2 seconds"), |
| 431 | }), |
| 432 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 433 | ); |
| 434 | if (operation !== undefined) { |
| 435 | yield* waitForDeleteOperation(operation); |
| 436 | } |
| 437 | yield* waitUntilGone(getByName(output.name), output.name); |
| 438 | }), |
| 439 | }); |