The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import * as resourcemanagerV1 from "@distilled.cloud/gcp/unstable/cloudresourcemanager_v1"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import { tagRecord } from "alchemy/Tags"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import { |
| 13 | createInternalLabels, |
| 14 | diffLabels, |
| 15 | hasAlchemyLabels, |
| 16 | stripInternalLabels, |
| 17 | toLabels, |
| 18 | } from "../Labels.ts"; |
| 19 | import type { Providers } from "../Providers.ts"; |
| 20 | import { |
| 21 | PROJECT_DISPLAY_MAX, |
| 22 | PROJECT_DISPLAY_MIN, |
| 23 | PROJECT_ID_MAX, |
| 24 | PROJECT_ID_MIN, |
| 25 | collectPages, |
| 26 | isDeleteRequested, |
| 27 | lastSegment, |
| 28 | projectIdFromOperation, |
| 29 | normalizeHierarchyParent, |
| 30 | resourceNameFromOperation, |
| 31 | sameHierarchyParent, |
| 32 | tryResolveParent, |
| 33 | waitForOperation, |
| 34 | waitForCreate, |
| 35 | } from "./internal.ts"; |
| 36 | |
| 37 | export type ProjectProps = { |
| 38 | /** |
| 39 | * Globally unique project id. 6-30 lowercase letters, digits, or |
| 40 | * hyphens; must start with a letter and must not end with a hyphen. |
| 41 | * If omitted, a unique id is generated from the stack, stage, and |
| 42 | * logical id. Immutable — changing it replaces the project. |
| 43 | */ |
| 44 | projectId?: string; |
| 45 | /** |
| 46 | * Parent `organizations/{org}` or `folders/{folder}`. Defaults to the |
| 47 | * current project's parent; when the current project has none, the |
| 48 | * project is created standalone. Changing parent moves the project. |
| 49 | */ |
| 50 | parent?: string; |
| 51 | /** |
| 52 | * User-assigned display name (4-30 characters). Defaults to the |
| 53 | * project id when omitted. |
| 54 | */ |
| 55 | displayName?: string; |
| 56 | /** |
| 57 | * User labels. Alchemy ownership labels (`alchemy-stack`, |
| 58 | * `alchemy-stage`, `alchemy-id`) are merged in automatically. |
| 59 | */ |
| 60 | labels?: Record<string, string>; |
| 61 | }; |
| 62 | |
| 63 | export type Project = Resource< |
| 64 | "GCP.ResourceManager.Project", |
| 65 | ProjectProps, |
| 66 | { |
| 67 | /** Resource name `projects/{project_number}`. */ |
| 68 | name: string; |
| 69 | /** User-assigned project id. */ |
| 70 | projectId: string; |
| 71 | /** Parent `organizations/{org}` or `folders/{folder}`; `undefined` when standalone. */ |
| 72 | parent: string | undefined; |
| 73 | /** User-assigned display name. */ |
| 74 | displayName: string | undefined; |
| 75 | /** User labels (Alchemy ownership labels stripped). */ |
| 76 | labels: Record<string, string>; |
| 77 | /** Lifecycle state (`ACTIVE` or `DELETE_REQUESTED`). */ |
| 78 | state: string | undefined; |
| 79 | /** Server etag for optimistic concurrency. */ |
| 80 | etag: string | undefined; |
| 81 | /** RFC3339 creation timestamp. */ |
| 82 | createTime: string | undefined; |
| 83 | /** RFC3339 last-update timestamp. */ |
| 84 | updateTime: string | undefined; |
| 85 | /** RFC3339 time a delete was requested, if any. */ |
| 86 | deleteTime: string | undefined; |
| 87 | /** Configured capabilities when this is a management project. */ |
| 88 | configuredCapabilities: string[]; |
| 89 | }, |
| 90 | never, |
| 91 | Providers |
| 92 | >; |
| 93 | |
| 94 | /** |
| 95 | * A Google Cloud project — the container for APIs, IAM, billing, and |
| 96 | * other resources. |
| 97 | * |
| 98 | * `projectId` is globally unique and immutable; changing it replaces |
| 99 | * the project. `parent` is moved in place. `displayName` and `labels` |
| 100 | * update in place. Delete is a 30-day soft-delete (`DELETE_REQUESTED`). |
| 101 | * Alchemy ownership labels are applied so `list` / `pnpm nuke:gcp` can |
| 102 | * find leftover projects. |
| 103 | * |
| 104 | * ### Creating a Project |
| 105 | * **Example:** Generated project id under the current project's parent |
| 106 | * ```typescript |
| 107 | * const project = yield* GCP.ResourceManager.Project("Sandbox", {}); |
| 108 | * ``` |
| 109 | * |
| 110 | * **Example:** Explicit id, parent, and labels |
| 111 | * ```typescript |
| 112 | * const project = yield* GCP.ResourceManager.Project("Sandbox", { |
| 113 | * projectId: "my-app-sandbox", |
| 114 | * parent: "folders/123456789", |
| 115 | * displayName: "Sandbox", |
| 116 | * labels: { env: "test" }, |
| 117 | * }); |
| 118 | * ``` |
| 119 | * |
| 120 | * **Example:** Standalone project without an organization or folder |
| 121 | * ```typescript |
| 122 | * // With no `parent`, the project lands under the current project's |
| 123 | * // organization or folder. When the current project has none, it is |
| 124 | * // created standalone and `parent` is `undefined`. Google only lets user |
| 125 | * // credentials create standalone projects, not service accounts. |
| 126 | * const project = yield* GCP.ResourceManager.Project("Sandbox", { |
| 127 | * displayName: "Sandbox", |
| 128 | * }); |
| 129 | * ``` |
| 130 | * |
| 131 | * ### Updating a Project |
| 132 | * **Example:** Change display name and labels |
| 133 | * ```typescript |
| 134 | * const project = yield* GCP.ResourceManager.Project("Sandbox", { |
| 135 | * projectId: "my-app-sandbox", |
| 136 | * displayName: "Sandbox prod", |
| 137 | * labels: { env: "prod" }, |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * @resource |
| 142 | * @category ResourceManager |
| 143 | */ |
| 144 | export const Project = Resource<Project>("GCP.ResourceManager.Project"); |
| 145 | |
| 146 | export class ProjectNotResolved extends Data.TaggedError("GCP.ResourceManager.ProjectNotResolved")<{ |
| 147 | resourceName: string; |
| 148 | }> {} |
| 149 | |
| 150 | export class ProjectStillExists extends Data.TaggedError("GCP.ResourceManager.ProjectStillExists")<{ |
| 151 | resourceName: string; |
| 152 | }> {} |
| 153 | |
| 154 | const userLabels = ( |
| 155 | labels: Record<string, string | undefined> | null | undefined, |
| 156 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 157 | |
| 158 | const sanitizeProjectId = (value: string) => { |
| 159 | let next = value |
| 160 | .toLowerCase() |
| 161 | .replace(/[^a-z0-9-]/g, "-") |
| 162 | .replace(/-+/g, "-"); |
| 163 | if (!/^[a-z]/.test(next)) next = `p${next}`; |
| 164 | next = next.replace(/-+$/g, ""); |
| 165 | if (next.length > PROJECT_ID_MAX) { |
| 166 | next = next.slice(0, PROJECT_ID_MAX).replace(/-+$/g, ""); |
| 167 | } |
| 168 | if (next.length < PROJECT_ID_MIN) { |
| 169 | next = `${next}xxxxxx`.slice(0, PROJECT_ID_MIN); |
| 170 | } |
| 171 | return next; |
| 172 | }; |
| 173 | |
| 174 | const toProjectId = (id: string, projectId: string | undefined, existing?: string) => |
| 175 | Effect.gen(function* () { |
| 176 | if (projectId !== undefined) return sanitizeProjectId(projectId); |
| 177 | if (existing !== undefined) return existing; |
| 178 | const generated = yield* createPhysicalName({ |
| 179 | id, |
| 180 | maxLength: PROJECT_ID_MAX, |
| 181 | lowercase: true, |
| 182 | }); |
| 183 | return sanitizeProjectId(generated); |
| 184 | }); |
| 185 | |
| 186 | const sanitizeDisplayName = (value: string | undefined, fallback: string) => { |
| 187 | const source = (value ?? fallback).trim(); |
| 188 | let next = source |
| 189 | .replace(/[^a-zA-Z0-9 '"\-!]/g, " ") |
| 190 | .replace(/\s+/g, " ") |
| 191 | .trim(); |
| 192 | if (next.length === 0) next = fallback; |
| 193 | if (next.length > PROJECT_DISPLAY_MAX) next = next.slice(0, PROJECT_DISPLAY_MAX); |
| 194 | if (next.length < PROJECT_DISPLAY_MIN) { |
| 195 | next = `${next} proj`.slice(0, PROJECT_DISPLAY_MIN); |
| 196 | } |
| 197 | return next; |
| 198 | }; |
| 199 | |
| 200 | const toAttrs = (project: resourcemanager.Project) => ({ |
| 201 | name: project.name ?? "", |
| 202 | projectId: project.projectId ?? lastSegment(project.name ?? ""), |
| 203 | parent: project.parent || undefined, |
| 204 | displayName: project.displayName, |
| 205 | labels: userLabels(project.labels), |
| 206 | state: project.state, |
| 207 | etag: project.etag, |
| 208 | createTime: project.createTime, |
| 209 | updateTime: project.updateTime, |
| 210 | deleteTime: project.deleteTime, |
| 211 | configuredCapabilities: project.configuredCapabilities ?? [], |
| 212 | }); |
| 213 | |
| 214 | const getByName = (name: string) => |
| 215 | resourcemanager |
| 216 | .getProjects({ name }) |
| 217 | .pipe(Effect.catchTag(["NotFound", "ProjectNotFound"], () => Effect.undefined)); |
| 218 | |
| 219 | const observe = (resourceName: string | undefined, projectId: string) => |
| 220 | Effect.gen(function* () { |
| 221 | if (resourceName !== undefined && resourceName.length > 0) { |
| 222 | const byName = yield* getByName(resourceName); |
| 223 | if (byName !== undefined) return byName; |
| 224 | } |
| 225 | return yield* getByName(`projects/${projectId}`); |
| 226 | }); |
| 227 | |
| 228 | const waitUntilExists = (resourceName: string | undefined, projectId: string) => |
| 229 | observe(resourceName, projectId).pipe( |
| 230 | Effect.filterOrFail( |
| 231 | (project): project is resourcemanager.Project => project !== undefined, |
| 232 | () => |
| 233 | new ProjectNotResolved({ |
| 234 | resourceName: resourceName ?? `projects/${projectId}`, |
| 235 | }), |
| 236 | ), |
| 237 | Effect.retry({ |
| 238 | while: (error) => error._tag === "GCP.ResourceManager.ProjectNotResolved", |
| 239 | times: 8, |
| 240 | schedule: Schedule.spaced("1 second"), |
| 241 | }), |
| 242 | ); |
| 243 | |
| 244 | const waitUntilGone = (name: string) => |
| 245 | getByName(name).pipe( |
| 246 | Effect.flatMap((project) => |
| 247 | project === undefined || isDeleteRequested(project.state) |
| 248 | ? Effect.void |
| 249 | : Effect.fail(new ProjectStillExists({ resourceName: name })), |
| 250 | ), |
| 251 | Effect.retry({ |
| 252 | while: (error) => error._tag === "GCP.ResourceManager.ProjectStillExists", |
| 253 | times: 10, |
| 254 | schedule: Schedule.spaced("1 second"), |
| 255 | }), |
| 256 | ); |
| 257 | |
| 258 | const ensureActive = (project: resourcemanager.Project) => |
| 259 | Effect.gen(function* () { |
| 260 | if (!isDeleteRequested(project.state) || project.name === undefined) { |
| 261 | return project; |
| 262 | } |
| 263 | const operation = yield* resourcemanager.undeleteProjects({ |
| 264 | name: project.name, |
| 265 | body: {}, |
| 266 | }); |
| 267 | yield* waitForOperation(operation); |
| 268 | return yield* waitUntilExists(project.name, project.projectId ?? lastSegment(project.name)); |
| 269 | }); |
| 270 | |
| 271 | // Unlike folders, a project may be standalone (no organization or folder). |
| 272 | // No parent omits `parent` on create and never moves the project. A deployed |
| 273 | // project keeps the parent it has, so a standalone one stays out of the |
| 274 | // current project's hierarchy. |
| 275 | const resolveProjectParent = Effect.fn(function* ( |
| 276 | explicit: string | undefined, |
| 277 | output: { readonly parent: string | undefined } | undefined, |
| 278 | ) { |
| 279 | if (explicit) return normalizeHierarchyParent(explicit); |
| 280 | if (output !== undefined) { |
| 281 | return output.parent ? normalizeHierarchyParent(output.parent) : undefined; |
| 282 | } |
| 283 | return yield* tryResolveParent(); |
| 284 | }); |
| 285 | |
| 286 | export const ProjectProvider = () => |
| 287 | Provider.succeed(Project, { |
| 288 | stables: ["name", "projectId", "createTime"], |
| 289 | |
| 290 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 291 | if (!isResolved(news)) return undefined; |
| 292 | const previousId = olds?.projectId ?? output?.projectId; |
| 293 | const nextId = news.projectId !== undefined ? sanitizeProjectId(news.projectId) : previousId; |
| 294 | const idChanged = |
| 295 | previousId !== undefined && news.projectId !== undefined && nextId !== previousId; |
| 296 | if (!idChanged) return undefined; |
| 297 | return { action: "replace" as const, deleteFirst: false }; |
| 298 | }), |
| 299 | |
| 300 | read: Effect.fn(function* ({ id, olds, output }) { |
| 301 | const projectId = yield* toProjectId(id, olds?.projectId, output?.projectId); |
| 302 | const existing = yield* observe(output?.name, projectId); |
| 303 | if (existing === undefined) return undefined; |
| 304 | const attrs = toAttrs(existing); |
| 305 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 306 | }), |
| 307 | |
| 308 | list: () => |
| 309 | collectPages( |
| 310 | resourcemanager.searchProjects.pages({ |
| 311 | query: "labels.alchemy-stack:*", |
| 312 | pageSize: 300, |
| 313 | }), |
| 314 | (page) => page.projects, |
| 315 | ).pipe( |
| 316 | Effect.map((projects) => |
| 317 | projects |
| 318 | .filter((project) => |
| 319 | Object.keys(project.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 320 | ) |
| 321 | .map(toAttrs), |
| 322 | ), |
| 323 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 324 | ), |
| 325 | |
| 326 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 327 | const projectId = yield* toProjectId(id, news.projectId, output?.projectId); |
| 328 | const parent = yield* resolveProjectParent(news.parent, output); |
| 329 | const displayName = sanitizeDisplayName(news.displayName, projectId); |
| 330 | const desiredLabels = { |
| 331 | ...toLabels(news.labels), |
| 332 | ...(yield* createInternalLabels(id)), |
| 333 | }; |
| 334 | |
| 335 | let current = yield* observe(output?.name, projectId); |
| 336 | |
| 337 | if (current === undefined) { |
| 338 | const created = yield* resourcemanager |
| 339 | .createProjects({ |
| 340 | body: { |
| 341 | projectId, |
| 342 | parent, |
| 343 | displayName, |
| 344 | labels: desiredLabels, |
| 345 | }, |
| 346 | }) |
| 347 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 348 | if (created !== undefined) { |
| 349 | const settled = yield* waitForCreate(created); |
| 350 | current = yield* waitUntilExists( |
| 351 | resourceNameFromOperation(settled, "projects/") ?? |
| 352 | resourceNameFromOperation(created, "projects/"), |
| 353 | projectIdFromOperation(settled) ?? projectIdFromOperation(created) ?? projectId, |
| 354 | ); |
| 355 | } else { |
| 356 | current = yield* waitUntilExists(undefined, projectId); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | if (current === undefined || current.name === undefined) { |
| 361 | return yield* new ProjectNotResolved({ |
| 362 | resourceName: `projects/${projectId}`, |
| 363 | }); |
| 364 | } |
| 365 | |
| 366 | const name = current.name; |
| 367 | current = yield* ensureActive(current); |
| 368 | |
| 369 | const observedLabels = tagRecord(current.labels); |
| 370 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 371 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 372 | const displayChanged = (current.displayName ?? "") !== displayName; |
| 373 | |
| 374 | if (labelsChanged || displayChanged) { |
| 375 | // v3 `projects.patch` merges labels, so it can never remove one. |
| 376 | // v1 `projects.update` replaces them (v1 calls the display name `name`). |
| 377 | const id = current.projectId ?? projectId; |
| 378 | const observed = yield* resourcemanagerV1.getProjects({ projectId: id }); |
| 379 | yield* resourcemanagerV1.updateProjects({ |
| 380 | projectId: id, |
| 381 | body: { ...observed, name: displayName, labels: desiredLabels }, |
| 382 | }); |
| 383 | current = yield* waitUntilExists(current.name ?? name, projectId); |
| 384 | } |
| 385 | |
| 386 | if ( |
| 387 | current.parent !== undefined && |
| 388 | parent !== undefined && |
| 389 | !sameHierarchyParent(current.parent, parent) |
| 390 | ) { |
| 391 | const operation = yield* resourcemanager.moveProjects({ |
| 392 | name: current.name ?? name, |
| 393 | body: { destinationParent: parent }, |
| 394 | }); |
| 395 | yield* waitForOperation(operation); |
| 396 | current = yield* waitUntilExists(current.name ?? name, projectId); |
| 397 | } |
| 398 | |
| 399 | if (current === undefined) { |
| 400 | return yield* new ProjectNotResolved({ |
| 401 | resourceName: `projects/${projectId}`, |
| 402 | }); |
| 403 | } |
| 404 | |
| 405 | return toAttrs(current); |
| 406 | }), |
| 407 | |
| 408 | delete: Effect.fn(function* ({ output }) { |
| 409 | const operation = yield* resourcemanager.deleteProjects({ name: output.name }).pipe( |
| 410 | Effect.retry({ |
| 411 | while: (error) => error._tag === "Conflict", |
| 412 | times: 8, |
| 413 | schedule: Schedule.spaced("2 seconds"), |
| 414 | }), |
| 415 | Effect.catchTag(["NotFound", "ProjectNotFound"], () => Effect.undefined), |
| 416 | ); |
| 417 | if (operation !== undefined) { |
| 418 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 419 | } |
| 420 | yield* waitUntilGone(output.name); |
| 421 | }), |
| 422 | }); |