import * as apigateway from "@distilled.cloud/gcp/apigateway_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 DEFAULT_LOCATION = "global";
export const MAX_NAME_LENGTH = 63;
export const MIN_NAME_LENGTH = 4;
export type ApiConfigFile = {
/** File path (for example `openapi.yaml`). */
path: string;
/**
* UTF-8 file contents. Alchemy base64-encodes them for the API Gateway
* wire format.
*/
contents: string;
};
export type ApiConfigOpenApiDocument = {
/** OpenAPI Specification document file. */
document: ApiConfigFile;
};
export type ApiConfigGrpcServiceDefinition = {
/** Uncompiled proto sources associated with the descriptor set. */
source?: readonly ApiConfigFile[];
/** File descriptor set generated by protoc. */
fileDescriptorSet?: ApiConfigFile;
};
export class ResourceNotResolved extends Data.TaggedError("GCP.ApiGateway.NotResolved")<{
resourceName: string;
}> {}
export class ResourceStillExists extends Data.TaggedError("GCP.ApiGateway.StillExists")<{
resourceName: string;
}> {}
export class ResourceNotReady extends Data.TaggedError("GCP.ApiGateway.NotReady")<{
resourceName: string;
state: string;
}> {}
export class ResourceFailed extends Data.TaggedError("GCP.ApiGateway.Failed")<{
resourceName: string;
state: 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 = "apigw"): string => {
let next = name
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "");
if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "a"}${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`;
if (next.length < MIN_NAME_LENGTH) {
next = `${next}${"x".repeat(MIN_NAME_LENGTH)}`.slice(0, MIN_NAME_LENGTH);
}
return next.slice(0, MAX_NAME_LENGTH);
};
export const locationParent = (project: string) =>
`projects/${project}/locations/${DEFAULT_LOCATION}`;
export const expandApi = (value: string, project: string) => {
const trimmed = value.replace(/\/+$/, "");
if (trimmed.includes("/apis/")) return trimmed;
return `${locationParent(project)}/apis/${trimmed}`;
};
export const resourceName = (api: string, apiConfigId: string) => `${api}/configs/${apiConfigId}`;
export const toPhysicalId = (
id: string,
explicit: string | undefined,
existing: string | undefined,
fallback = "apigw",
) =>
Effect.gen(function* () {
if (explicit !== undefined) return explicit;
if (existing !== undefined) return existing;
return rfc1035(
yield* createPhysicalName({
id,
maxLength: MAX_NAME_LENGTH,
lowercase: true,
}),
fallback,
);
});
export const parseName = (name: string, collection: 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]! : DEFAULT_LOCATION,
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 userLabels = (
labels: Record<string, string | undefined> | null | undefined,
): Record<string, string> => stripInternalLabels(tagRecord(labels));
export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
export const sameText = (left: string | undefined, right: string | undefined) =>
(left ?? "") === (right ?? "");
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<string, unknown>)
.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 sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
export const fieldMask = (fields: Array<string | false | undefined>) =>
fields.filter((field): field is string => typeof field === "string").join(",");
export const replaceOnIdentity = (input: {
previousId: string | undefined;
nextId: string | undefined;
previousParent?: string;
nextParent?: string;
extra?: boolean;
}) => {
const parentChanged =
(input.previousParent ?? "") !== "" &&
(input.nextParent ?? "") !== "" &&
(input.previousParent ?? "") !== (input.nextParent ?? "");
const replace =
(input.extra ?? false) ||
parentChanged ||
(input.previousId !== undefined &&
input.nextId !== undefined &&
input.nextId !== input.previousId);
if (!replace) return undefined;
const samePhysical =
!parentChanged && input.previousId !== undefined && input.nextId === input.previousId;
return {
action: "replace" as const,
deleteFirst: samePhysical,
};
};
export const encodeContents = (contents: string) =>
Effect.sync(() => Buffer.from(contents, "utf8").toString("base64"));
export const encodeFile = (file: ApiConfigFile) =>
Effect.gen(function* () {
return {
path: file.path,
contents: yield* encodeContents(file.contents),
};
});
export const encodeOpenApiDocuments = (
documents: readonly ApiConfigOpenApiDocument[] | undefined,
) =>
documents === undefined
? Effect.undefined
: Effect.forEach(documents, (document) =>
Effect.gen(function* () {
return { document: yield* encodeFile(document.document) };
}),
);
export const encodeFiles = (files: readonly ApiConfigFile[] | undefined) =>
files === undefined ? Effect.undefined : Effect.forEach(files, encodeFile);
export const encodeGrpcServices = (
services: readonly ApiConfigGrpcServiceDefinition[] | undefined,
) =>
services === undefined
? Effect.undefined
: Effect.forEach(services, (service) =>
Effect.gen(function* () {
return {
source: yield* encodeFiles(service.source),
fileDescriptorSet: service.fileDescriptorSet
? yield* encodeFile(service.fileDescriptorSet)
: undefined,
};
}),
);
/**
* Wait for an API Gateway long-running operation. API configs take several
* minutes to roll out. An operation that finished with `ALREADY_EXISTS` (6)
* is a lost create race; `notFoundOk` also accepts `NOT_FOUND` (5).
*/
export const waitForOperation = (
operation: apigateway.ApigatewayOperation,
options?: { notFoundOk?: boolean },
) =>
waitForGcpOperation(
operation,
(name) =>
apigateway.getProjectsLocationsOperations({ name }).pipe(
Effect.catchTag("NotFound", (error) =>
options?.notFoundOk === true
? Effect.succeed<apigateway.ApigatewayOperation>({
name,
done: true,
})
: Effect.fail(error),
),
),
{ budget: "20 minutes" },
).pipe(
Effect.catchIf(
(error) =>
error._tag === "GCP.OperationFailed" &&
(error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
() => Effect.void,
),
Effect.asVoid,
);
export const waitUntilExists = <A, E, R>(
get: Effect.Effect<A | undefined, E, R>,
name: string,
): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
get.pipe(
Effect.filterOrFail(
(value): value is NonNullable<A> => value != null,
() => new ResourceNotResolved({ resourceName: name }),
),
Effect.retry({
while: (error) => error instanceof ResourceNotResolved,
times: 8,
schedule: Schedule.spaced("1 second"),
}),
);
export const waitUntilGone = <A, E, R>(
get: Effect.Effect<A | undefined, E, R>,
name: string,
): Effect.Effect<void, E | ResourceStillExists, R> =>
get.pipe(
Effect.filterOrFail(
(value) => value === undefined,
() => new ResourceStillExists({ resourceName: name }),
),
Effect.retry({
while: (error) => error instanceof ResourceStillExists,
times: 10,
schedule: Schedule.spaced("3 seconds"),
}),
Effect.asVoid,
);
const FAILED_STATES = new Set(["FAILED"]);
const READY_STATES = new Set(["ACTIVE"]);
export const waitUntilReady = <A, E, R>(
get: Effect.Effect<A | undefined, E, R>,
name: string,
stateOf: (value: NonNullable<A>) => string | undefined,
options?: {
times?: number;
interval?: `${number} seconds`;
},
): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceFailed | ResourceNotReady, R> =>
get.pipe(
Effect.filterOrFail(
(value): value is NonNullable<A> => value != null,
() => new ResourceNotResolved({ resourceName: name }),
),
Effect.filterOrFail(
(value) => !FAILED_STATES.has((stateOf(value) ?? "").toUpperCase()),
(value) =>
new ResourceFailed({
resourceName: name,
state: (stateOf(value) ?? "").toUpperCase(),
}),
),
Effect.filterOrFail(
(value) => READY_STATES.has((stateOf(value) ?? "").toUpperCase()),
(value) =>
new ResourceNotReady({
resourceName: name,
state: (stateOf(value) ?? "").toUpperCase(),
}),
),
Effect.retry({
while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved,
times: options?.times ?? 10,
schedule: Schedule.spaced(options?.interval ?? "8 seconds"),
}),
);
const emptyList = <A>() => Effect.succeed<A[]>([]);
export const collectPages = <Page, Item, E, R>(
pages: Stream.Stream<Page, E, R>,
items: (page: Page) => readonly Item[] | null | undefined,
) =>
pages.pipe(
Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
);
export const listApis = (parent: string) =>
parent.length === 0
? emptyList<apigateway.ApigatewayApi>()
: collectPages(
apigateway.listProjectsLocationsApis.pages({
parent,
pageSize: 1000,
}),
(page) => page.apis,
).pipe(Effect.catchTag("NotFound", () => emptyList<apigateway.ApigatewayApi>()));
export const listConfigs = (parent: string) =>
parent.length === 0
? emptyList<apigateway.ApigatewayApiConfig>()
: collectPages(
apigateway.listProjectsLocationsApisConfigs.pages({
parent,
pageSize: 1000,
}),
(page) => page.apiConfigs,
).pipe(Effect.catchTag("NotFound", () => emptyList<apigateway.ApigatewayApiConfig>()));
export const listChildResources = <A, E, R>(
parents: readonly { name?: string }[],
list: (name: string) => Effect.Effect<A[], E, R>,
) =>
Effect.forEach(
parents.filter((parent) => (parent.name ?? "").length > 0),
(parent) => list(parent.name!),
{ concurrency: 4 },
).pipe(Effect.map((groups) => groups.flat()));