import * as config from "@distilled.cloud/gcp/config_v1"; import { createPhysicalName } from "alchemy/PhysicalName"; import { tagRecord } from "alchemy/Tags"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import { stripInternalLabels } from "../Labels.ts"; import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; export const MAX_NAME_LENGTH = 63; export class ResourceNotResolved extends Data.TaggedError("GCP.Config.ResourceNotResolved")<{ resourceName: string; }> {} export class ResourceStillExists extends Data.TaggedError("GCP.Config.ResourceStillExists")<{ resourceName: string; }> {} export const lastSegment = (value: string) => { const trimmed = value.replace(/\/+$/, ""); const parts = trimmed.split("/"); return parts[parts.length - 1] || trimmed; }; export const rfc1035 = (name: string, fallback = "config"): string => { let next = name .toLowerCase() .replace(/[^a-z0-9-]/g, "-") .replace(/-+/g, "-") .replace(/^-+|-+$/g, ""); if (!/^[a-z]/.test(next)) next = `c${next}`; next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); if (next.length === 0) return fallback; if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; return next.slice(0, MAX_NAME_LENGTH); }; export const normalizeLocation = (location: string | undefined, defaultLocation: string) => lastSegment(location ?? defaultLocation).toLowerCase(); export const parentOf = (project: string, location: string) => `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; export const toPhysicalId = ( id: string, explicit: string | undefined, existing: string | undefined, fallback = "config", maxLength = MAX_NAME_LENGTH, ) => Effect.gen(function* () { if (explicit !== undefined) return rfc1035(explicit, fallback); if (existing !== undefined) return existing; return rfc1035( yield* createPhysicalName({ id, maxLength, lowercase: true, }), fallback, ); }); export const parseName = (name: string, collection: string, defaultLocation: string) => { const parts = name.split("/").filter((part) => part.length > 0); const collectionAt = parts.lastIndexOf(collection); const locationsAt = parts.lastIndexOf("locations"); const projectsAt = parts.lastIndexOf("projects"); return { project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), parent: collectionAt > 0 ? parts.slice(0, collectionAt).join("/") : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), }; }; export const expandNamed = ( value: string, project: string, location: string, collection: string, ) => { if (value.includes("/")) return value.replace(/\/+$/, ""); return `projects/${project}/locations/${location}/${collection}/${value}`; }; export const serviceAccountName = (value: string, project: string) => { if (value.startsWith("projects/")) return value.replace(/\/+$/, ""); if (value.includes("@")) { return `projects/${project}/serviceAccounts/${value}`; } return `projects/${project}/serviceAccounts/${value}@${project}.iam.gserviceaccount.com`; }; export const userLabels = ( labels: Record | null | undefined, ): Record => stripInternalLabels(tagRecord(labels)); export const stringMap = ( value: Record | null | undefined, ): Record => Object.fromEntries( Object.entries(value ?? {}).filter( (entry): entry is [string, string] => typeof entry[1] === "string", ), ); export const hasAlchemyLabelMap = (labels: Record | null | undefined) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); export const canonical = (value: unknown): unknown => { if (value === undefined || value === null) return undefined; if (typeof value === "boolean" || typeof value === "number") return value; if (typeof value === "string") { return value.length === 0 ? undefined : value; } if (Array.isArray(value)) { const items = value.map(canonical).filter((item) => item !== undefined); return items.length === 0 ? undefined : items; } if (typeof value === "object") { const entries = Object.entries(value as Record) .map(([key, item]) => [key, canonical(item)] as const) .filter(([, item]) => item !== undefined) .sort(([left], [right]) => left.localeCompare(right)); if (entries.length === 0) return undefined; return Object.fromEntries(entries); } return undefined; }; export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); export const fieldMask = (fields: Array) => fields.filter((field): field is string => typeof field === "string").join(","); export const sameText = (left: string | undefined, right: string | undefined) => (left ?? "") === (right ?? ""); export const replaceOnIdentity = (input: { previousId: string | undefined; nextId: string | undefined; previousLocation: string; nextLocation: string; extra?: boolean; }) => { const replace = (input.extra ?? false) || (input.previousId !== undefined && input.nextId !== undefined && input.nextId !== input.previousId) || input.previousLocation !== input.nextLocation; if (!replace) return undefined; const samePhysical = input.previousLocation === input.nextLocation && input.previousId !== undefined && input.nextId === input.previousId; return { action: "replace" as const, deleteFirst: samePhysical, }; }; /** * Wait for an Infrastructure Manager operation; previews and deployment * groups run Terraform and can take several minutes. ALREADY_EXISTS * (code 6) counts as success (create race); with `notFoundOk`, so does * NOT_FOUND (code 5, delete race). */ export const waitForOperation = (operation: config.Operation, options?: { notFoundOk?: boolean }) => waitForGcpOperation(operation, (name) => config.getProjectsLocationsOperations({ name }), { budget: "20 minutes", }).pipe( Effect.catchIf( (error) => error._tag === "GCP.OperationFailed" && (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), () => Effect.succeed(operation), ), ); export const waitUntilExists = ( get: Effect.Effect, name: string, ): Effect.Effect, E | ResourceNotResolved, R> => get.pipe( Effect.filterOrFail( (value): value is NonNullable => value != null, () => new ResourceNotResolved({ resourceName: name }), ), Effect.retry({ while: (error) => error instanceof ResourceNotResolved, times: 8, schedule: Schedule.spaced("1 second"), }), ); export const waitUntilGone = ( get: Effect.Effect, name: string, ): Effect.Effect => get.pipe( Effect.filterOrFail( (value) => value === undefined, () => new ResourceStillExists({ resourceName: name }), ), Effect.retry({ while: (error) => error instanceof ResourceStillExists, times: 10, schedule: Schedule.spaced("2 seconds"), }), Effect.asVoid, ); export const listAtLocation = ( project: string, region: string, list: (parent: string) => Effect.Effect, ): Effect.Effect => // Prefer the all-locations wildcard; fall back to the default region // (whose error, if any, propagates). list(`projects/${project}/locations/-`).pipe( Effect.catch(() => list(`projects/${project}/locations/${region}`)), ); export const listLabeledPages = ( pages: Stream.Stream, items: (page: Page) => readonly A[] | undefined, labelsOf: (item: A) => Record | null | undefined, ): Effect.Effect => pages.pipe( Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))), Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), );