diff --git a/.github/workflows/api-package-sync.yml b/.github/workflows/api-package-sync.yml index d651f7b49d..3ac1084ab4 100644 --- a/.github/workflows/api-package-sync.yml +++ b/.github/workflows/api-package-sync.yml @@ -28,13 +28,16 @@ jobs: env: SUPABASE_API_URL: https://api.supabase.com + - name: Regenerate API commands + run: pnpm --filter supabase run api-commands:generate + - name: Format API package run: pnpm run fmt:fix - name: Check for generated changes id: check run: | - if git diff --ignore-space-at-eol --exit-code --quiet packages/api/src/generated packages/api/scripts/openapi-source.json; then + if git diff --ignore-space-at-eol --exit-code --quiet packages/api/src/generated packages/api/scripts/openapi-source.json apps/cli/src/commands/api/generated.ts apps/cli/src/commands/api/generated.md; then echo "No generated changes detected." echo "has_changes=false" >> "$GITHUB_OUTPUT" else diff --git a/.oxlintrc.json b/.oxlintrc.json index f48e4f2a84..a0076f3df5 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -10,6 +10,8 @@ ".repos", /* Generated from the OpenAPI spec by `packages/api/scripts/generate.ts`. */ "packages/api/src/generated/contracts.ts", + // Generated command data, whose API paths are data rather than hand-built requests. + "apps/cli/src/commands/api/generated.ts", // Generated by `supabase gen types` (see `gen:feedback-types` in apps/cli). "apps/cli/src/shared/feedback/database.types.ts", /* Standalone Node shim built with `bun build --target node` that does not use Effect. */ diff --git a/apps/cli/AGENTS.md b/apps/cli/AGENTS.md index c6b5879aaa..ae458e875f 100644 --- a/apps/cli/AGENTS.md +++ b/apps/cli/AGENTS.md @@ -24,6 +24,9 @@ src/commands// .errors.ts # domain errors ``` +Generated Management API commands have no folder of their own; the generated +[`src/commands/api/generated.md`](src/commands/api/generated.md) is their per-command reference. + Register every command in `src/cli/root.ts`. Keep `.format.ts` and `.encoders.ts` pure. Handler phase spans are named `.`; see the root tracing rule. Read `src/shared/` and the command-level infrastructure under diff --git a/apps/cli/package.json b/apps/cli/package.json index 4460882edc..5a48fcd702 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -24,6 +24,8 @@ "access": "public" }, "scripts": { + "api-commands:check": "bun scripts/generate-api-commands.ts --check", + "api-commands:generate": "bun scripts/generate-api-commands.ts", "build": "pnpm build:binary && pnpm build:shim", "build:binary": "bun scripts/build-binary.ts", "build:shim": "bun build src/shared/cli/bin.ts --outfile dist/supabase.js --target node", diff --git a/apps/cli/schemas/config/v1.json b/apps/cli/schemas/config/v1.json index b0c2f32069..d07bc06b9e 100644 --- a/apps/cli/schemas/config/v1.json +++ b/apps/cli/schemas/config/v1.json @@ -4331,6 +4331,18 @@ } ] }, + "warehouse": { + "description": "Enable the experimental warehouse command family.", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "pattern": "^env\\((.*)\\)$" + } + ] + }, "stack": { "description": "Use the new local stack backend for start, stop, and status, and for --local targets of the db, migration, test db, gen types, inspect, and pull command families.", "anyOf": [ @@ -9256,6 +9268,18 @@ } ] }, + "warehouse": { + "description": "Enable the experimental warehouse command family.", + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "string", + "pattern": "^env\\((.*)\\)$" + } + ] + }, "stack": { "description": "Use the new local stack backend for start, stop, and status, and for --local targets of the db, migration, test db, gen types, inspect, and pull command families.", "anyOf": [ diff --git a/apps/cli/scripts/api-command-derive.ts b/apps/cli/scripts/api-command-derive.ts new file mode 100644 index 0000000000..51a426853e --- /dev/null +++ b/apps/cli/scripts/api-command-derive.ts @@ -0,0 +1,1103 @@ +import type { OperationId } from "@supabase/api/effect"; +import { isDeepStrictEqual } from "node:util"; +import { Cause, Exit, Predicate, Schema } from "effect"; +import { ROOT_GLOBAL_FLAGS } from "../src/command-internal/global-flags.ts"; +import type { ApiNoun, ApiCommandPolicy } from "../src/commands/api/api-command-policy.ts"; +import type { + ApiCommandBinding, + ApiCommandEntry, + ApiCommandFlag, + ApiCommandWait, + ApiPollTarget, +} from "../src/commands/api/api-command.model.ts"; + +type JsonObject = Readonly>; + +/** Flags a generated command may not redeclare: the registered globals plus those the runtime adds itself. */ +const RESERVED_FLAGS: ReadonlySet = new Set([ + ...ROOT_GLOBAL_FLAGS.map((flag) => flag.id), + "body", + "file", + "remote", + "project-ref", + "dry-run", + "wait", + "timeout", + "help", +]); + +const CREDENTIAL_TOKENS: ReadonlySet = new Set([ + "password", + "secret", + "token", + "key", + "private", +]); + +const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; +const KEBAB = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/u; +/** Headers the request builder owns; a spec may declare them, and they get no flag. */ +const CLIENT_HEADERS: ReadonlySet = new Set(["authorization", "content-type", "accept"]); + +export class ApiCommandGenerationError extends Schema.TaggedError()( + "ApiCommandGenerationError", + { problems: Schema.Array(Schema.String) }, +) { + override get message(): string { + return this.problems.map((problem) => `- ${problem}`).join("\n"); + } +} + +const StatusMapping = { + status: Schema.String, + succeeded: Schema.Array(Schema.String), + failed: Schema.Array(Schema.String), + error: Schema.optionalKey(Schema.String), +}; + +/** How to tell that the resource a read operation returns has settled. */ +type ApiCommandPoll = Pick; + +const XOperationSchema = Schema.Struct({ + group: Schema.optionalKey(Schema.String), + method: Schema.optionalKey(Schema.String), + poll: Schema.optionalKey( + Schema.Struct({ ...StatusMapping, inspect: Schema.optionalKey(Schema.String) }), + ), +}); + +const decodeXOperation = Schema.decodeUnknownExit(XOperationSchema, { + onExcessProperty: "error", +}); + +/** + * An `x-operation` block: an optional command name and an optional poll mapping. A name generates + * a command only for operations in the generated list. + */ +type ParsedXOperation = + | { + readonly kind: "valid"; + readonly name?: { readonly group: string; readonly method: string }; + readonly poll?: ApiCommandPoll; + readonly inspect?: string; + } + | { readonly kind: "invalid"; readonly reason: string }; + +const statusMapping = (poll: ApiCommandPoll): ApiCommandPoll => ({ + status: poll.status, + succeeded: poll.succeeded, + failed: poll.failed, + ...(poll.error === undefined ? {} : { error: poll.error }), +}); + +const parseXOperation = (block: unknown): ParsedXOperation => { + const decoded = decodeXOperation(block); + if (Exit.isFailure(decoded)) return { kind: "invalid", reason: Cause.pretty(decoded.cause) }; + const { group, method, poll } = decoded.value; + if ((group === undefined) !== (method === undefined)) { + return { kind: "invalid", reason: "a command name needs both group and method" }; + } + if (group === undefined && poll === undefined) { + return { kind: "invalid", reason: "set group and method, poll, or both" }; + } + if (poll?.inspect === "") { + return { kind: "invalid", reason: "poll.inspect must name an operation" }; + } + return { + kind: "valid", + ...(group === undefined || method === undefined ? {} : { name: { group, method } }), + ...(poll === undefined ? {} : { poll: statusMapping(poll) }), + ...(poll?.inspect === undefined ? {} : { inspect: poll.inspect }), + }; +}; + +interface DeriveInput { + readonly policies?: Readonly>; + /** The parsed OpenAPI document. */ + readonly spec: JsonObject; + /** Operation ids that generate commands; the roots whose response `links` are followed. */ + readonly generated: ReadonlyArray; + readonly nouns: Readonly>; + /** Kebab-case operation id to the camelCase key of the typed client's `operationDefinitions`. */ + readonly operationIdMap: Readonly>; + /** Names of the hand-written root commands; a generated noun may not reuse one. */ + readonly handWrittenRoots: ReadonlySet; +} + +interface DeriveResult { + readonly entries: ReadonlyArray; + readonly pollTargets: ReadonlyArray; + /** Success status code of each generated command's operation, for the reference. */ + readonly successStatuses: ReadonlyMap; + readonly problems: ReadonlyArray; +} + +interface Operation { + readonly id: string; + readonly method: (typeof HTTP_METHODS)[number]; + readonly node: JsonObject; + readonly pathItem: JsonObject; +} + +interface OperationMetadata { + readonly group: string; + readonly method: string; + readonly poll?: ApiCommandPoll; +} + +interface FlagShape { + readonly type: ApiCommandFlag["type"]; + readonly choices?: ReadonlyArray; + readonly repeatable: boolean; +} + +const asRecord = (value: unknown): JsonObject | undefined => + Predicate.isReadonlyObject(value) ? value : undefined; + +const asArray = (value: unknown): ReadonlyArray => (Array.isArray(value) ? value : []); + +const asString = (value: unknown): string | undefined => + typeof value === "string" ? value : undefined; + +const MAX_REF_DEPTH = 32; + +const lookupRef = (spec: JsonObject, ref: string): unknown => { + if (!ref.startsWith("#/")) return undefined; + let target: unknown = spec; + for (const segment of ref.slice(2).split("/")) { + target = asRecord(target)?.[segment.replaceAll("~1", "/").replaceAll("~0", "~")]; + } + return target; +}; + +/** Follows `$ref` chains within the document; unresolvable references yield `undefined`. */ +const resolve = (spec: JsonObject, value: unknown): unknown => { + let current = value; + for (let depth = 0; depth < MAX_REF_DEPTH; depth++) { + const ref = asString(asRecord(current)?.$ref); + if (ref === undefined) return current; + current = lookupRef(spec, ref); + } + return undefined; +}; + +const COMPOSITION_KEYWORDS = ["anyOf", "oneOf", "allOf"]; + +/** + * The fields of an envelope's attributes: a plain object, or an `anyOf` of closed objects that + * share identical properties and differ only in what they require. A field is required only when + * every branch requires it. + */ +const deriveAttributeFields = ( + spec: JsonObject, + attributes: JsonObject | undefined, +): { readonly properties: JsonObject; readonly required: ReadonlyArray } | undefined => { + if (attributes === undefined) return undefined; + const properties = asRecord(attributes.properties); + const composed = COMPOSITION_KEYWORDS.filter((keyword) => keyword in attributes); + if (composed.length === 0) { + return attributes.type === "object" && properties !== undefined + ? { properties, required: asArray(attributes.required) } + : undefined; + } + if (composed.length !== 1 || composed[0] !== "anyOf" || properties !== undefined) { + return undefined; + } + const branches = asArray(attributes.anyOf).map((branch) => asRecord(resolve(spec, branch))); + const resolvedProperties = (branch: JsonObject | undefined) => + Object.entries(asRecord(branch?.properties) ?? {}).map( + ([field, schema]) => [field, resolve(spec, schema)] as const, + ); + const [first] = branches; + const firstProperties = asRecord(first?.properties); + if ( + first === undefined || + firstProperties === undefined || + branches.length < 2 || + !branches.every( + (branch) => + branch?.type === "object" && + branch.additionalProperties === false && + isDeepStrictEqual(resolvedProperties(branch), resolvedProperties(first)), + ) + ) { + return undefined; + } + return { + properties: firstProperties, + required: asArray(first.required).filter((field) => + branches.every((branch) => asArray(branch?.required).includes(field)), + ), + }; +}; + +const SCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf"] as const; + +const escapePointer = (segment: string): string => + segment.replaceAll("~", "~0").replaceAll("/", "~1"); + +/** The first 2xx status code; every command and poll target needs its success response to be JSON. */ +const successStatus = ( + spec: JsonObject, + operation: Operation, + fail: (reason: string) => void, +): number | undefined => { + const responses = asRecord(operation.node.responses) ?? {}; + const statuses: Array = []; + for (const code of Object.keys(responses).sort()) { + if (!code.startsWith("2")) continue; + const status = Number(code); + if (!Number.isInteger(status)) { + fail(`unsupported in this runtime: response status "${code}"`); + continue; + } + const content = asRecord(asRecord(resolve(spec, responses[code]))?.content) ?? {}; + if (jsonMediaType(content) === undefined) { + fail( + `unsupported in this runtime: ${code} response is not JSON (${Object.keys(content).join(", ") || "no content"})`, + ); + continue; + } + statuses.push(status); + } + if (statuses.length === 0 && !Object.keys(responses).some((code) => code.startsWith("2"))) { + fail("operation has no 2xx response"); + } + return statuses[0]; +}; + +const STABILITY_NOTICE = /\s*This endpoint is currently in its \*\*[^*]+\*\* stage\.\s*$/u; + +/** The description without the stage paragraph the spec appends to it; `undefined` when nothing is left. */ +const stripStabilityNotice = (description: string | undefined): string | undefined => { + const stripped = description?.replace(STABILITY_NOTICE, "").trim(); + return stripped === undefined || stripped === "" ? undefined : stripped; +}; + +const kebabCase = (field: string): string => + field + .replace(/([a-z0-9])([A-Z])/gu, "$1-$2") + .replaceAll("_", "-") + .toLowerCase(); + +/** `tables` to `table`, `entries` to `entry`; names ending in `ss`, `us` or `is` stay as they are. */ +const singular = (kebab: string): string => { + if (kebab.endsWith("ies")) return `${kebab.slice(0, -3)}y`; + if (/(?:ss|us|is)$/u.test(kebab) || !kebab.endsWith("s")) return kebab; + return kebab.slice(0, -1); +}; + +const credentialLike = (field: string): boolean => + kebabCase(field) + .split("-") + .some((token) => CREDENTIAL_TOKENS.has(token.replace(/s$/u, ""))); + +const describeScalar = ( + spec: JsonObject, + raw: unknown, +): Pick | undefined => { + const schema = asRecord(resolve(spec, raw)); + if (schema === undefined) return undefined; + if (["anyOf", "oneOf", "allOf", "not"].some((keyword) => keyword in schema)) return undefined; + const type = schema.type; + if (type !== "string" && type !== "boolean") return undefined; + if (schema.enum === undefined) return { type }; + const choices = asArray(schema.enum); + if (type !== "string" || !choices.every((choice) => typeof choice === "string")) { + return undefined; + } + return { type, choices: choices.filter(Predicate.isString) }; +}; + +const describeFlagSchema = (spec: JsonObject, raw: unknown): FlagShape | undefined => { + const schema = asRecord(resolve(spec, raw)); + if (schema?.type === "array") { + const items = describeScalar(spec, schema.items); + return items === undefined ? undefined : { ...items, repeatable: true }; + } + const scalar = describeScalar(spec, raw); + return scalar === undefined ? undefined : { ...scalar, repeatable: false }; +}; + +/** Whether a schema is a number or integer, or an array of them. */ +const isNumeric = (spec: JsonObject, raw: unknown): boolean => { + const schema = asRecord(resolve(spec, raw)); + const item = schema?.type === "array" ? asRecord(resolve(spec, schema.items)) : schema; + return item?.type === "integer" || item?.type === "number"; +}; + +const isSecretField = (spec: JsonObject, raw: unknown): boolean => { + const schema = asRecord(resolve(spec, raw)); + return ( + schema?.writeOnly === true || schema?.format === "password" || schema?.["x-sensitive"] === true + ); +}; + +/** + * The dotted path of the first secret a schema holds at any depth: a schema marked secret or a + * property with a credential-like name. `visited` ends the walk on a recursive schema. + */ +const findSecret = ( + spec: JsonObject, + raw: unknown, + path: string, + visited: Set = new Set(), +): string | undefined => { + const schema = asRecord(resolve(spec, raw)); + if (schema === undefined || visited.has(schema)) return undefined; + visited.add(schema); + if (isSecretField(spec, schema)) return path; + const properties = Object.entries(asRecord(schema.properties) ?? {}); + const credential = properties.find(([name]) => credentialLike(name)); + if (credential !== undefined) return `${path}.${credential[0]}`; + const children: ReadonlyArray = [ + ...properties.map(([name, child]) => [`${path}.${name}`, child] as const), + [`${path}[]`, schema.items], + [path, schema.additionalProperties], + ...Object.values(asRecord(schema.patternProperties) ?? {}).map( + (child) => [path, child] as const, + ), + ...SCHEMA_LIST_KEYWORDS.flatMap((keyword) => + asArray(schema[keyword]).map((child) => [path, child] as const), + ), + ]; + for (const [childPath, child] of children) { + const found = findSecret(spec, child, childPath, visited); + if (found !== undefined) return found; + } + return undefined; +}; + +const schemaDescription = (spec: JsonObject, raw: unknown): string | undefined => + asString(asRecord(resolve(spec, raw))?.description); + +const pointerSegments = (pointer: string): ReadonlyArray => + pointer + .slice(1) + .split("/") + .map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")); + +const resolvePointer = (spec: JsonObject, root: unknown, pointer: string): unknown => { + if (!pointer.startsWith("/")) return undefined; + let current = resolve(spec, root); + for (const segment of pointerSegments(pointer)) { + const node = asRecord(current); + if (node === undefined) return undefined; + const property = asRecord(node.properties)?.[segment]; + if (property !== undefined) { + current = resolve(spec, property); + } else if (node.type === "array" && /^\d+$/u.test(segment) && node.items !== undefined) { + current = resolve(spec, node.items); + } else { + return undefined; + } + } + return current; +}; + +/** Whether `pointer` names a property that is required at every object level it passes through. */ +const pointerAlwaysPresent = (spec: JsonObject, root: unknown, pointer: string): boolean => { + if (!pointer.startsWith("/")) return false; + let current = resolve(spec, root); + for (const segment of pointerSegments(pointer)) { + const node = asRecord(current); + const property = asRecord(node?.properties)?.[segment]; + if (property === undefined || !asArray(node?.required).includes(segment)) return false; + current = resolve(spec, property); + if (asRecord(current)?.nullable === true) return false; + } + return true; +}; + +/** The JSON media type a response offers: `application/json` or a `+json` suffix type. */ +const jsonMediaType = (content: JsonObject): string | undefined => + Object.keys(content).find((type) => type === "application/json" || type.endsWith("+json")); + +const hasSeveralSuccessResponses = (operation: Operation): boolean => + Object.keys(asRecord(operation.node.responses) ?? {}).filter((code) => code.startsWith("2")) + .length > 1; + +const successSchema = (spec: JsonObject, operation: Operation): unknown => { + const responses = asRecord(operation.node.responses) ?? {}; + for (const code of Object.keys(responses).sort()) { + if (!code.startsWith("2")) continue; + const response = asRecord(resolve(spec, responses[code])); + const content = asRecord(response?.content) ?? {}; + const mediaType = jsonMediaType(content); + const media = mediaType === undefined ? undefined : asRecord(content[mediaType]); + if (media?.schema !== undefined) return media.schema; + } + return undefined; +}; + +const collectOperations = (spec: JsonObject): ReadonlyMap => { + const operations = new Map(); + for (const rawItem of Object.values(asRecord(spec.paths) ?? {})) { + const pathItem = asRecord(rawItem); + if (pathItem === undefined) continue; + for (const method of HTTP_METHODS) { + const node = asRecord(pathItem[method.toLowerCase()]); + const id = asString(node?.operationId); + if (node === undefined || id === undefined) continue; + operations.set(id, { + id, + method, + node, + pathItem, + }); + } + } + return operations; +}; + +const operationParameters = (spec: JsonObject, operation: Operation): ReadonlyArray => + [...asArray(operation.pathItem.parameters), ...asArray(operation.node.parameters)] + .map((raw) => asRecord(resolve(spec, raw))) + .filter(Predicate.isNotUndefined); + +/** Reads each generated operation's `x-operation`. */ +const readMetadata = ( + operations: ReadonlyMap, + generated: ReadonlyArray, + problems: Array, +): ReadonlyMap => { + const metadata = new Map(); + for (const operationId of generated) { + const operation = operations.get(operationId); + if (operation === undefined) { + problems.push(`${operationId}: generated operation has no operation in the spec`); + continue; + } + const block = operation.node["x-operation"]; + if (block === undefined) { + problems.push(`${operationId}: no command name; set x-operation group and method`); + continue; + } + const parsed = parseXOperation(block); + if (parsed.kind === "invalid") { + problems.push(`${operationId}: invalid x-operation: ${parsed.reason}`); + continue; + } + const { name, poll } = parsed; + if (name === undefined) { + problems.push(`${operationId}: no command name; set x-operation group and method`); + continue; + } + metadata.set(operationId, { ...name, ...(poll === undefined ? {} : { poll }) }); + if (poll !== undefined && operation.method !== "GET") { + problems.push(`${operationId}: poll belongs on a read operation, not ${operation.method}`); + } + } + return metadata; +}; + +const requireExperimental = (operation: Operation, fail: (reason: string) => void): void => { + if (asString(operation.node["x-scalar-stability"]) !== "experimental") { + fail("only operations marked experimental can be generated (x-scalar-stability)"); + } +}; + +const requireOneWait = ( + ownPoll: ApiCommandPoll | undefined, + linkedRead: string | undefined, + fail: (reason: string) => void, +): void => { + if (ownPoll !== undefined && linkedRead !== undefined) { + fail(`declares poll and also links to the polled operation "${linkedRead}"; use one`); + } +}; + +/** The first operation declaring `poll` that an operation's 2xx response `links` target. */ +const polledLinkTarget = ( + spec: JsonObject, + operations: ReadonlyMap, + operation: Operation, +): string | undefined => { + const responses = asRecord(operation.node.responses) ?? {}; + for (const code of Object.keys(responses).sort()) { + if (!code.startsWith("2")) continue; + const links = asRecord(asRecord(resolve(spec, responses[code]))?.links) ?? {}; + for (const rawLink of Object.values(links)) { + const targetId = asString(asRecord(resolve(spec, rawLink))?.operationId); + const target = targetId === undefined ? undefined : operations.get(targetId); + if (asRecord(target?.node["x-operation"])?.poll !== undefined) return targetId; + } + } + return undefined; +}; + +const pollWait = ( + read: string, + params: Readonly>, + poll: ApiCommandPoll, +): ApiCommandWait => ({ + read, + params, + status: poll.status, + succeeded: poll.succeeded, + failed: poll.failed, + ...(poll.error === undefined ? {} : { error: poll.error }), +}); + +const RESPONSE_POINTER = /^\$response\.body#(\/.*)$/u; +const REQUEST_PATH = /^\$request\.path\.(.+)$/u; + +/** A polled read that is not a generated command, reached through a response link, with the operation that inspects its state. */ +interface HiddenRead { + readonly poll: ApiCommandPoll; + readonly inspect: string; +} + +/** + * The wait a command's 2xx response `links` declare: the one link whose target operation has + * `poll`. A target that is not a generated operation needs `poll.inspect` and is recorded in + * `hidden`; links without `poll` are ignored. + */ +const linkedWait = ( + spec: JsonObject, + operations: ReadonlyMap, + metadata: ReadonlyMap, + generated: ReadonlyArray, + hidden: Map, + operation: Operation, + fail: (reason: string) => void, +): ApiCommandWait | undefined => { + const responses = asRecord(operation.node.responses) ?? {}; + const waits: Array = []; + for (const code of Object.keys(responses).sort()) { + if (!code.startsWith("2")) continue; + const links = asRecord(asRecord(resolve(spec, responses[code]))?.links) ?? {}; + for (const [linkName, rawLink] of Object.entries(links)) { + const link = asRecord(resolve(spec, rawLink)); + const targetId = asString(link?.operationId); + if (link === undefined || targetId === undefined) { + fail(`link "${linkName}" must name its target with operationId`); + continue; + } + const target = operations.get(targetId); + if (target === undefined) { + fail(`link "${linkName}" targets unknown operation "${targetId}"`); + continue; + } + let poll: ApiCommandPoll | undefined; + if (generated.includes(targetId)) { + poll = metadata.get(targetId)?.poll; + } else { + const block = target.node["x-operation"]; + if (block === undefined) continue; + const parsed = parseXOperation(block); + if (parsed.kind === "invalid") { + fail( + `link "${linkName}" targets "${targetId}", whose x-operation is invalid: ${parsed.reason}`, + ); + } else if (parsed.poll !== undefined && parsed.inspect === undefined) { + fail( + `link "${linkName}" targets polled operation "${targetId}", which is not a generated command and sets no poll.inspect`, + ); + } else if (parsed.poll !== undefined && parsed.inspect !== undefined) { + poll = parsed.poll; + hidden.set(targetId, { poll, inspect: parsed.inspect }); + } + } + if (poll === undefined) continue; + + const params: Record = {}; + for (const [parameter, expression] of Object.entries(asRecord(link.parameters) ?? {})) { + const pointer = typeof expression === "string" ? RESPONSE_POINTER.exec(expression) : null; + const pathName = typeof expression === "string" ? REQUEST_PATH.exec(expression)?.[1] : null; + if (pointer?.[1] !== undefined) { + params[parameter] = pointer[1]; + } else if (pathName !== null && pathName !== undefined) { + const hasPath = (candidate: Operation) => + operationParameters(spec, candidate).some( + (item) => item.in === "path" && item.name === pathName, + ); + if (pathName !== "ref") { + fail( + `link "${linkName}" parameter "${parameter}": only "$request.path.ref" is supported in this runtime`, + ); + } else if (parameter !== pathName || !hasPath(target) || !hasPath(operation)) { + fail( + `link "${linkName}" parameter "${parameter}": "${String(expression)}" needs a path parameter of that name on both operations`, + ); + } + } else { + fail( + `link "${linkName}" parameter "${parameter}": unsupported expression ${JSON.stringify(expression)}`, + ); + } + } + waits.push(pollWait(targetId, params, poll)); + } + } + if (waits.length > 1) { + fail( + `more than one response link targets a polled operation (${waits.map((w) => w.read).join(", ")})`, + ); + return undefined; + } + return waits[0]; +}; + +/** Derives the generated commands from each operation's `x-operation` and collects every lint failure. */ +export function deriveApiCommands(input: DeriveInput): DeriveResult { + const { spec, generated, nouns, operationIdMap, handWrittenRoots } = input; + const operations = collectOperations(spec); + const problems: Array = []; + for (const id of Object.keys(input.policies ?? {})) { + if (!input.generated.includes(id)) + problems.push(`${id}: CLI policy requires an allowlisted command`); + } + const metadata = readMetadata(operations, generated, problems); + const hidden = new Map(); + const entries: Array = []; + const successStatuses = new Map(); + const commandOwners = new Map(); + const groupPaths = new Set(); + + for (const noun of Object.keys(nouns)) { + if (handWrittenRoots.has(noun)) { + problems.push(`noun "${noun}" is already a hand-written command`); + } + } + + for (const [operationId, name] of metadata) { + const { group, method } = name; + const fail = (reason: string) => problems.push(`${operationId}: ${reason}`); + const operation = operations.get(operationId); + if (operation === undefined) continue; + const definition = operationIdMap[operationId]; + if (definition === undefined) { + fail("operation is missing from the typed client; regenerate @supabase/api"); + continue; + } + const failuresBefore = problems.length; + + const command = [...group.split("."), method]; + if (!command.every((segment) => KEBAB.test(segment))) { + fail(`command "${command.join(" ")}" must be lowercase kebab-case words`); + } + const noun = nouns[command[0] ?? ""]; + if (noun === undefined) { + fail(`noun "${command[0]}" is missing from the nouns table`); + continue; + } + const commandKey = command.join(" "); + const owner = commandOwners.get(commandKey); + if (owner !== undefined) fail(`command "${commandKey}" is already generated by ${owner}`); + commandOwners.set(commandKey, operationId); + if (groupPaths.has(commandKey)) fail(`command "${commandKey}" is both a command and a group`); + for (let depth = 1; depth < command.length; depth += 1) { + const groupKey = command.slice(0, depth).join(" "); + if (depth < 2) continue; + if (commandOwners.has(groupKey)) fail(`command "${groupKey}" is both a command and a group`); + groupPaths.add(groupKey); + const subGroup = command.slice(1, depth).join("."); + if (noun.groups?.[subGroup] === undefined) { + fail(`group "${subGroup}" has no description in the nouns table`); + } + } + + requireExperimental(operation, fail); + const summary = asString(operation.node.summary); + if (summary === undefined) fail("operation has no summary"); + + const fields: Array<{ + readonly location: "query" | "body"; + readonly key: string; + readonly pointer?: string; + readonly shape: FlagShape; + readonly required: boolean; + readonly description: string | undefined; + readonly writeOnly: boolean; + }> = []; + + const pathBindings: Array = []; + const pathNames: Array = []; + const positionals: Array<{ + readonly name: string; + readonly parameter: string; + readonly description: string | undefined; + }> = []; + for (const parameter of operationParameters(spec, operation)) { + const parameterName = asString(parameter.name) ?? ""; + switch (parameter.in) { + case "path": { + pathNames.push(parameterName); + if (parameterName === "ref") { + pathBindings.push({ location: "path", name: "ref", source: "target" }); + break; + } + const shape = describeFlagSchema(spec, parameter.schema); + if (shape === undefined || shape.repeatable) { + fail(`unsupported in this runtime: path parameter "${parameterName}" is not a scalar`); + } else if (shape.type !== "string") { + fail(`unsupported in this runtime: path parameter "${parameterName}" is not a string`); + } else { + positionals.push({ + name: kebabCase(parameterName), + parameter: parameterName, + description: + asString(parameter.description) ?? schemaDescription(spec, parameter.schema), + }); + } + break; + } + case "header": { + if (!CLIENT_HEADERS.has(parameterName.toLowerCase())) { + fail(`unsupported in this runtime: header parameter "${parameterName}"`); + } + break; + } + case "query": { + const shape = describeFlagSchema(spec, parameter.schema); + if (parameterName === "dry_run") { + fail('unsupported in this runtime: server-side "dry_run" parameter'); + } else if (isSecretField(spec, parameter.schema)) { + fail( + `unsupported in this runtime: query parameter "${parameterName}" is a secret, and the dry-run preview masks only body fields`, + ); + } else if (shape === undefined || shape.repeatable) { + fail(`unsupported in this runtime: query parameter "${parameterName}" is not a scalar`); + } else { + fields.push({ + location: "query", + key: parameterName, + shape, + required: parameter.required === true, + description: + asString(parameter.description) ?? schemaDescription(spec, parameter.schema), + writeOnly: false, + }); + } + break; + } + default: + fail(`unsupported in this runtime: ${String(parameter.in)} parameter "${parameterName}"`); + } + } + + let body: ApiCommandEntry["body"]; + const requestBody = asRecord(resolve(spec, operation.node.requestBody)); + if (requestBody !== undefined) { + const content = asRecord(requestBody.content) ?? {}; + const mediaTypes = Object.keys(content); + const bodySchema = asRecord(resolve(spec, asRecord(content["application/json"])?.schema)); + const properties = asRecord(bodySchema?.properties); + if ( + mediaTypes.length !== 1 || + bodySchema?.type !== "object" || + properties === undefined || + ["anyOf", "oneOf", "allOf"].some((keyword) => keyword in bodySchema) + ) { + fail( + `unsupported in this runtime: request body (${mediaTypes.join(", ") || "none"}) is not a JSON object`, + ); + } else { + const data = asRecord(resolve(spec, properties.data)); + const dataProperties = asRecord(data?.properties); + const typeEnum = asArray(asRecord(resolve(spec, dataProperties?.type))?.enum); + const attributes = asRecord(resolve(spec, dataProperties?.attributes)); + const envelopeType = asString(typeEnum[0]); + const hasEnvelopeShape = + Object.keys(properties).length === 1 && + typeEnum.length === 1 && + envelopeType !== undefined; + const unboundDataKeys = Object.keys(dataProperties ?? {}).filter( + (key) => key !== "type" && key !== "attributes", + ); + if (hasEnvelopeShape && unboundDataKeys.length > 0) { + fail( + `unsupported in this runtime: envelope data declares ${unboundDataKeys.map((key) => `"${key}"`).join(", ")}, but only data.type and data.attributes are bound`, + ); + } + const attributeFields = hasEnvelopeShape + ? deriveAttributeFields(spec, attributes) + : undefined; + if ( + hasEnvelopeShape && + attributeFields === undefined && + COMPOSITION_KEYWORDS.some((keyword) => attributes !== undefined && keyword in attributes) + ) { + fail( + "unsupported in this runtime: envelope attributes use a schema composition other than an anyOf of closed objects over identical properties", + ); + } + const required = attributeFields?.required ?? []; + if (attributeFields === undefined) { + fail("unsupported in this runtime: request body is not a data envelope"); + } else if (envelopeType !== undefined) { + body = { contentType: "application/json", type: envelopeType }; + } + for (const [field, schema] of Object.entries(attributeFields?.properties ?? {})) { + const scalarShape = describeFlagSchema(spec, schema); + const secret = findSecret(spec, schema, field); + if (field === "dry_run") { + fail('unsupported in this runtime: server-side "dry_run" body field'); + } else if (scalarShape === undefined && isNumeric(spec, schema)) { + fail(`unsupported in this runtime: numeric body field "${field}"`); + } else if (scalarShape === undefined && secret !== undefined) { + fail( + `unsupported in this runtime: body field "${field}" ${secret === field ? "is a secret" : `holds the secret "${secret}"`}, and the dry-run preview masks only scalar flag values`, + ); + } + fields.push({ + location: "body", + key: field, + pointer: `/data/attributes/${escapePointer(field)}`, + shape: scalarShape ?? { type: "json", repeatable: false }, + required: required.includes(field), + description: schemaDescription(spec, schema), + writeOnly: secret !== undefined, + }); + } + } + } + + if (pathBindings.length === 0) { + fail('unsupported in this runtime: operation has no "ref" path parameter'); + } + const [positional, ...extraPositionals] = positionals; + if (extraPositionals.length > 0) { + fail('unsupported in this runtime: more than one path parameter besides "ref"'); + } + if (positional !== undefined) { + if (!KEBAB.test(positional.name)) { + fail(`argument "${positional.name}" must be lowercase kebab-case`); + } + pathBindings.push({ + location: "path", + name: positional.parameter, + source: "argument", + argument: positional.name, + }); + } + + const flags: Array = []; + const bindings: Array = [...pathBindings]; + const seenNames = new Set(); + const seenKeys = new Set(pathNames); + for (const field of fields) { + const flagName = + field.location === "body" && field.shape.repeatable + ? singular(kebabCase(field.key)) + : kebabCase(field.key); + if (!KEBAB.test(flagName)) fail(`flag "${flagName}" must be lowercase kebab-case`); + if (RESERVED_FLAGS.has(flagName)) { + fail(`flag "--${flagName}" (from "${field.key}") collides with a reserved runtime flag`); + } + if (seenNames.has(flagName)) { + fail(`flag "--${flagName}" (from "${field.key}") is produced twice`); + } + if (seenKeys.has(field.key)) { + fail( + `"${field.key}" is used by more than one of: path parameter, header parameter, query parameter, body field`, + ); + } + seenNames.add(flagName); + seenKeys.add(field.key); + const isSensitive = field.location === "body" && field.writeOnly; + if (field.location === "body" && credentialLike(field.key) && !isSensitive) { + fail( + `body field "${field.key}" looks like a credential; mark its schema writeOnly, format: password or x-sensitive`, + ); + } + bindings.push( + field.location === "body" && field.pointer !== undefined + ? { + location: "body", + name: field.key, + pointer: field.pointer, + source: "flag", + flag: flagName, + } + : { + location: "query", + name: field.key, + source: "flag", + flag: flagName, + }, + ); + flags.push({ + name: flagName, + type: field.shape.type, + ...(field.shape.choices === undefined ? {} : { choices: field.shape.choices }), + repeatable: field.shape.repeatable, + required: field.required, + ...(isSensitive ? { sensitive: true as const } : {}), + ...(field.description === undefined ? {} : { description: field.description }), + }); + } + + const linked = linkedWait(spec, operations, metadata, generated, hidden, operation, fail); + const ownPoll = name.poll; + requireOneWait(ownPoll, linked?.read, fail); + const wait = linked ?? (ownPoll === undefined ? undefined : pollWait(operationId, {}, ownPoll)); + if (wait !== undefined) { + lintWait({ spec, operations, operation, wait, fail }); + } + + const status = successStatus(spec, operation, fail); + if (problems.length > failuresBefore || summary === undefined) continue; + if (status === undefined) continue; + const description = stripStabilityNotice(asString(operation.node.description)); + const policy = input.policies?.[operationId]; + if (policy?.confirmDescription && (operation.method === "GET" || !description)) { + fail("confirmation details require a mutation with an API description"); + continue; + } + successStatuses.set(operationId, status); + entries.push({ + command, + operationId, + definition, + summary, + ...(description === undefined ? {} : { description }), + readOnly: operation.method === "GET", + ...policy, + ...(body === undefined ? {} : { body }), + ...(positional === undefined + ? {} + : { + argument: { + name: positional.name, + ...(positional.description === undefined + ? {} + : { description: positional.description }), + }, + }), + flags, + bindings, + ...(wait === undefined ? {} : { wait }), + }); + } + + entries.sort((left, right) => + left.command.join(" ").localeCompare(right.command.join(" "), "en"), + ); + const pollTargets: Array = []; + for (const [operationId, { poll, inspect: inspectId }] of [...hidden].toSorted(([a], [b]) => + a.localeCompare(b, "en"), + )) { + const operation = operations.get(operationId); + if (operation === undefined) continue; + const fail = (reason: string) => problems.push(`${operationId}: ${reason}`); + const definition = operationIdMap[operationId]; + if (definition === undefined) { + fail("polling target is missing from the typed client; regenerate @supabase/api"); + continue; + } + requireExperimental(operation, fail); + requireOneWait(poll, polledLinkTarget(spec, operations, operation), fail); + if (!generated.includes(inspectId)) { + fail(`inspect operation "${inspectId}" is not a generated operation`); + } + const inspect = entries.find((entry) => entry.operationId === inspectId); + if ( + inspect !== undefined && + (inspect.argument !== undefined || + inspect.body !== undefined || + inspect.flags.some((flag) => flag.required)) + ) { + fail(`inspect operation "${inspectId}" needs input beyond the project ref`); + } + if (inspect !== undefined && !inspect.readOnly) { + fail(`inspect operation "${inspectId}" must be a read-only command`); + } + const summary = asString(operation.node.summary); + if (summary === undefined) { + fail("polling target is missing a summary"); + continue; + } + if (successStatus(spec, operation, fail) === undefined) continue; + pollTargets.push({ operationId, definition, summary, inspect: inspectId }); + } + return { entries, pollTargets, successStatuses, problems }; +} + +function lintWait(input: { + readonly spec: JsonObject; + readonly operations: ReadonlyMap; + readonly operation: Operation; + readonly wait: ApiCommandWait; + readonly fail: (reason: string) => void; +}): void { + const { spec, operations, operation, wait, fail } = input; + const readOperation = operations.get(wait.read); + if (readOperation === undefined) { + fail(`wait.read "${wait.read}" has no operation in the spec`); + return; + } + if (readOperation.method !== "GET") { + fail(`wait.read "${wait.read}" must use GET`); + } + if (readOperation.node.requestBody !== undefined) { + fail(`wait.read "${wait.read}" must not require a request body`); + } + + if (hasSeveralSuccessResponses(operation)) { + fail("unsupported in this runtime: a wait needs a single 2xx response to resolve its pointers"); + } + if (readOperation !== operation && hasSeveralSuccessResponses(readOperation)) { + fail( + `unsupported in this runtime: wait.read "${wait.read}" has several 2xx responses, so its status pointers cannot be resolved`, + ); + } + + const readParameters = operationParameters(spec, readOperation); + if (!readParameters.some((parameter) => parameter.in === "path" && parameter.name === "ref")) { + fail(`wait.read "${wait.read}" must be scoped by a project ref path parameter`); + } + const suppliable = new Set( + readParameters + .filter( + (parameter) => + parameter.in === "query" || (parameter.in === "path" && parameter.name !== "ref"), + ) + .map((p) => asString(p.name)), + ); + const changeResponse = successSchema(spec, operation); + for (const [parameter, pointer] of Object.entries(wait.params)) { + if (!suppliable.has(parameter)) { + fail(`wait.params "${parameter}" is not a query or path parameter of ${wait.read}`); + } + if (resolvePointer(spec, changeResponse, pointer) === undefined) { + fail(`wait.params "${parameter}" pointer "${pointer}" does not resolve in the response`); + } else if (!pointerAlwaysPresent(spec, changeResponse, pointer)) { + fail( + `wait.params "${parameter}" pointer "${pointer}" is not required at every level of the response, so --wait could have nothing to poll with`, + ); + } + } + for (const parameter of readParameters) { + const parameterName = asString(parameter.name); + if ( + wait.read !== operation.id && + parameter.required === true && + parameterName !== undefined && + !(parameterName === "ref" && parameter.in === "path") && + wait.params[parameterName] === undefined + ) { + fail(`wait.params does not supply required parameter "${parameterName}" of ${wait.read}`); + } + } + + const readResponse = successSchema(spec, readOperation); + const status = resolvePointer(spec, readResponse, wait.status); + if (status === undefined) { + fail(`wait.status pointer "${wait.status}" does not resolve in the ${wait.read} response`); + } + if (wait.error !== undefined && resolvePointer(spec, readResponse, wait.error) === undefined) { + fail(`wait.error pointer "${wait.error}" does not resolve in the ${wait.read} response`); + } + if (wait.succeeded.length === 0) fail("wait.succeeded must list at least one status"); + const statusValues = asRecord(status)?.enum; + if (statusValues !== undefined) { + const allowed = asArray(statusValues); + for (const value of [...wait.succeeded, ...wait.failed]) { + if (!allowed.includes(value)) { + fail(`wait status "${value}" is not in the status enum of ${wait.read}`); + } + } + } +} diff --git a/apps/cli/scripts/api-command-derive.unit.test.ts b/apps/cli/scripts/api-command-derive.unit.test.ts new file mode 100644 index 0000000000..1b5e1d470c --- /dev/null +++ b/apps/cli/scripts/api-command-derive.unit.test.ts @@ -0,0 +1,1639 @@ +import { describe, expect, it } from "@effect/vitest"; +import type { ApiNoun } from "../src/commands/api/api-command-policy.ts"; +import { deriveApiCommands } from "./api-command-derive.ts"; + +const jsonResponse = (schema: unknown) => ({ + "200": { description: "ok", content: { "application/json": { schema } } }, +}); + +const operation = (overrides: Record) => ({ + summary: "Do the thing", + "x-scalar-stability": "experimental", + parameters: [{ name: "ref", in: "path", required: true, schema: { type: "string" } }], + responses: jsonResponse({ type: "object", properties: { ok: { type: "boolean" } } }), + ...overrides, +}); + +const envelope = (attributes: Record) => ({ + content: { + "application/json": { + schema: { + type: "object", + properties: { + data: { + type: "object", + properties: { + type: { type: "string", enum: ["thing"] }, + attributes: { + type: "object", + required: ["name"], + properties: { name: { type: "string" }, ...attributes }, + }, + }, + }, + }, + }, + }, + }, +}); + +const unionEnvelope = (branches: ReadonlyArray>) => ({ + content: { + "application/json": { + schema: { + type: "object", + properties: { + data: { + type: "object", + properties: { + type: { type: "string", enum: ["thing"] }, + attributes: { anyOf: branches }, + }, + }, + }, + }, + }, + }, +}); + +const closedBranch = (properties: Record, required: ReadonlyArray) => ({ + type: "object", + additionalProperties: false, + properties, + required, +}); + +const thingNoun: ApiNoun = { + description: "Manage things", + experimental: "warehouse", + groups: { sub: "Manage sub things", "sub.deep": "Manage deep things", status: "Status" }, +}; + +/** The spec path of an operation: the project ref, then one segment per other path parameter. */ +const pathOf = (id: string, node: unknown): string => { + const parameters: unknown = Reflect.get(Object(node), "parameters"); + const extra = Array.isArray(parameters) + ? parameters + .filter((parameter) => parameter.in === "path" && parameter.name !== "ref") + .map((parameter) => `/{${parameter.name}}`) + : []; + return `/v1/projects/{ref}/${id}${extra.join("")}`; +}; + +const derive = ( + operations: Record, + generated: ReadonlyArray = Object.keys(operations), + options: { + readonly schemas?: Record; + readonly overrides?: Partial[0]>; + } = {}, +) => + deriveApiCommands({ + spec: { + paths: Object.fromEntries( + Object.entries(operations).map(([id, node]) => [ + pathOf(id, node), + { [id.startsWith("get-") ? "get" : "post"]: { operationId: id, ...(node as object) } }, + ]), + ), + components: { + schemas: { Tags: { type: "array", items: { type: "string" } }, ...options.schemas }, + }, + }, + generated, + nouns: { thing: thingNoun }, + operationIdMap: Object.fromEntries( + Object.keys(operations).map((id) => [id, "v2EnableWarehouse" as const]), + ), + handWrittenRoots: new Set(), + ...options.overrides, + }); + +const named = (method: string) => ({ "x-operation": { group: "thing", method } }); +const create = named("create"); + +describe("deriveApiCommands", () => { + it("applies CLI-only mutation policies and rejects an unused policy", () => { + const operations = { + "create-thing": operation({ ...create, description: "Rebuilds the thing." }), + }; + const result = derive(operations, undefined, { + overrides: { policies: { "create-thing": { confirmDescription: true } } }, + }); + expect(result.problems).toEqual([]); + expect(result.entries[0]).toMatchObject({ confirmDescription: true }); + expect( + derive(operations, undefined, { + overrides: { policies: { "missing-thing": { confirmDescription: true } } }, + }).problems, + ).toEqual([expect.stringContaining("missing-thing")]); + }); + + it.each([ + { id: "get-thing", node: operation({ ...named("get"), description: "Reads the thing." }) }, + { id: "create-thing", node: operation({ ...create }) }, + ])("rejects confirmation descriptions on $id without a described mutation", ({ id, node }) => { + const result = derive({ [id]: node }, undefined, { + overrides: { policies: { [id]: { confirmDescription: true } } }, + }); + expect(result.problems).toEqual([expect.stringContaining("confirmation")]); + }); + + it("binds envelope body fields by JSON pointer and the project ref to the target", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ tags: { type: "array", items: { type: "string" } } }), + }), + }); + + expect(result.problems).toEqual([]); + const [entry] = result.entries; + expect(entry?.body).toEqual({ contentType: "application/json", type: "thing" }); + expect([...result.successStatuses]).toEqual([["create-thing", 200]]); + expect(entry?.flags.map((flag) => [flag.name, flag.required, flag.repeatable])).toEqual([ + ["name", true, false], + ["tag", false, true], + ]); + expect(entry?.bindings).toEqual([ + { location: "path", name: "ref", source: "target" }, + { + location: "body", + name: "name", + pointer: "/data/attributes/name", + source: "flag", + flag: "name", + }, + { + location: "body", + name: "tags", + pointer: "/data/attributes/tags", + source: "flag", + flag: "tag", + }, + ]); + }); + + it("derives envelope fields from an anyOf of closed objects and requires only what every branch requires", () => { + const properties = { name: { type: "string" }, a: { type: "string" }, b: { type: "string" } }; + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: unionEnvelope([ + closedBranch(properties, ["name", "a"]), + closedBranch(properties, ["name", "b"]), + ]), + }), + }); + + expect(result.problems).toEqual([]); + const [entry] = result.entries; + expect(entry?.body).toEqual({ contentType: "application/json", type: "thing" }); + expect(entry?.flags.map((flag) => [flag.name, flag.required])).toEqual([ + ["name", true], + ["a", false], + ["b", false], + ]); + expect(entry?.bindings).toContainEqual({ + location: "body", + name: "a", + pointer: "/data/attributes/a", + source: "flag", + flag: "a", + }); + }); + + it("rejects envelope attributes whose anyOf branches differ in properties", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: unionEnvelope([ + closedBranch({ a: { type: "string" } }, ["a"]), + closedBranch({ c: { type: "string" } }, ["c"]), + ]), + }), + }); + + expect(result.problems.join("\n")).toContain( + "unsupported in this runtime: envelope attributes use a schema composition", + ); + }); + + it("rejects an envelope whose data declares fields beyond type and attributes", () => { + const body = envelope({}); + const data = body.content["application/json"].schema.properties.data; + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + properties: { + data: { + ...data, + properties: { ...data.properties, id: { type: "string" } }, + }, + }, + }, + }, + }, + }, + }), + }); + + expect(result.entries).toEqual([]); + expect(result.problems.join("\n")).toContain('envelope data declares "id"'); + }); + + it("rejects a JSON body that is not a data envelope", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: { + content: { + "application/json": { + schema: { type: "object", properties: { display_name: { type: "string" } } }, + }, + }, + }, + }), + }); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + "create-thing: unsupported in this runtime: request body is not a data envelope", + ]); + }); + + it("turns a string enum query parameter into flag choices", () => { + const result = derive({ + "list-things": operation({ + ...named("list"), + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "sort", in: "query", schema: { type: "string", enum: ["asc", "desc"] } }, + ], + }), + }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.flags[0]).toMatchObject({ name: "sort", choices: ["asc", "desc"] }); + }); + + it("derives a plain token-named query parameter as a flag", () => { + const result = derive({ + "list-things": operation({ + ...named("list"), + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "page_token", in: "query", schema: { type: "string" } }, + ], + }), + }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.flags[0]).toMatchObject({ name: "page-token" }); + }); + + it.each([ + ["a binary", { "200": { description: "file", content: { "application/octet-stream": {} } } }], + ["a text", { "200": { description: "text", content: { "text/plain": {} } } }], + ["an empty", { "204": { description: "none" } }], + ])("rejects %s success response", (_label, responses) => { + const result = derive({ "create-thing": operation({ ...create, responses }) }); + + expect(result.entries).toEqual([]); + expect(result.problems.join("\n")).toContain("response is not JSON"); + }); + + it.each([ + ["a numeric body field", { requestBody: envelope({ size: { type: "integer" } }) }, "size"], + [ + "an array of numbers in a body field", + { requestBody: envelope({ sizes: { type: "array", items: { type: "number" } } }) }, + "sizes", + ], + ])("rejects %s", (_label, node, field) => { + const result = derive({ "create-thing": operation({ ...create, ...node }) }); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + `create-thing: unsupported in this runtime: numeric body field "${field}"`, + ]); + }); + + it("rejects a numeric query parameter", () => { + const result = derive({ + "get-thing": operation({ + ...named("get"), + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "limit", in: "query", schema: { type: "integer" } }, + ], + }), + }); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + 'get-thing: unsupported in this runtime: query parameter "limit" is not a scalar', + ]); + }); + + describe("nested body fields", () => { + const writeOnlyString = { type: "string", writeOnly: true }; + const nestedBody = (nested: Record) => + derive({ + "create-thing": operation({ ...create, requestBody: envelope({ nested }) }), + }); + + it("binds an object and an array of objects to JSON flags named after the field", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ + name: { type: "string" }, + nested: { type: "object", properties: { size: { type: "string" } } }, + rules: { type: "array", items: { type: "object", properties: {} } }, + }), + }), + }); + + expect(result.problems).toEqual([]); + const [entry] = result.entries; + expect(entry?.flags).toMatchObject([ + { name: "name", type: "string" }, + { name: "nested", type: "json", repeatable: false }, + { name: "rules", type: "json", repeatable: false }, + ]); + expect(entry?.bindings.filter((binding) => binding.location === "body")).toMatchObject([ + { pointer: "/data/attributes/name", flag: "name" }, + { pointer: "/data/attributes/nested", flag: "nested" }, + { pointer: "/data/attributes/rules", flag: "rules" }, + ]); + }); + + it("rejects a sensitive nested field", () => { + const result = nestedBody({ + type: "object", + writeOnly: true, + properties: { size: { type: "string" } }, + }); + + expect(result.entries).toEqual([]); + expect(result.problems.join("\n")).toContain( + 'unsupported in this runtime: body field "nested" is a secret', + ); + }); + + it("rejects an unmarked credential-like nested field", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ api_key: { type: "object", properties: {} } }), + }), + }); + + expect(result.problems.join("\n")).toContain('"api_key" looks like a credential'); + }); + + it.each([ + [ + "a writeOnly property", + { type: "object", properties: { size: { type: "string" }, pin: writeOnlyString } }, + "nested.pin", + ], + [ + "a credential-like property name", + { type: "object", properties: { db_password: { type: "string" } } }, + "nested.db_password", + ], + [ + "a secret inside array items", + { type: "array", items: { type: "object", properties: { pin: writeOnlyString } } }, + "nested[].pin", + ], + [ + "a secret two levels down", + { + type: "object", + properties: { inner: { type: "object", properties: { pin: writeOnlyString } } }, + }, + "nested.inner.pin", + ], + [ + "a secret in an anyOf member", + { anyOf: [{ type: "object", properties: { pin: writeOnlyString } }, { type: "null" }] }, + "nested.pin", + ], + ])("rejects a nested field that holds %s", (_label, nested, secretPath) => { + const result = nestedBody(nested); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + `create-thing: unsupported in this runtime: body field "nested" holds the secret "${secretPath}", and the dry-run preview masks only scalar flag values`, + ]); + }); + + it("rejects a nested field whose patternProperties value is a secret", () => { + const result = nestedBody({ + type: "object", + patternProperties: { ".*": { type: "string", format: "password" } }, + }); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + 'create-thing: unsupported in this runtime: body field "nested" is a secret, and the dry-run preview masks only scalar flag values', + ]); + }); + + it("accepts a nested field whose schema refers back to itself when it holds no secret", () => { + const node = { + type: "object", + properties: { label: { type: "string" }, child: { $ref: "#/components/schemas/Node" } }, + }; + const result = derive( + { + "create-thing": operation({ + ...create, + requestBody: envelope({ tree: { $ref: "#/components/schemas/Node" } }), + }), + }, + ["create-thing"], + { schemas: { Node: node } }, + ); + + expect(result.problems).toEqual([]); + }); + }); + + it("rejects a body field that collides with a reserved runtime flag", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ wait: { type: "boolean" } }), + }), + }); + + expect(result.problems.join("\n")).toContain('"--wait"'); + }); + + it("rejects a body field named like a registered global flag", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ profile: { type: "string" } }), + }), + }); + + expect(result.problems.join("\n")).toContain('"--profile"'); + }); + + it("names a command from the operation's x-operation", () => { + const result = derive({ "create-thing": operation(create) }); + + expect(result.problems).toEqual([]); + expect(result.entries.map((entry) => entry.command)).toEqual([["thing", "create"]]); + }); + + it("strips the stage paragraph from the description whatever the stage word", () => { + const describe = (description: string) => + derive({ "create-thing": operation({ ...create, description }) }).entries[0]?.description; + + expect(describe("Does the thing.\n\nThis endpoint is currently in its **Alpha** stage.")).toBe( + "Does the thing.", + ); + expect(describe("Does the thing.\n\nThis endpoint is currently in its **Beta** stage.\n")).toBe( + "Does the thing.", + ); + expect(describe("This endpoint is currently in its **Alpha** stage.")).toBeUndefined(); + }); + + it("generates only operations marked experimental", () => { + const result = derive({ + "create-thing": operation({ ...create, "x-scalar-stability": "beta" }), + }); + + expect(result.entries).toEqual([]); + expect(result.problems.join("\n")).toContain("only operations marked experimental"); + }); + + it("names array body flags in the singular and keeps other fields as they are", () => { + const list = { type: "array", items: { type: "string" } }; + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ + categories: list, + tables: list, + access: list, + status: list, + analysis: list, + sizes: { type: "string" }, + }), + }), + }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.flags.map((flag) => flag.name)).toEqual([ + "name", + "category", + "table", + "access", + "status", + "analysis", + "sizes", + ]); + }); + + it("rejects a singularised flag that collides with another flag", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ + table: { type: "string" }, + tables: { type: "array", items: { type: "string" } }, + }), + }), + }); + + expect(result.problems.join("\n")).toContain('"--table"'); + }); + + it("marks writeOnly and password-format body fields sensitive", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({ + api_secret: { type: "string", writeOnly: true }, + pin: { type: "string", format: "password" }, + recovery_codes: { type: "array", items: { type: "string", writeOnly: true } }, + }), + }), + }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.flags.map((flag) => [flag.name, flag.sensitive === true])).toEqual([ + ["name", false], + ["api-secret", true], + ["pin", true], + ["recovery-code", true], + ]); + }); + + it("accepts a credential-like field that is marked x-sensitive and rejects it otherwise", () => { + const body = (api_key: Record) => envelope({ api_key }); + const flagOf = (result: ReturnType) => + result.entries[0]?.flags.find((flag) => flag.name === "api-key"); + + const marked = derive({ + "create-thing": operation({ + ...create, + requestBody: body({ type: "string", "x-sensitive": true }), + }), + }); + const unmarked = derive({ + "create-thing": operation({ ...create, requestBody: body({ type: "string" }) }), + }); + + expect(marked.problems).toEqual([]); + expect(flagOf(marked)?.sensitive).toBe(true); + expect(unmarked.problems.join("\n")).toContain('"api_key" looks like a credential'); + }); + + describe("wait from response links", () => { + const requiredChain = { + type: "object", + required: ["data"], + properties: { + data: { type: "object", required: ["id"], properties: { id: { type: "string" } } }, + }, + }; + const changeResponse = ( + links: unknown, + schema: unknown = requiredChain, + mediaType = "json", + ) => ({ + "202": { + description: "accepted", + content: { [mediaType === "json" ? "application/json" : mediaType]: { schema } }, + links, + }, + }); + const poll = { + status: "/data/attributes/status", + succeeded: ["done"], + failed: ["broken"], + error: "/data/attributes/reason", + }; + const readSchema = { + type: "object", + properties: { + data: { + type: "object", + properties: { + attributes: { + type: "object", + properties: { + status: { type: "string", enum: ["done", "broken", "pending"] }, + reason: { type: "string" }, + }, + }, + }, + }, + }, + }; + const readOf = (xOperation: unknown, responses: unknown = jsonResponse(readSchema)) => + operation({ + "x-operation": xOperation, + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "thing_id", in: "query", schema: { type: "string" } }, + ], + responses, + }); + const readWith = (readPoll: unknown, responses?: unknown) => + readOf({ group: "thing", method: "get", poll: readPoll }, responses); + const hiddenWith = (readPoll: object, responses?: unknown, inspect = "get-inspect") => + readOf({ poll: { ...readPoll, inspect } }, responses); + const readThing = readWith(poll); + const hiddenThing = hiddenWith(poll); + const link = (parameters: Record, operationId = "get-thing") => ({ + setup: { operationId, parameters }, + }); + const changeThing = (links: unknown, schema?: unknown) => + operation({ ...create, responses: changeResponse(links, schema) }); + const waitOf = (result: ReturnType) => + result.entries.find((entry) => entry.operationId === "create-thing")?.wait; + const inspectThing = operation(named("status")); + /** `create-thing` and an inspect command are generated; poll-only reads stay hidden. */ + const deriveHidden = (operations: Record, inspect: unknown = inspectThing) => + derive({ ...operations, "get-inspect": inspect }, ["create-thing", "get-inspect"]); + + it("builds the wait from the polled target and leaves the shared path parameter to the runtime", () => { + const result = derive({ + "create-thing": changeThing( + link({ ref: "$request.path.ref", thing_id: "$response.body#/data/id" }), + ), + "get-thing": readThing, + }); + + expect(result.problems).toEqual([]); + expect(waitOf(result)).toEqual({ + read: "get-thing", + params: { thing_id: "/data/id" }, + ...poll, + }); + }); + + it("resolves wait pointers from +json responses", () => { + const jsonApi = (schema: unknown) => ({ + "200": { description: "ok", content: { "application/vnd.api+json": { schema } } }, + }); + const result = derive({ + "create-thing": operation({ + ...create, + responses: changeResponse( + link({ thing_id: "$response.body#/data/id" }), + requiredChain, + "application/vnd.api+json", + ), + }), + "get-thing": readWith(poll, jsonApi(readSchema)), + }); + + expect(result.problems).toEqual([]); + expect(waitOf(result)?.read).toBe("get-thing"); + }); + + it("resolves escaped status and error pointers against property names", () => { + const escapedRead = { + type: "object", + properties: { + "a/b": { type: "string", enum: ["done", "broken"] }, + "c~d": { type: "string" }, + }, + }; + const result = derive({ + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" })), + "get-thing": readWith( + { ...poll, status: "/a~1b", error: "/c~0d" }, + jsonResponse(escapedRead), + ), + }); + + expect(result.problems).toEqual([]); + expect(waitOf(result)).toMatchObject({ status: "/a~1b", error: "/c~0d" }); + }); + + it("accepts a link parameter pointing at a required property with escaped characters", () => { + const escapedChange = { + type: "object", + required: ["a~/b"], + properties: { "a~/b": { type: "string" } }, + }; + const result = derive( + { + "create-thing": changeThing(link({ thing_id: "$response.body#/a~0~1b" }), escapedChange), + "get-thing": readThing, + }, + ["create-thing", "get-thing"], + ); + + expect(result.problems).toEqual([]); + }); + + it("ignores a link whose target has no poll", () => { + const result = derive({ + "create-thing": changeThing(link({})), + "get-thing": operation(named("get")), + }); + + expect(result.problems).toEqual([]); + expect(waitOf(result)).toBeUndefined(); + }); + + it.each([ + ["without a command name", hiddenThing], + ["with a command name", readWith({ ...poll, inspect: "get-inspect" })], + ])("keeps a polled read %s internal when it is not generated", (_label, read) => { + const result = deriveHidden({ + "create-thing": changeThing( + link({ ref: "$request.path.ref", thing_id: "$response.body#/data/id" }), + ), + "get-thing": read, + }); + + expect(result.problems).toEqual([]); + expect(result.entries.map((entry) => entry.command)).toEqual([ + ["thing", "create"], + ["thing", "status"], + ]); + expect(waitOf(result)).toEqual({ + read: "get-thing", + params: { thing_id: "/data/id" }, + ...poll, + }); + expect(result.pollTargets).toEqual([ + { + operationId: "get-thing", + definition: "v2EnableWarehouse", + summary: "Do the thing", + inspect: "get-inspect", + }, + ]); + }); + + it("rejects a poll-only read whose success response is not JSON", () => { + const result = deriveHidden({ + "create-thing": changeThing( + link({ ref: "$request.path.ref", thing_id: "$response.body#/data/id" }), + ), + "get-thing": hiddenWith(poll, { "200": { description: "none" } }), + }); + + expect(result.pollTargets).toEqual([]); + expect(result.problems.join("\n")).toContain("get-thing: unsupported in this runtime"); + }); + + it("records a poll-only read once when several mutations link to it", () => { + const result = derive( + { + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" })), + "update-thing": operation({ + ...named("update"), + responses: changeResponse(link({ thing_id: "$response.body#/data/id" })), + }), + "get-thing": hiddenThing, + "get-inspect": inspectThing, + }, + ["create-thing", "update-thing", "get-inspect"], + ); + + expect(result.problems).toEqual([]); + expect(result.entries.map((entry) => [entry.operationId, entry.wait?.read])).toEqual([ + ["create-thing", "get-thing"], + ["get-inspect", undefined], + ["update-thing", "get-thing"], + ]); + expect(result.pollTargets.map((target) => target.operationId)).toEqual(["get-thing"]); + }); + + it("ignores a poll-only read that no generated operation links to", () => { + const result = deriveHidden({ + "create-thing": operation(create), + "get-thing": hiddenThing, + }); + + expect(result.problems).toEqual([]); + expect(result.pollTargets).toEqual([]); + }); + + it.each([ + ["without a command name", readOf({ poll })], + ["with a command name", readThing], + ])( + "rejects a linked polled read %s that is not generated and sets no inspect", + (_label, read) => { + const result = deriveHidden({ "create-thing": changeThing(link({})), "get-thing": read }); + + expect(result.problems).toEqual([ + 'create-thing: link "setup" targets polled operation "get-thing", which is not a generated command and sets no poll.inspect', + ]); + expect(waitOf(result)).toBeUndefined(); + expect(result.pollTargets).toEqual([]); + }, + ); + + it.each([ + ["a misspelled poll key", { pool: { ...poll, inspect: "get-inspect" } }, "pool"], + ["a partial command name", { group: "thing" }, "a command name needs both group and method"], + ])("rejects a linked read whose x-operation has %s", (_label, xOperation, reason) => { + const result = deriveHidden({ + "create-thing": changeThing(link({})), + "get-thing": readOf(xOperation), + }); + + expect(result.problems).toHaveLength(1); + expect(result.problems[0]).toContain( + 'create-thing: link "setup" targets "get-thing", whose x-operation is invalid', + ); + expect(result.problems[0]).toContain(reason); + expect(waitOf(result)).toBeUndefined(); + }); + + it("polls a generated read as its own command even when it sets inspect", () => { + const result = derive( + { + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" })), + "get-thing": readWith({ ...poll, inspect: "get-inspect" }), + "get-inspect": inspectThing, + }, + ["create-thing", "get-thing", "get-inspect"], + ); + + expect(result.problems).toEqual([]); + expect(waitOf(result)?.read).toBe("get-thing"); + expect(result.pollTargets).toEqual([]); + }); + + it.each([ + ["group without method", { group: "thing" }], + ["method without group", { method: "create" }], + ])("rejects a command name with %s", (_label, xOperation) => { + const result = derive({ "create-thing": operation({ "x-operation": xOperation }) }); + + expect(result.problems).toEqual([ + "create-thing: invalid x-operation: a command name needs both group and method", + ]); + }); + + it("rejects a generated operation whose x-operation has no command name", () => { + const result = derive( + { + "create-thing": changeThing(link({})), + "get-thing": hiddenThing, + "get-inspect": inspectThing, + }, + ["create-thing", "get-thing", "get-inspect"], + ); + + expect(result.problems).toEqual([ + "get-thing: no command name; set x-operation group and method", + ]); + }); + + it("rejects an inspect command that needs input beyond the project ref", () => { + const result = deriveHidden( + { "create-thing": changeThing(link({})), "get-thing": hiddenThing }, + operation({ + ...named("status"), + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "id", in: "path", required: true, schema: { type: "string" } }, + ], + }), + ); + + expect(result.problems).toEqual([ + 'get-thing: inspect operation "get-inspect" needs input beyond the project ref', + ]); + }); + + it("rejects an inspect command that changes state", () => { + const result = derive( + { + "create-thing": changeThing(link({})), + "get-thing": hiddenWith(poll, undefined, "reset-thing"), + "reset-thing": operation(named("delete")), + }, + ["create-thing", "reset-thing"], + ); + + expect(result.problems).toEqual([ + 'get-thing: inspect operation "reset-thing" must be a read-only command', + ]); + }); + + it("rejects an inspect operation that is not generated", () => { + const result = deriveHidden({ + "create-thing": changeThing(link({})), + "get-thing": hiddenWith(poll, undefined, "get-missing"), + }); + + expect(result.problems).toEqual([ + 'get-thing: inspect operation "get-missing" is not a generated operation', + ]); + }); + + it("rejects a poll-only read that declares poll and also links to a polled operation", () => { + const result = deriveHidden({ + "create-thing": changeThing(link({})), + "get-thing": operation({ + ...hiddenThing, + responses: { + "200": { ...jsonResponse(readSchema)["200"], links: link({}, "get-other") }, + }, + }), + "get-other": hiddenThing, + }); + + expect(result.problems.join("\n")).toContain( + 'get-thing: declares poll and also links to the polled operation "get-other"; use one', + ); + }); + + it("ignores an invalid x-operation on an operation only a poll-only read links to", () => { + const result = deriveHidden({ + "create-thing": changeThing(link({})), + "get-thing": operation({ + ...hiddenThing, + responses: { + "200": { ...jsonResponse(readSchema)["200"], links: link({}, "get-other") }, + }, + }), + "get-other": readOf({ group: "thing" }), + }); + + expect(result.problems).toEqual([]); + expect(result.pollTargets.map((target) => target.operationId)).toEqual(["get-thing"]); + }); + + it("rejects a poll-only read that is not experimental", () => { + const result = deriveHidden({ + "create-thing": changeThing(link({})), + "get-thing": { ...hiddenThing, "x-scalar-stability": "stable" }, + }); + + expect(result.problems).toEqual([ + "get-thing: only operations marked experimental can be generated (x-scalar-stability)", + ]); + }); + + it.each([ + ["a mutation", "update-thing", hiddenThing, "must use GET"], + [ + "a request body", + "get-thing", + { ...hiddenThing, requestBody: envelope({}) }, + "must not require a request body", + ], + [ + "no project scope", + "get-thing", + { ...hiddenThing, parameters: [] }, + "must be scoped by a project ref path parameter", + ], + [ + "invalid poll metadata", + "get-thing", + hiddenWith({ ...poll, succeeded: "done" }), + "whose x-operation is invalid", + ], + ] as const)("rejects a poll-only read with %s", (_label, id, read, message) => { + const result = deriveHidden({ "create-thing": changeThing(link({}, id)), [id]: read }); + + expect(result.problems.join("\n")).toContain(message); + }); + + it("rejects a poll-only read missing from the typed client", () => { + const result = derive( + { + "create-thing": changeThing(link({})), + "get-thing": hiddenThing, + "get-inspect": inspectThing, + }, + ["create-thing", "get-inspect"], + { + overrides: { + operationIdMap: { + "create-thing": "v2EnableWarehouse", + "get-inspect": "v2EnableWarehouse", + }, + }, + }, + ); + + expect(result.problems).toEqual([ + "get-thing: polling target is missing from the typed client; regenerate @supabase/api", + ]); + }); + + it("derives a self wait on a read that declares its own poll", () => { + const result = derive({ "get-thing": readThing }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.wait).toEqual({ read: "get-thing", params: {}, ...poll }); + }); + + it("rejects a read that declares poll and also links to a polled operation", () => { + const result = derive({ + "get-thing": readThing, + "get-other": operation({ + ...readThing, + responses: { + "200": { + description: "ok", + content: { "application/json": { schema: requiredChain } }, + links: link({ thing_id: "$response.body#/data/id" }), + }, + }, + }), + }); + + expect(result.problems.join("\n")).toContain( + 'declares poll and also links to the polled operation "get-thing"; use one', + ); + }); + + it("rejects a poll status pointer that does not resolve in the read response", () => { + const result = derive({ + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" })), + "get-thing": readWith({ ...poll, status: "/data/attributes/missing" }), + }); + + expect(result.problems.join("\n")).toContain( + 'wait.status pointer "/data/attributes/missing"', + ); + }); + + it.each([ + [ + "an error pointer the read response does not have", + hiddenWith({ ...poll, error: "/data/attributes/nope" }), + 'wait.error pointer "/data/attributes/nope" does not resolve in the get-thing response', + ], + [ + "an empty succeeded list", + hiddenWith({ ...poll, succeeded: [] }), + "wait.succeeded must list at least one status", + ], + [ + "a status outside the status enum", + hiddenWith({ ...poll, failed: ["bogus"] }), + 'wait status "bogus" is not in the status enum of get-thing', + ], + [ + "a required read parameter the link does not supply", + operation({ + ...hiddenThing, + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "thing_id", in: "query", required: true, schema: { type: "string" } }, + ], + }), + 'wait.params does not supply required parameter "thing_id" of get-thing', + ], + ])("rejects a poll with %s", (_label, read, message) => { + const result = deriveHidden({ "create-thing": changeThing(link({})), "get-thing": read }); + + expect(result.problems.map((problem) => problem.replace(/^[^:]+: /u, ""))).toContain(message); + }); + + it.each([ + [ + "an unsupported expression", + link({ thing_id: "$request.query.id" }), + "unsupported expression", + ], + ["an unknown target", link({}, "get-missing"), 'unknown operation "get-missing"'], + [ + "a request path expression other than ref", + link({ ref: "$request.path.other" }), + 'link "setup" parameter "ref": only "$request.path.ref" is supported in this runtime', + ], + [ + "a link without a target operationId", + { setup: { parameters: {} } }, + 'link "setup" must name its target with operationId', + ], + [ + "a ref expression bound to a parameter of another name", + link({ other: "$request.path.ref" }), + 'link "setup" parameter "other": "$request.path.ref" needs a path parameter of that name on both operations', + ], + [ + "a parameter the polled read does not take", + link({ bogus: "$response.body#/data/id" }), + 'wait.params "bogus" is not a query or path parameter of get-thing', + ], + [ + "a pointer the change response does not have", + link({ thing_id: "$response.body#/data/missing" }), + 'wait.params "thing_id" pointer "/data/missing" does not resolve in the response', + ], + [ + "two links to a polled operation", + { first: link({}).setup, second: link({}).setup }, + "more than one response link targets a polled operation (get-thing, get-thing)", + ], + ])("rejects %s", (_label, links, message) => { + const result = derive({ "create-thing": changeThing(links), "get-thing": readThing }); + + expect(result.problems.join("\n")).toContain(message); + }); + + it("rejects a linked wait on an operation with several 2xx responses", () => { + const responses = { + ...changeResponse(link({ thing_id: "$response.body#/data/id" })), + "200": { description: "done", content: { "application/json": { schema: requiredChain } } }, + }; + const result = derive({ + "create-thing": operation({ ...create, responses }), + "get-thing": readThing, + }); + + expect(result.problems.join("\n")).toContain("a wait needs a single 2xx response"); + }); + + it("rejects a poll-only read with several 2xx responses", () => { + const responses = { + ...jsonResponse(readSchema), + "201": { description: "created", content: { "application/json": { schema: readSchema } } }, + }; + const result = deriveHidden({ + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" })), + "get-thing": hiddenWith(poll, responses), + }); + + expect(result.problems.join("\n")).toContain('wait.read "get-thing" has several 2xx'); + }); + + it.each([ + [ + "a property that is not required in the enclosing object", + { + type: "object", + required: ["data"], + properties: { data: { type: "object", properties: { id: { type: "string" } } } }, + }, + ], + [ + "an enclosing object that is not required", + { + type: "object", + properties: { + data: { type: "object", required: ["id"], properties: { id: { type: "string" } } }, + }, + }, + ], + [ + "a required property that is nullable", + { + type: "object", + required: ["data"], + properties: { + data: { + type: "object", + required: ["id"], + properties: { id: { type: "string", nullable: true } }, + }, + }, + }, + ], + ])("rejects a wait value taken from %s", (_label, schema) => { + const result = derive({ + "create-thing": changeThing(link({ thing_id: "$response.body#/data/id" }), schema), + "get-thing": readThing, + }); + + expect(waitOf(result)).toBeUndefined(); + expect(result.problems.join("\n")).toContain("is not required at every level"); + }); + }); + + describe("nested groups", () => { + it("derives a command path from a dotted group, three levels deep", () => { + const result = derive({ + "create-thing": operation({ "x-operation": { group: "thing.sub", method: "create" } }), + "create-deep": operation({ "x-operation": { group: "thing.sub.deep", method: "create" } }), + }); + + expect(result.problems).toEqual([]); + expect(result.entries.map((entry) => entry.command)).toEqual([ + ["thing", "sub", "create"], + ["thing", "sub", "deep", "create"], + ]); + }); + }); + + describe("path parameters", () => { + const withParameters = (...parameters: ReadonlyArray) => + operation({ + "x-operation": { group: "thing", method: "get" }, + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + ...parameters, + ], + }); + const pathParameter = (name: string, extra: Record = {}) => ({ + name, + in: "path", + required: true, + schema: { type: "string" }, + ...extra, + }); + + it("binds the one other path parameter to a positional argument named after it", () => { + const result = derive({ + "get-thing": withParameters( + pathParameter("function_slug", { description: "Slug of the function." }), + ), + }); + + expect(result.problems).toEqual([]); + const [entry] = result.entries; + expect(entry?.argument).toEqual({ + name: "function-slug", + description: "Slug of the function.", + }); + expect(entry?.bindings).toEqual([ + { location: "path", name: "ref", source: "target" }, + { location: "path", name: "function_slug", source: "argument", argument: "function-slug" }, + ]); + expect(entry?.flags).toEqual([]); + }); + + it.each([ + [ + "a second path parameter", + withParameters(pathParameter("version"), pathParameter("id")), + 'unsupported in this runtime: more than one path parameter besides "ref"', + ], + [ + "a path parameter that is not a scalar", + withParameters( + pathParameter("version", { schema: { type: "array", items: { type: "string" } } }), + ), + 'path parameter "version" is not a scalar', + ], + [ + "a path parameter that is not a string", + withParameters(pathParameter("version", { schema: { type: "boolean" } })), + 'unsupported in this runtime: path parameter "version" is not a string', + ], + [ + "a path parameter named like a query parameter", + withParameters(pathParameter("version"), { + name: "version", + in: "query", + schema: { type: "string" }, + }), + '"version" is used by more than one of', + ], + [ + "a path parameter that stands in for no ref", + operation({ + "x-operation": { group: "thing", method: "get" }, + parameters: [pathParameter("version")], + }), + 'operation has no "ref" path parameter', + ], + ])("rejects %s", (_label, node, message) => { + const result = derive({ "get-thing": node }); + + expect(result.problems.join("\n")).toContain(message); + }); + }); + + describe("header parameters", () => { + const withHeaders = (...headers: ReadonlyArray) => + operation({ + ...create, + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + ...headers, + ], + }); + const header = (name: string, extra: Record = {}) => ({ + name, + in: "header", + schema: { type: "string" }, + ...extra, + }); + + it.each([ + ["a header parameter", header("Idempotency-Key")], + ["a required header parameter", header("X-Trace-Id", { required: true })], + ["a credential-named header", header("X-Api-Key")], + ])("rejects %s", (_label, parameter) => { + const result = derive({ "create-thing": withHeaders(parameter) }); + + expect(result.entries).toEqual([]); + expect(result.problems).toEqual([ + `create-thing: unsupported in this runtime: header parameter "${parameter.name}"`, + ]); + }); + + it("gives no flag to Authorization, Content-Type or Accept in any case", () => { + const result = derive({ + "create-thing": withHeaders( + header("Authorization"), + header("content-type"), + header("ACCEPT"), + ), + }); + + expect(result.problems).toEqual([]); + expect(result.entries[0]?.flags).toEqual([]); + }); + + it("rejects a cookie parameter", () => { + const result = derive({ + "create-thing": operation({ + ...create, + requestBody: envelope({}), + parameters: [ + { name: "ref", in: "path", required: true, schema: { type: "string" } }, + { name: "session", in: "cookie", schema: { type: "string" } }, + ], + }), + }); + + expect(result.problems.join("\n")).toContain( + 'unsupported in this runtime: cookie parameter "session"', + ); + }); + }); + + it.each([ + [ + "a sub-group without a description", + { "create-thing": operation({ "x-operation": { group: "thing.other", method: "create" } }) }, + 'group "other" has no description in the nouns table', + ], + [ + "a leaf command that is also a group", + { + "get-status": operation({ "x-operation": { group: "thing", method: "status" } }), + "get-detail": operation({ "x-operation": { group: "thing.status", method: "get" } }), + }, + 'command "thing status" is both a command and a group', + ], + [ + "an operation without a ref path parameter", + { "create-thing": operation({ ...create, parameters: [] }) }, + 'operation has no "ref" path parameter', + ], + [ + "an unknown key in x-operation", + { + "create-thing": operation({ + "x-operation": { group: "thing", method: "create", bogus: 1 }, + }), + }, + "create-thing: invalid x-operation", + ], + [ + "a generated operation that has no x-operation", + { "create-thing": operation({}) }, + "create-thing: no command name", + ], + ])("rejects %s", (_label, operations, message) => { + const result = derive(operations); + + expect(result.problems.join("\n")).toContain(message); + }); + + describe("operation rejections", () => { + const ref = { name: "ref", in: "path", required: true, schema: { type: "string" } }; + const withParameters = (...parameters: ReadonlyArray) => + operation({ ...create, parameters: [ref, ...parameters] }); + + it.each([ + [ + "a response status that is not a number", + { "create-thing": operation({ ...create, responses: { "2XX": { description: "ok" } } }) }, + 'create-thing: unsupported in this runtime: response status "2XX"', + ], + [ + "an operation with no 2xx response", + { + "create-thing": operation({ ...create, responses: { "400": { description: "bad" } } }), + }, + "create-thing: operation has no 2xx response", + ], + [ + "a noun missing from the nouns table", + { "create-thing": operation({ "x-operation": { group: "other", method: "create" } }) }, + 'create-thing: noun "other" is missing from the nouns table', + ], + [ + "a command that is not lowercase kebab-case", + { "create-thing": operation({ "x-operation": { group: "thing", method: "Create" } }) }, + 'create-thing: command "thing Create" must be lowercase kebab-case words', + ], + [ + "a command generated twice", + { "create-thing": operation(create), "create-other": operation(create) }, + 'create-other: command "thing create" is already generated by create-thing', + ], + [ + "a command declared after the group that contains it", + { + "get-detail": operation({ "x-operation": { group: "thing.status", method: "get" } }), + "get-status": operation({ "x-operation": { group: "thing", method: "status" } }), + }, + 'get-status: command "thing status" is both a command and a group', + ], + [ + "a poll on an operation that is not a read", + { + "create-thing": operation({ + "x-operation": { + group: "thing", + method: "create", + poll: { status: "/ok", succeeded: ["done"], failed: [] }, + }, + }), + }, + "create-thing: poll belongs on a read operation, not POST", + ], + [ + "an operation with no summary", + { "create-thing": operation({ ...create, summary: undefined }) }, + "create-thing: operation has no summary", + ], + [ + "a server-side dry_run query parameter", + { + "create-thing": withParameters({ + name: "dry_run", + in: "query", + schema: { type: "boolean" }, + }), + }, + 'create-thing: unsupported in this runtime: server-side "dry_run" parameter', + ], + [ + "a query parameter that is not a scalar", + { + "create-thing": withParameters({ + name: "filter", + in: "query", + schema: { type: "object" }, + }), + }, + 'create-thing: unsupported in this runtime: query parameter "filter" is not a scalar', + ], + [ + "a secret query parameter", + { + "create-thing": withParameters({ + name: "pin", + in: "query", + schema: { type: "string", writeOnly: true }, + }), + }, + 'create-thing: unsupported in this runtime: query parameter "pin" is a secret, and the dry-run preview masks only body fields', + ], + [ + "a query parameter whose flag is not kebab-case", + { + "create-thing": withParameters({ + name: "page.size", + in: "query", + schema: { type: "string" }, + }), + }, + 'create-thing: flag "page.size" must be lowercase kebab-case', + ], + [ + "a path parameter whose argument is not kebab-case", + { + "create-thing": withParameters({ + name: "slug.name", + in: "path", + required: true, + schema: { type: "string" }, + }), + }, + 'create-thing: argument "slug.name" must be lowercase kebab-case', + ], + [ + "a request body that is not JSON", + { + "create-thing": operation({ + ...create, + requestBody: { content: { "text/plain": { schema: { type: "string" } } } }, + }), + }, + "create-thing: unsupported in this runtime: request body (text/plain) is not a JSON object", + ], + [ + "a server-side dry_run body field", + { + "create-thing": operation({ + ...create, + requestBody: envelope({ dry_run: { type: "boolean" } }), + }), + }, + 'create-thing: unsupported in this runtime: server-side "dry_run" body field', + ], + [ + "a nested body field named like a path parameter", + { + "create-thing": operation({ + ...create, + parameters: [ + ref, + { name: "version", in: "path", required: true, schema: { type: "string" } }, + ], + requestBody: envelope({ version: { type: "object", properties: {} } }), + }), + }, + 'create-thing: "version" is used by more than one of: path parameter, header parameter, query parameter, body field', + ], + ])("rejects %s", (_label, operations, problem) => { + const result = derive(operations); + + expect(result.problems).toContain(problem); + }); + + it("rejects an operation that the typed client does not have", () => { + const result = derive({ "create-thing": operation(create) }, undefined, { + overrides: { operationIdMap: {} }, + }); + + expect(result.problems).toEqual([ + "create-thing: operation is missing from the typed client; regenerate @supabase/api", + ]); + }); + }); + + describe("hand-written commands", () => { + it("rejects a noun named like a hand-written root command", () => { + const result = derive({ "create-thing": operation(create) }, undefined, { + overrides: { handWrittenRoots: new Set(["thing"]) }, + }); + + expect(result.problems).toContain('noun "thing" is already a hand-written command'); + }); + + it("requires a description for each generated sub-group", () => { + const result = derive( + { + "create-thing": operation({ "x-operation": { group: "thing.sub", method: "create" } }), + }, + undefined, + { + overrides: { + nouns: { thing: { description: "Manage things", experimental: "warehouse" } }, + }, + }, + ); + + expect(result.problems).toContain( + 'create-thing: group "sub" has no description in the nouns table', + ); + }); + }); + + describe("generated operations", () => { + const named = operation({ "x-operation": { group: "thing", method: "create" } }); + + it("ignores x-operation on an operation that is not generated, even when it is invalid", () => { + const result = derive( + { + "create-thing": named, + "create-other": operation({ + "x-operation": { group: "other", method: "frobnicate", bogus: 1 }, + }), + }, + ["create-thing"], + ); + + expect(result.problems).toEqual([]); + expect(result.entries.map((entry) => entry.operationId)).toEqual(["create-thing"]); + }); + + it("rejects a generated operation that is missing from the spec", () => { + const result = derive({ "create-thing": named }, ["create-thing", "missing-thing"]); + + expect(result.problems).toEqual([ + "missing-thing: generated operation has no operation in the spec", + ]); + }); + }); +}); diff --git a/apps/cli/scripts/api-command-reference.ts b/apps/cli/scripts/api-command-reference.ts new file mode 100644 index 0000000000..b82dc0e7cd --- /dev/null +++ b/apps/cli/scripts/api-command-reference.ts @@ -0,0 +1,197 @@ +import { operationDefinitions } from "@supabase/api/effect"; +import type { + ApiCommandBinding, + ApiCommandEntry, + ApiCommandFlag, + ApiCommandWait, + ApiPollTarget, +} from "../src/commands/api/api-command.model.ts"; +import type { ApiNoun } from "../src/commands/api/api-command-policy.ts"; + +export interface ApiCommandReferenceInput { + readonly entries: ReadonlyArray; + readonly pollTargets: ReadonlyArray; + /** Success status code per operation id. */ + readonly successStatuses: ReadonlyMap; + readonly nouns: Readonly>; +} + +const code = (text: string): string => `\`${text}\``; + +/** The route the runtime sends, read from the typed client's definition of the operation. */ +const route = (operation: Pick): string => { + const { method, path } = operationDefinitions[operation.definition]; + return code(`${method} ${path}`); +}; + +const cell = (text: string): string => text.replaceAll("|", "\\|"); + +const commandLine = (entry: Pick): string => + ["supabase", ...entry.command].join(" "); + +const flagType = (flag: ApiCommandFlag): string => + flag.choices === undefined ? flag.type : `${flag.type} (${flag.choices.map(code).join(", ")})`; + +const bindsTo = (entry: ApiCommandEntry, flag: ApiCommandFlag): string => { + const binding = entry.bindings.find( + (candidate) => candidate.source === "flag" && candidate.flag === flag.name, + ); + if (binding === undefined) return ""; + return binding.location === "body" + ? `body ${code(binding.pointer)}` + : `${binding.location} ${code(binding.name)}`; +}; + +const requiredCell = (entry: ApiCommandEntry, flag: ApiCommandFlag): string => { + if (!flag.required) return "no"; + const bodyBound = entry.bindings.some( + (binding) => binding.location === "body" && binding.flag === flag.name, + ); + return bodyBound ? `yes, unless ${code("--body")} or ${code("--file")} has the field` : "yes"; +}; + +const flagRows = (entry: ApiCommandEntry): ReadonlyArray => + entry.flags.map((flag) => { + const label = + flag.type === "boolean" + ? `--${flag.name}` + : `--${flag.name} <${flag.type === "json" ? "json" : flag.name}>`; + const notes = flag.sensitive === true ? " Sensitive: never echoed or recorded." : ""; + return `| ${code(label)} | ${cell(flagType(flag))} | ${requiredCell(entry, flag)} | ${flag.repeatable ? "yes" : "no"} | ${bindsTo(entry, flag)}${notes} |`; + }); + +const argumentLine = (entry: ApiCommandEntry): string | undefined => { + if (entry.argument === undefined) return undefined; + const binding = entry.bindings.find( + (candidate): candidate is Extract => + candidate.source === "argument" && candidate.argument === entry.argument?.name, + ); + const target = binding === undefined ? "" : `, bound to path parameter ${code(binding.name)}`; + return `Positional argument ${code(`<${entry.argument.name}>`)}${target}.`; +}; + +/** The command a failed or timed-out wait names, as the runtime builds it. */ +const failureHintCommand = ( + entry: ApiCommandEntry, + wait: ApiCommandWait, + input: ApiCommandReferenceInput, +): string => { + const read = input.entries.find((candidate) => candidate.operationId === wait.read); + if (read === undefined) { + const inspect = input.entries.find( + (candidate) => + candidate.operationId === + input.pollTargets.find((target) => target.operationId === wait.read)?.inspect, + ); + return `${inspect === undefined ? "" : commandLine(inspect)} --remote=`.trim(); + } + const own = read.operationId === entry.operationId; + const parts = read.bindings.flatMap((binding) => { + if (binding.source === "target" || binding.location === "body") return []; + if (!own && !(binding.name in wait.params)) return []; + const text = + binding.source === "argument" ? `<${binding.name}>` : `--${binding.flag} <${binding.name}>`; + return [own ? `[${text}]` : text]; + }); + return [commandLine(read), ...parts, "--remote="].join(" "); +}; + +const waitSection = ( + entry: ApiCommandEntry, + wait: ApiCommandWait, + input: ApiCommandReferenceInput, +): ReadonlyArray => { + const publicRead = input.entries.find((candidate) => candidate.operationId === wait.read); + const polled = publicRead ?? input.pollTargets.find((target) => target.operationId === wait.read); + const polledRoute = polled === undefined ? "unknown route" : route(polled); + const params = Object.entries(wait.params); + return [ + "### Wait", + "", + `- Polls: ${polledRoute} (${code(wait.read)}${publicRead === undefined ? ", poll-only read" : publicRead.operationId === entry.operationId ? ", the command's own read" : ""}).`, + ...(params.length === 0 + ? [] + : [ + `- Read parameters from the change response: ${params + .map(([name, pointer]) => `${code(name)} from ${code(pointer)}`) + .join(", ")}.`, + ]), + `- Status at ${code(wait.status)}; succeeded: ${wait.succeeded.map(code).join(", ")}; failed: ${wait.failed.map(code).join(", ")}.`, + ...(wait.error === undefined ? [] : [`- Failure message from ${code(wait.error)}.`]), + `- Failure hint names ${code(failureHintCommand(entry, wait, input))}.`, + ]; +}; + +const bodyLine = (entry: ApiCommandEntry): string | undefined => { + const { body } = entry; + if (body === undefined) return undefined; + return `JSON envelope ${code(`data.type = ${body.type}`)}, fields under ${code("data.attributes")}`; +}; + +const experimentalLine = ( + entry: ApiCommandEntry, + input: ApiCommandReferenceInput, +): ReadonlyArray => { + const flag = input.nouns[entry.command[0] ?? ""]?.experimental; + return flag === undefined + ? [] + : [ + `- Experimental: enable with ${code(`experimental.${flag}`)} or ${code(`SUPABASE_EXPERIMENTAL_${flag.toUpperCase()}=1`)}.`, + ]; +}; + +const commandSection = ( + entry: ApiCommandEntry, + input: ApiCommandReferenceInput, +): ReadonlyArray => { + const body = bodyLine(entry); + const argument = argumentLine(entry); + const flags = flagRows(entry); + return [ + `## ${code(commandLine(entry))}`, + "", + entry.summary, + "", + ...(entry.examples ?? []).flatMap((example) => [ + example.description, + "", + "```sh", + example.command, + "```", + "", + ]), + ...(entry.description === undefined ? [] : [entry.description, ""]), + `- Access: ${entry.readOnly ? "read-only, no consent" : "mutation, consent defaults to No (`--yes` when it cannot prompt)"}.`, + ...experimentalLine(entry, input), + ...(entry.confirmDescription + ? ["- Consent: prints the API description before the interactive confirmation."] + : []), + `- Request: ${route(entry)} (${code(entry.operationId)}), success ${input.successStatuses.get(entry.operationId)} json.`, + ...(body === undefined ? [] : [`- Body: ${body}.`]), + ...(argument === undefined ? [] : [`- ${argument}`]), + ...(flags.length === 0 + ? [] + : [ + "", + "### Flags", + "", + "| Flag | Type | Required | Repeatable | Binds to |", + "| ---- | ---- | -------- | ---------- | -------- |", + ...flags, + ]), + ...(entry.wait === undefined ? [] : ["", ...waitSection(entry, entry.wait, input)]), + "", + ]; +}; + +/** Renders the per-command reference from the derived entries; formatting is left to oxfmt. */ +export const renderApiCommandReference = (input: ApiCommandReferenceInput): string => + [ + "", + "", + "# Generated API commands", + "", + "Reference for the commands generated from the Management API contract.", + "", + ...input.entries.flatMap((entry) => commandSection(entry, input)), + ].join("\n"); diff --git a/apps/cli/scripts/generate-api-commands.ts b/apps/cli/scripts/generate-api-commands.ts new file mode 100644 index 0000000000..90274762e7 --- /dev/null +++ b/apps/cli/scripts/generate-api-commands.ts @@ -0,0 +1,138 @@ +import { BunRuntime, BunServices } from "@effect/platform-bun"; +import { Console, Data, Effect, FileSystem, Path, Predicate, Schema, Stream } from "effect"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { rootCommandForFeatures } from "../src/cli/root.ts"; +import { + generatedOperations, + nouns, + commandPolicies, +} from "../src/commands/api/api-command-policy.ts"; +import { openApiOperationIdMap } from "@supabase/api/effect"; +import { renderApiCommandReference } from "./api-command-reference.ts"; +import { ApiCommandGenerationError, deriveApiCommands } from "./api-command-derive.ts"; + +class ApiCommandFormatError extends Data.TaggedError("ApiCommandFormatError")<{ + readonly message: string; +}> {} + +class ApiCommandDriftError extends Data.TaggedError("ApiCommandDriftError")<{ + readonly files: ReadonlyArray; +}> { + override get message(): string { + return `Generated API command files are out of date: ${this.files.join(", ")}. Run \`pnpm --filter supabase run api-commands:generate\`.`; + } +} + +const HEADER = "// Generated by scripts/generate-api-commands.ts. Do not edit.\n"; +const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown, { space: 2 })); +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); +const ROOT_OPTIONS: ReadonlyArray[0]> = [ + { stackBackend: "legacy", computeEnabled: false }, + { stackBackend: "legacy", computeEnabled: true }, + { stackBackend: "stack", computeEnabled: false }, + { stackBackend: "stack", computeEnabled: true }, +]; + +/** The root command names: the union of the trees every backend and feature option builds. */ +const handWrittenRoots = Effect.fn("ApiCommands.collectHandWrittenRoots")(function* () { + const roots = new Set(); + for (const options of ROOT_OPTIONS) { + for (const { commands } of rootCommandForFeatures(options).subcommands) { + for (const command of commands) roots.add(command.name); + } + } + yield* Effect.annotateCurrentSpan({ "handWritten.roots": roots.size }); + return roots; +}); + +/** Formats in memory with the repo's oxfmt config so the committed files match `pnpm fmt`. */ +const format = Effect.fn("ApiCommands.format")(function* ( + repoRoot: string, + filePath: string, + source: string, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const output = yield* spawner + .string( + ChildProcess.make( + "node_modules/.bin/oxfmt", + ["-c", ".oxfmtrc.json", "--stdin-filepath", filePath], + { + cwd: repoRoot, + stdin: Stream.make(new TextEncoder().encode(source)), + stderr: "inherit", + }, + ), + ) + .pipe( + Effect.mapError( + (error) => new ApiCommandFormatError({ message: `oxfmt failed: ${error.message}` }), + ), + ); + if (output.trim() === "") { + return yield* new ApiCommandFormatError({ + message: `oxfmt produced no output for ${filePath}`, + }); + } + return output; +}); + +const main = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const check = process.argv.includes("--check"); + const cliRoot = path.resolve(import.meta.dir, ".."); + const repoRoot = path.resolve(cliRoot, "../.."); + const specPath = path.join(repoRoot, "packages/api/src/generated/openapi.json"); + const spec = yield* decodeJson(yield* fs.readFileString(specPath)); + if (!Predicate.isReadonlyObject(spec)) { + return yield* new ApiCommandGenerationError({ problems: ["openapi.json is not an object"] }); + } + + const { entries, pollTargets, successStatuses, problems } = deriveApiCommands({ + spec, + generated: generatedOperations, + policies: commandPolicies, + nouns, + operationIdMap: openApiOperationIdMap, + handWrittenRoots: yield* handWrittenRoots(), + }); + if (problems.length > 0) return yield* new ApiCommandGenerationError({ problems }); + + const outputs = [ + { + relative: "src/commands/api/generated.ts", + source: `${HEADER}import type { ApiCommandEntry, ApiPollTarget } from "./api-command.model.ts";\n\nexport const apiCommands = ${yield* encodeJson(entries)} as const satisfies readonly ApiCommandEntry[];\n\nexport const apiPollTargets = ${yield* encodeJson(pollTargets)} as const satisfies readonly ApiPollTarget[];\n`, + }, + { + relative: "src/commands/api/generated.md", + source: renderApiCommandReference({ entries, pollTargets, successStatuses, nouns }), + }, + ]; + + const stale: Array = []; + for (const output of outputs) { + const target = path.join(cliRoot, output.relative); + const formatted = yield* format(repoRoot, path.relative(repoRoot, target), output.source); + if (check) { + const current = (yield* fs.exists(target)) ? yield* fs.readFileString(target) : undefined; + if (current !== formatted) stale.push(output.relative); + } else { + yield* fs.makeDirectory(path.dirname(target), { recursive: true }); + yield* fs.writeFileString(target, formatted); + yield* Console.log(`Generated: ${output.relative}`); + } + } + if (stale.length > 0) return yield* new ApiCommandDriftError({ files: stale }); + if (check) yield* Console.log("Generated API command files are up to date."); + yield* Effect.annotateCurrentSpan({ + "apiCommands.count": entries.length, + "apiPollTargets.count": pollTargets.length, + }); +}); + +if (import.meta.main) { + BunRuntime.runMain( + main.pipe(Effect.withSpan("ApiCommands.generate"), Effect.provide(BunServices.layer)), + ); +} diff --git a/apps/cli/src/cli/boolean-flag-defaults.unit.test.ts b/apps/cli/src/cli/boolean-flag-defaults.unit.test.ts index c3e6284563..ff25471d5a 100644 --- a/apps/cli/src/cli/boolean-flag-defaults.unit.test.ts +++ b/apps/cli/src/cli/boolean-flag-defaults.unit.test.ts @@ -54,9 +54,13 @@ describe("boolean flag wiring", () => { it("gives every boolean flag a default, so omitting it is not a parse error", () => { for (const stackBackend of ["legacy", "stack"] as const) { for (const computeEnabled of [false, true]) { - expect( - booleanFlagsRequiringAValue(rootCommandForFeatures({ stackBackend, computeEnabled })), - ).toEqual([]); + for (const apiFeatures of [[], ["warehouse"]] as const) { + expect( + booleanFlagsRequiringAValue( + rootCommandForFeatures({ stackBackend, computeEnabled, apiFeatures }), + ), + ).toEqual([]); + } } } }); diff --git a/apps/cli/src/cli/main.ts b/apps/cli/src/cli/main.ts index 4e7a099358..d71cb3c7ce 100644 --- a/apps/cli/src/cli/main.ts +++ b/apps/cli/src/cli/main.ts @@ -7,6 +7,7 @@ import { upgradeNoticeHook } from "../command-internal/upgrade-notice.ts"; import { analyticsLayerFor } from "../telemetry/analytics.layer.ts"; import { defaultCompleteDeps, tryComplete } from "./complete.ts"; import { resolveProjectStateSelection } from "../command-internal/stack-backend.ts"; +import { resolveApiCommandFeatures } from "../commands/api/api-command-features.ts"; import { resolveComputeEnabled } from "../commands/experimental/compute/compute-backend.ts"; import { cliConfigProviderLayer } from "../shared/config/cli-config-provider.layer.ts"; import { cliEntrypointForFeatures, rootCommandForFeatures } from "./root.ts"; @@ -28,12 +29,16 @@ const selectionExit = await Effect.runPromiseExit( args, cwd: process.cwd(), }); - return { projectState, stackBackend, computeEnabled }; + const apiFeatures = yield* resolveApiCommandFeatures({ + args, + cwd: process.cwd(), + }); + return { projectState, stackBackend, computeEnabled, apiFeatures }; }).pipe(Effect.provide(Layer.mergeAll(BunServices.layer, cliConfigProviderLayer))), ); const selectedFeatures = Exit.isSuccess(selectionExit) ? selectionExit.value - : ({ stackBackend: "legacy", computeEnabled: false } as const); + : ({ stackBackend: "legacy", computeEnabled: false, apiFeatures: [] } as const); const { rootCommand: selectedRoot, agentDefaultOutputFormat } = cliEntrypointForFeatures( selectedFeatures, args, diff --git a/apps/cli/src/cli/root.ts b/apps/cli/src/cli/root.ts index 9e41bc8ff5..a8a9c27c31 100644 --- a/apps/cli/src/cli/root.ts +++ b/apps/cli/src/cli/root.ts @@ -18,11 +18,15 @@ import { stackStopCommand } from "../commands/experimental/stack/stop/stop.comma import { stackStatusCommand } from "../commands/experimental/stack/status/status.command.ts"; import type { StackBackend } from "../command-internal/stack-backend.ts"; import { isFunctionsServePath, stackBackendLayer } from "../command-internal/stack-backend.ts"; -import type { ExperimentalFeatureFlagError } from "../shared/config/experimental-feature.ts"; +import type { + ExperimentalFeature, + ExperimentalFeatureFlagError, +} from "../shared/config/experimental-feature.ts"; import { type ProjectStateMode, projectStateModeLayer, } from "../shared/config/project-state-mode.ts"; +import { withApiCommands } from "../commands/api/runtime.ts"; import { computeCommand } from "../commands/experimental/compute/compute.command.ts"; import { feedbackCommand } from "../commands/feedback/feedback.command.ts"; import { functionsCommand } from "../commands/functions/functions.command.ts"; @@ -147,6 +151,7 @@ interface RootCommandFeatures { readonly projectState?: Exit.Exit; readonly stackBackend?: StackBackend; readonly computeEnabled?: boolean; + readonly apiFeatures?: ReadonlyArray; } /** Agents default to stream-json for Stack-backed `functions serve`, which rejects json. */ @@ -161,51 +166,56 @@ const agentDefaultOutputFormatFor = ( export const rootCommandForFeatures = (options: RootCommandFeatures = {}) => Command.make("supabase").pipe( Command.withDescription(rootDescription(CLI_VERSION)), - Command.withSubcommands([ - backupsCommand, - bootstrapCommand, - branchesCommand, - completionCommand, - ...(options.computeEnabled ? [computeCommand] : []), - configCommand, - dbCommand, - domainsCommand, - encryptionCommand, - feedbackCommand, - functionsCommand, - genCommand, - initCommand, - inspectCommand, - issueCommand, - linkCommand, - loginCommand, - logoutCommand, - logsCommandFor(), - migrationCommand, - networkBansCommand, - networkRestrictionsCommand, - notebooksCommand, - orgsCommand, - postgresConfigCommand, - projectsCommand, - pullCommand, - secretsCommand, - seedCommand, - servicesCommand, - snippetsCommand, - sslEnforcementCommand, - ssoCommand, - ...(options.stackBackend === "stack" ? [stackCommand] : []), - options.stackBackend === "stack" ? stackStartAliasCommand : startCommand, - options.stackBackend === "stack" ? stackStatusAliasCommand : statusCommand, - options.stackBackend === "stack" ? stackStopAliasCommand : stopCommand, - storageCommand, - telemetryCommand, - testCommand, - unlinkCommand, - vanitySubdomainsCommand, - whoamiCommand, - ]), + Command.withSubcommands( + withApiCommands( + [ + backupsCommand, + bootstrapCommand, + branchesCommand, + completionCommand, + ...(options.computeEnabled ? [computeCommand] : []), + configCommand, + dbCommand, + domainsCommand, + encryptionCommand, + feedbackCommand, + functionsCommand, + genCommand, + initCommand, + inspectCommand, + issueCommand, + linkCommand, + loginCommand, + logoutCommand, + logsCommandFor(), + migrationCommand, + networkBansCommand, + networkRestrictionsCommand, + notebooksCommand, + orgsCommand, + postgresConfigCommand, + projectsCommand, + pullCommand, + secretsCommand, + seedCommand, + servicesCommand, + snippetsCommand, + sslEnforcementCommand, + ssoCommand, + ...(options.stackBackend === "stack" ? [stackCommand] : []), + options.stackBackend === "stack" ? stackStartAliasCommand : startCommand, + options.stackBackend === "stack" ? stackStatusAliasCommand : statusCommand, + options.stackBackend === "stack" ? stackStopAliasCommand : stopCommand, + storageCommand, + telemetryCommand, + testCommand, + unlinkCommand, + vanitySubdomainsCommand, + whoamiCommand, + ], + options.apiFeatures ?? [], + ), + ), Command.provide( Layer.unwrap( Effect.gen(function* () { diff --git a/apps/cli/src/command-internal/command-errors/api-command.errors.ts b/apps/cli/src/command-internal/command-errors/api-command.errors.ts new file mode 100644 index 0000000000..d966760291 --- /dev/null +++ b/apps/cli/src/command-internal/command-errors/api-command.errors.ts @@ -0,0 +1,66 @@ +import { Data } from "effect"; + +import type { PlanGateEntitlement } from "../../shared/output/normalize-error.ts"; +import { + actionability, + type CliErrorActionabilityDeclaration, + ErrorActionabilityId, + statusCodeActionability, +} from "../../shared/telemetry/error-actionability.ts"; + +/** The Management API answered a generated command with a non-2xx status. */ +export class ApiCommandStatusError extends Data.TaggedError("ApiCommandStatusError")<{ + readonly status: number; + readonly message: string; + readonly suggestion?: string | undefined; + readonly entitlement?: PlanGateEntitlement | undefined; +}> { + get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { + return statusCodeActionability(this.status, { notFoundIsInvalidInput: true }); + } +} + +/** The invocation cannot form a valid request; nothing was sent. */ +export class ApiCommandUsageError extends Data.TaggedError("ApiCommandUsageError")<{ + readonly message: string; + readonly suggestion?: string | undefined; +}> { + get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { + return actionability.invalidInput; + } +} + +/** `--wait` observed the operation reach a failed status. */ +export class ApiCommandOperationFailedError extends Data.TaggedError( + "ApiCommandOperationFailedError", +)<{ + readonly message: string; + readonly status: string; + readonly suggestion: string; +}> { + get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { + return actionability.apiStatus; + } +} + +/** `--wait` read a 2xx response without the status it polls. */ +export class ApiCommandUnexpectedResponseError extends Data.TaggedError( + "ApiCommandUnexpectedResponseError", +)<{ + readonly message: string; + readonly suggestion: string; +}> { + get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { + return { ...actionability.apiStatus, fingerprint_suffix: "api_response" }; + } +} + +/** `--wait` reached its timeout before the operation settled. */ +export class ApiCommandWaitTimeoutError extends Data.TaggedError("ApiCommandWaitTimeoutError")<{ + readonly message: string; + readonly suggestion: string; +}> { + get [ErrorActionabilityId](): CliErrorActionabilityDeclaration { + return { ...actionability.apiStatus, fingerprint_suffix: "operation_timeout" }; + } +} diff --git a/apps/cli/src/command-internal/command-permissions/command-permissions.unit.test.ts b/apps/cli/src/command-internal/command-permissions/command-permissions.unit.test.ts index 527cd603aa..45e0748e90 100644 --- a/apps/cli/src/command-internal/command-permissions/command-permissions.unit.test.ts +++ b/apps/cli/src/command-internal/command-permissions/command-permissions.unit.test.ts @@ -43,6 +43,7 @@ const VARIANTS: ReadonlyArray<{ readonly name: string; readonly variant: Permiss projectState: Exit.succeed("stack"), stackBackend: "stack", computeEnabled: true, + apiFeatures: ["warehouse"], } satisfies Required>, }, ]; diff --git a/apps/cli/src/command-internal/command-permissions/fga-request-sets.unit.test.ts b/apps/cli/src/command-internal/command-permissions/fga-request-sets.unit.test.ts index 72371f570f..d43788145f 100644 --- a/apps/cli/src/command-internal/command-permissions/fga-request-sets.unit.test.ts +++ b/apps/cli/src/command-internal/command-permissions/fga-request-sets.unit.test.ts @@ -19,6 +19,7 @@ const VARIANTS: ReadonlyArray = [ projectState: Exit.succeed("stack"), stackBackend: "stack", computeEnabled: true, + apiFeatures: ["warehouse"], } satisfies Required>, ]; diff --git a/apps/cli/src/command-internal/command-permissions/help-section.tree.unit.test.ts b/apps/cli/src/command-internal/command-permissions/help-section.tree.unit.test.ts index a8b801f817..40fbfa0c50 100644 --- a/apps/cli/src/command-internal/command-permissions/help-section.tree.unit.test.ts +++ b/apps/cli/src/command-internal/command-permissions/help-section.tree.unit.test.ts @@ -21,6 +21,7 @@ const VARIANTS: ReadonlyArray<{ readonly name: string; readonly variant: Permiss projectState: Exit.succeed("stack"), stackBackend: "stack", computeEnabled: true, + apiFeatures: ["warehouse"], } satisfies Required>, }, ]; diff --git a/apps/cli/src/command-internal/db-config.layer.ts b/apps/cli/src/command-internal/db-config.layer.ts index 7e4fef1339..957b9898ab 100644 --- a/apps/cli/src/command-internal/db-config.layer.ts +++ b/apps/cli/src/command-internal/db-config.layer.ts @@ -42,8 +42,8 @@ import { import { DbConnection, type PgConnInput } from "./db-connection.service.ts"; import { IdentityStitch } from "./identity-stitch.ts"; import { - linkedDbResolverRuntimeLayer, - type LinkedDbResolverRuntimeRequirements, + lazyManagementApiRuntimeLayer, + type LazyManagementApiRuntimeRequirements, } from "./management-api-runtime.layer.ts"; import * as Errors from "./db-config.errors.ts"; import { @@ -736,7 +736,7 @@ export const dbConfigResolverLayer = Layer.effect( // directly from its own ambient context). Calling them from here would otherwise leak those // services into `resolveConnection`/`resolvePoolerFallback`'s R (the interface promises // `never`), so every call site below re-closes the gap by additionally providing this layer of - // already-resolved values alongside `linkedDbResolverRuntimeLayer`. + // already-resolved values alongside `lazyManagementApiRuntimeLayer`. const localAmbientServices = Layer.mergeAll( Layer.succeed(FileSystem.FileSystem, fs), Layer.succeed(Path.Path, path), @@ -767,7 +767,7 @@ export const dbConfigResolverLayer = Layer.effect( Layer.succeed(WorkdirFlag, yield* WorkdirFlag), Layer.succeed(OutputFlag, yield* OutputFlag), Layer.succeed(DebugFlag, yield* DebugFlag), - // `linkedDbResolverRuntimeLayer`'s platform-API factory provides a DoH fetch layer that + // `lazyManagementApiRuntimeLayer`'s platform-API factory provides a DoH fetch layer that // reads `DnsResolverFlag`; snapshot it so the lazily built linked stack stays fully // self-provided (`resolveConnection`'s R stays `never`). Layer.succeed(DnsResolverFlag, yield* DnsResolverFlag), @@ -790,12 +790,12 @@ export const dbConfigResolverLayer = Layer.effect( BunServices.layer, BunCrypto.layerSecureRandom, ); - // Compile-time guard: if `linkedDbResolverRuntimeLayer`'s requirements ever + // Compile-time guard: if `lazyManagementApiRuntimeLayer`'s requirements ever // grow a service not captured above, this assignment fails to type-check (the // lazy `Effect.provide` in the `--linked` branch would otherwise leak that // service into `resolveConnection`'s R and only surface as a runtime panic). Mirrors the // `_serviceCoverageCheck` pattern in `management-api-runtime.layer.ts`. - const _ambientCoverageCheck: Layer.Layer = + const _ambientCoverageCheck: Layer.Layer = ambientLayer; void _ambientCoverageCheck; @@ -961,7 +961,7 @@ export const dbConfigResolverLayer = Layer.effect( effect.pipe( Effect.provide( Layer.mergeAll( - linkedDbResolverRuntimeLayer(["test", "db"]).pipe(Layer.provide(ambientLayer)), + lazyManagementApiRuntimeLayer(["test", "db"]).pipe(Layer.provide(ambientLayer)), localAmbientServices, ), ), @@ -1054,7 +1054,7 @@ export const dbConfigResolverLayer = Layer.effect( }).pipe( Effect.provide( Layer.mergeAll( - linkedDbResolverRuntimeLayer(["db", "dump"]).pipe(Layer.provide(ambientLayer)), + lazyManagementApiRuntimeLayer(["db", "dump"]).pipe(Layer.provide(ambientLayer)), localAmbientServices, ), ), diff --git a/apps/cli/src/command-internal/hosted-consent/hosted-consent-coverage.unit.test.ts b/apps/cli/src/command-internal/hosted-consent/hosted-consent-coverage.unit.test.ts index 6193c832b2..f0fedb7837 100644 --- a/apps/cli/src/command-internal/hosted-consent/hosted-consent-coverage.unit.test.ts +++ b/apps/cli/src/command-internal/hosted-consent/hosted-consent-coverage.unit.test.ts @@ -11,7 +11,7 @@ const srcDir = fileURLToPath(new URL("../..", import.meta.url)); const VARIANTS: ReadonlyArray = [ undefined, - { stackBackend: "stack", computeEnabled: true }, + { stackBackend: "stack", computeEnabled: true, apiFeatures: ["warehouse"] }, ]; const consentDefaultByLeaf: ReadonlyMap = new Map( @@ -135,6 +135,12 @@ describe("hosted consent coverage", () => { "test db": "no", "vanity-subdomains activate": "no", "vanity-subdomains delete": "no", + "warehouse disable": "no", + "warehouse enable": "no", + "warehouse replication add": "no", + "warehouse replication remove": "no", + "warehouse replication resync": "no", + "warehouse tables layout update": "no", } `); }); diff --git a/apps/cli/src/command-internal/management-api-runtime.layer.ts b/apps/cli/src/command-internal/management-api-runtime.layer.ts index 419311f577..6ea308910b 100644 --- a/apps/cli/src/command-internal/management-api-runtime.layer.ts +++ b/apps/cli/src/command-internal/management-api-runtime.layer.ts @@ -121,12 +121,13 @@ type ManagementApiServices = | DebugLogger; /** - * Runtime layer for the `--linked` db-config resolver path (`db dump`, `db query`, - * `db schema declarative generate/sync`). Identical to `managementApiRuntimeLayer`, except the - * access token resolves lazily via `CommandPlatformApiFactory` on first use instead of eagerly, so - * `--linked --password …` invocations succeed without requiring a login. + * Management API runtime for commands that may finish without an access token (`--linked + * --password …` db commands, generated API commands under `--dry-run`). Identical to + * `managementApiRuntimeLayer`, except the token resolves lazily through `CommandPlatformApiFactory` + * on first use instead of at layer build. It requires `IdentityStitch` from the caller so the + * factory's client and the linked-project cache share one stitcher. */ -export function linkedDbResolverRuntimeLayer(subcommand: ReadonlyArray) { +export function lazyManagementApiRuntimeLayer(subcommand: ReadonlyArray) { const cliSettings = commandSettingsLayer.pipe(Layer.provide(debugLoggerLayer)); const httpClient = httpClientLayer.pipe(Layer.provide(debugLoggerLayer)); const credentials = commandCredentialsLayer.pipe( @@ -155,6 +156,6 @@ export function linkedDbResolverRuntimeLayer(subcommand: ReadonlyArray) return built; } -type LinkedDbResolverRuntime = ReturnType; -export type LinkedDbResolverRuntimeRequirements = - LinkedDbResolverRuntime extends Layer.Layer ? R : never; +type LazyManagementApiRuntime = ReturnType; +export type LazyManagementApiRuntimeRequirements = + LazyManagementApiRuntime extends Layer.Layer ? R : never; diff --git a/apps/cli/src/command-internal/routing-args.ts b/apps/cli/src/command-internal/routing-args.ts new file mode 100644 index 0000000000..ddb38a6f55 --- /dev/null +++ b/apps/cli/src/command-internal/routing-args.ts @@ -0,0 +1,22 @@ +import { extractCommandPath, hasRootVersionFlag } from "../shared/cli/run.ts"; + +const isCompletionToken = (arg: string | undefined): boolean => + arg === "__complete" || arg === "__completeNoDesc"; + +/** + * Splits argv into the args and command path that backend and feature routing read, or + * `undefined` for `--version`. Completion passes the final token as the cursor word, so it is + * dropped from both, and a leading `help` is dropped from the path so `help ` routes like + * ``. + */ +export const routingArgsFor = ( + args: ReadonlyArray, +): + | { readonly routingArgs: ReadonlyArray; readonly path: ReadonlyArray } + | undefined => { + const routingArgs = isCompletionToken(args[0]) ? args.slice(0, -1) : args; + if (hasRootVersionFlag(routingArgs)) return undefined; + const commandPath = extractCommandPath(routingArgs); + const path = isCompletionToken(commandPath[0]) ? commandPath.slice(1) : commandPath; + return { routingArgs, path: path[0] === "help" ? path.slice(1) : path }; +}; diff --git a/apps/cli/src/command-internal/stack-backend.ts b/apps/cli/src/command-internal/stack-backend.ts index 850836704b..ac79ada7a0 100644 --- a/apps/cli/src/command-internal/stack-backend.ts +++ b/apps/cli/src/command-internal/stack-backend.ts @@ -8,7 +8,7 @@ import { Option, type Path, } from "effect"; -import { extractCommandPath, hasRootVersionFlag } from "../shared/cli/run.ts"; +import { routingArgsFor } from "./routing-args.ts"; import type { ExperimentalFeatureFlagError } from "../shared/config/experimental-feature.ts"; import { projectStateMode, @@ -97,27 +97,15 @@ export const resolveProjectStateSelection = Effect.fn("ProjectState.resolveSelec StackRoutingError, FileSystem.FileSystem | Path.Path > { - // Completion passes the final token as the cursor word, so it is not part of - // the resolved command path. - const routingArgs = - input.args[0] === "__complete" || input.args[0] === "__completeNoDesc" - ? input.args.slice(0, -1) - : input.args; - if (hasRootVersionFlag(routingArgs)) - return { projectState: undefined, stackBackend: undefined }; - - const commandPath = extractCommandPath(routingArgs); - const completePath = - commandPath[0] === "__complete" || commandPath[0] === "__completeNoDesc" - ? commandPath.slice(1) - : commandPath; - const routedPath = completePath[0] === "help" ? completePath.slice(1) : completePath; - const command = routedPath[0]; + const routing = routingArgsFor(input.args); + if (routing === undefined) return { projectState: undefined, stackBackend: undefined }; + const { routingArgs, path } = routing; + const command = path[0]; const routed = command === undefined || command === "stack" || STACK_BACKEND_COMMANDS.has(command) || - isFunctionsServePath(routedPath); + isFunctionsServePath(path); const projectState = yield* Effect.exit(projectStateMode({ ...input, args: routingArgs })); const stackBackend = routed diff --git a/apps/cli/src/command-internal/target/target-policy.unit.test.ts b/apps/cli/src/command-internal/target/target-policy.unit.test.ts index dbe7ef8626..b88a8e1db7 100644 --- a/apps/cli/src/command-internal/target/target-policy.unit.test.ts +++ b/apps/cli/src/command-internal/target/target-policy.unit.test.ts @@ -19,6 +19,7 @@ const VARIANTS: ReadonlyArray<{ readonly name: string; readonly variant: Permiss projectState: Exit.succeed("stack"), stackBackend: "stack", computeEnabled: true, + apiFeatures: ["warehouse"], } satisfies Required>, }, ]; diff --git a/apps/cli/src/commands/api/api-command-bindings.integration.test.ts b/apps/cli/src/commands/api/api-command-bindings.integration.test.ts new file mode 100644 index 0000000000..1b5fcf97ba --- /dev/null +++ b/apps/cli/src/commands/api/api-command-bindings.integration.test.ts @@ -0,0 +1,366 @@ +import { BunServices } from "@effect/platform-bun"; +import { describe, expect, it } from "@effect/vitest"; +import openApiSpec from "@supabase/api/openapi.json"; +import { Effect, Layer, Predicate, Schema, Stdio } from "effect"; +import { CliOutput, Command } from "effect/cli"; + +import { ExperimentalFlag, GLOBAL_FLAGS } from "../../command-internal/global-flags.ts"; +import { textCliOutputFormatter } from "../../shared/output/text-formatter.ts"; +import { + VALID_REF, + VALID_TOKEN, + buildTestRuntime, + mockCommandPlatformApi, + mockCommandSettings, + useTempWorkdir, + withConfigEnv, +} from "../../../tests/helpers/command-mocks.ts"; +import { + mockOutput, + mockRuntimeInfo, + mockStdin, + mockTelemetryRuntime, + mockTty, +} from "../../../tests/helpers/mocks.ts"; +import type { ApiCommandEntry } from "./api-command.model.ts"; +import { apiCommands } from "./generated.ts"; +import { withApiCommands } from "./runtime.ts"; + +type Json = Readonly>; + +const asRecord = (value: unknown): Json => (Predicate.isObject(value) ? value : {}); +const asList = (value: unknown): ReadonlyArray => (Array.isArray(value) ? value : []); + +const spec = asRecord(openApiSpec); +const componentSchemas = asRecord(asRecord(spec["components"])["schemas"]); + +/** Follows `$ref`s to the component schema they name. */ +const resolveRef = (schema: unknown): Json => { + const node = asRecord(schema); + const ref = node["$ref"]; + return typeof ref === "string" + ? resolveRef(componentSchemas[ref.replace("#/components/schemas/", "")]) + : node; +}; + +const at = (schema: unknown, path: readonly string[]): Json => + path.reduce((node, key) => resolveRef(node[key]), resolveRef(schema)); + +interface SpecOperation { + readonly method: string; + readonly template: string; + readonly parameters: ReadonlyArray; + readonly requestSchema: Json | undefined; + readonly responseStatus: number; +} + +const operationOf = (operationId: string): SpecOperation => { + for (const [template, item] of Object.entries(asRecord(spec["paths"]))) { + for (const [method, raw] of Object.entries(asRecord(item))) { + const operation = asRecord(raw); + if (operation["operationId"] !== operationId) continue; + const success = Object.entries(asRecord(operation["responses"])).find(([status]) => + status.startsWith("2"), + ); + if (success === undefined) throw new Error(`${operationId} has no 2xx response`); + const json = (content: unknown) => asRecord(asRecord(content)["application/json"])["schema"]; + const request = json(asRecord(operation["requestBody"])["content"]); + return { + method: method.toUpperCase(), + template, + parameters: asList(operation["parameters"]).map(asRecord), + requestSchema: request === undefined ? undefined : resolveRef(request), + responseStatus: Number(success[0]), + }; + } + } + throw new Error(`${operationId} is not in openapi.json`); +}; + +const PATTERN_SAMPLES: Readonly> = { + "^[1-9]\\d*(s|m|h|d)$": "30m", + "^[a-f0-9]{64}$": "ab".repeat(32), + "^[a-z]+$": "zyxwvutsrqponmlkjihg", + "^[1-9]\\d*$": "16385", + "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$": + "7579647f-2cdc-466c-982e-425958a2f985", +}; + +/** A value the field's schema accepts; an unknown string pattern fails loudly instead of guessing. */ +const sampleOf = (schema: unknown): unknown => { + const node = resolveRef(schema); + const choices = asList(node["enum"]); + if (choices.length > 0) return choices[0]; + switch (node["type"]) { + case "boolean": + return true; + case "array": + return [sampleOf(node["items"]), `${String(sampleOf(node["items"]))}-2`]; + case "string": { + if (node["format"] === "date-time") return "2026-11-18T10:00:00Z"; + const pattern = node["pattern"]; + if (pattern === undefined) return "sample"; + const sample = typeof pattern === "string" ? PATTERN_SAMPLES[pattern] : undefined; + if (sample === undefined) throw new Error(`no sample for string pattern ${String(pattern)}`); + return sample; + } + default: + throw new Error(`no sample for schema type ${String(node["type"])}`); + } +}; + +/** Samples for the body fields that take a JSON value; a field without one fails loudly. */ +const JSON_SAMPLES: Readonly> = { + "v2-update-warehouse-table-layout.sort_by": { kind: "primary_key" }, + "v2-update-warehouse-table-layout.partition_by": [ + { column: "id", transform: { kind: "identity" } }, + ], +}; + +interface Input { + readonly json: boolean; + readonly location: "query" | "body"; + readonly field: string; + readonly flag: string; + readonly required: boolean; + readonly sample: unknown; +} + +/** + * Every non-path input, read from openapi.json; the flag spelling comes from the command's declared + * binding, since naming is the derivation's contract. + */ +const inputsOf = ( + operationId: string, + operation: SpecOperation, + bindings: ApiCommandEntry["bindings"], +): ReadonlyArray => { + const flagFor = (location: Input["location"], field: string) => { + const binding = bindings.find((item) => item.location === location && item.name === field); + return binding?.source === "flag" ? binding.flag : ``; + }; + const queries = operation.parameters + .filter((parameter) => parameter["in"] === "query") + .map((parameter): Input => { + const field = String(parameter["name"]); + return { + json: false, + location: "query", + field, + flag: flagFor("query", field), + required: parameter["required"] === true, + sample: sampleOf(parameter["schema"]), + }; + }); + if (operation.requestSchema === undefined) return queries; + const attributes = at(operation.requestSchema, [ + "properties", + "data", + "properties", + "attributes", + ]); + const envelope = Object.keys(attributes).length > 0; + // Union attributes share their properties across branches; the first branch is one valid choice. + const [firstBranch] = asList(attributes["anyOf"]).map(resolveRef); + const container = firstBranch ?? (envelope ? attributes : operation.requestSchema); + const required = asList(container["required"]); + const scalarTypes = ["boolean", "string"]; + const fields = Object.entries(asRecord(container["properties"])).map(([field, schema]): Input => { + const node = resolveRef(schema); + const scalar = + scalarTypes.includes(String(node["type"])) || + (node["type"] === "array" && scalarTypes.includes(String(resolveRef(node["items"])["type"]))); + const key = `${operationId}.${field}`; + if (!scalar && !Object.hasOwn(JSON_SAMPLES, key)) { + throw new Error(`no JSON sample for body field ${key}`); + } + return { + json: !scalar, + location: "body", + field, + flag: flagFor("body", field), + required: required.includes(field), + sample: scalar ? sampleOf(schema) : JSON_SAMPLES[key], + }; + }); + return [...queries, ...fields]; +}; + +/** The path parameters besides `ref`, each supplied as a positional argument. */ +const positionalsOf = (operation: SpecOperation) => + operation.parameters + .filter((parameter) => parameter["in"] === "path" && parameter["name"] !== "ref") + .map((parameter) => ({ + name: String(parameter["name"]), + sample: String(sampleOf(parameter["schema"])), + })); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +const argvOf = (inputs: ReadonlyArray): ReadonlyArray => + inputs.flatMap((input) => + input.json + ? [`--${input.flag}`, encodeJson(input.sample)] + : Array.isArray(input.sample) + ? input.sample.flatMap((item) => [`--${input.flag}`, String(item)]) + : [`--${input.flag}`, String(input.sample)], + ); + +const expectedQuery = (inputs: ReadonlyArray): Readonly> => + Object.fromEntries( + inputs + .filter((input) => input.location === "query") + .map((input) => [input.field, String(input.sample)]), + ); + +const expectedBody = (operation: SpecOperation, inputs: ReadonlyArray): unknown => { + if (operation.requestSchema === undefined) return undefined; + const attributes = Object.fromEntries( + inputs.filter((input) => input.location === "body").map((input) => [input.field, input.sample]), + ); + const type = asList( + at(operation.requestSchema, ["properties", "data", "properties", "type"])["enum"], + )[0]; + return { data: { type, attributes } }; +}; + +const tempRoot = useTempWorkdir("supabase-api-bindings-int-"); + +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); + +interface Sent { + readonly method: string; + readonly path: string; + readonly search: string; + readonly body: unknown; +} + +const TARGET_LOOKUP_PATH = `/v1/projects/${VALID_REF}`; + +/** Replaces `globalThis.fetch` while `body` runs and answers every call with `status` and `{}`. */ +const withApi = (status: number, sent: Array) => { + const stub = (input: string | URL | Request, init?: RequestInit): Promise => { + const request = input instanceof Request ? input : new Request(String(input), init); + const url = new URL(request.url); + if (url.pathname === TARGET_LOOKUP_PATH) { + return Promise.resolve( + new Response("{}", { status: 200, headers: { "content-type": "application/json" } }), + ); + } + return request.text().then((text) => { + sent.push({ + method: request.method, + path: url.pathname, + search: url.search.replace(/^\?/, ""), + body: text === "" ? undefined : decodeJson(text), + }); + return new Response("{}", { status, headers: { "content-type": "application/json" } }); + }); + }; + return (body: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = globalThis.fetch; + globalThis.fetch = Object.assign(stub, { preconnect: previous.preconnect }); + return previous; + }), + () => body, + (previous) => + Effect.sync(() => { + globalThis.fetch = previous; + }), + ); +}; + +const warehouseRoot = Command.make("supabase").pipe( + Command.withSubcommands(withApiCommands([], ["warehouse"])), + Command.withGlobalFlags(GLOBAL_FLAGS), +); + +/** Runs the real parser and generated leaf for `path` and `argv`; only `fetch` is stubbed. */ +const send = (path: ReadonlyArray, argv: ReadonlyArray, status: number) => { + const args = [...path, ...argv, `--remote=${VALID_REF}`, "--yes"]; + const sent: Array = []; + const layer = Layer.mergeAll( + buildTestRuntime({ + out: mockOutput({ format: "text" }), + api: mockCommandPlatformApi({ response: { status: 200, body: {} } }), + cliSettings: mockCommandSettings({ workdir: tempRoot.current }), + tty: mockTty({ stdinIsTty: false, stdoutIsTty: false }), + stdin: mockStdin(false), + cliArgs: args, + }), + BunServices.layer, + CliOutput.layer(textCliOutputFormatter()), + Layer.succeed(ExperimentalFlag, false), + mockTelemetryRuntime({ configDir: tempRoot.current }), + mockRuntimeInfo({ cwd: tempRoot.current, homeDir: tempRoot.current }), + Stdio.layerTest({ args: Effect.succeed(args) }), + ); + return withConfigEnv( + { SUPABASE_ACCESS_TOKEN: VALID_TOKEN, SUPABASE_NO_KEYRING: "1" }, + Command.runWith(warehouseRoot, { version: "0.0.0-test" })(args), + ).pipe( + withApi(status, sent), + Effect.provide(layer), + Effect.map(() => sent), + ); +}; + +describe("generated command bindings", () => { + for (const entry of apiCommands) { + const { operationId } = entry; + const operation = operationOf(operationId); + // The API rejects `since` combined with `from`/`to`; the relative form is the one sent here. + const inputs = inputsOf(operationId, operation, entry.bindings).filter( + (input, _, all) => + input.location !== "query" || + (input.field !== "from" && input.field !== "to") || + !all.some((other) => other.field === "since"), + ); + const required = inputs.filter((input) => input.required); + const positionals = positionalsOf(operation); + const expectedPath = positionals.reduce( + (path, { name, sample }) => path.replace(`{${name}}`, sample), + operation.template.replace("{ref}", VALID_REF), + ); + + describe(entry.command.join(" "), () => { + it.effect("sends every input at its binding", () => + Effect.gen(function* () { + const requests = yield* send( + entry.command, + [...positionals.map(({ sample }) => sample), ...argvOf(inputs)], + operation.responseStatus, + ); + expect(requests).toHaveLength(1); + const [request] = requests; + expect(request?.method).toBe(operation.method); + expect(request?.path).toBe(expectedPath); + expect(Object.fromEntries(new URLSearchParams(request?.search))).toEqual( + expectedQuery(inputs), + ); + expect(request?.body).toEqual(expectedBody(operation, inputs)); + }), + ); + + if (required.length < inputs.length) { + it.effect("sends only the inputs the spec requires when no other flag is given", () => + Effect.gen(function* () { + const requests = yield* send( + entry.command, + [...positionals.map(({ sample }) => sample), ...argvOf(required)], + operation.responseStatus, + ); + expect(requests).toHaveLength(1); + const [request] = requests; + expect(Object.fromEntries(new URLSearchParams(request?.search))).toEqual( + expectedQuery(required), + ); + expect(request?.body).toEqual(expectedBody(operation, required)); + }), + ); + } + }); + } +}); diff --git a/apps/cli/src/commands/api/api-command-execute.ts b/apps/cli/src/commands/api/api-command-execute.ts new file mode 100644 index 0000000000..c701277d21 --- /dev/null +++ b/apps/cli/src/commands/api/api-command-execute.ts @@ -0,0 +1,406 @@ +import type { ApiClient, OperationId, OperationInput } from "@supabase/api/effect"; +import { operationPermissions } from "@supabase/api/permissions"; +import { DateTime, Duration, Effect, Option, Predicate, Ref, Schedule, Schema } from "effect"; +import * as HttpClientError from "effect/http/HttpClientError"; +import * as Headers from "effect/http/Headers"; +import type * as HttpClientResponse from "effect/http/HttpClientResponse"; + +import { planGateFromResponse, sanitizeErrorBody } from "../../command-internal/http-errors.ts"; +import { Output } from "../../shared/output/output.service.ts"; +import type { OutputFormat } from "../../shared/output/types.ts"; +import { readPointer } from "./api-command-pointer.ts"; +import { definitionOf, type ApiRequestPreview } from "./api-command-request.ts"; +import { renderDryRunText, renderResponseText, singleLine } from "./api-command.format.ts"; +import { + ApiCommandOperationFailedError, + ApiCommandStatusError, + ApiCommandUnexpectedResponseError, + ApiCommandWaitTimeoutError, +} from "../../command-internal/command-errors/api-command.errors.ts"; +import type { ApiCommandEntry, ApiCommandWait, ApiPollRead } from "./api-command.model.ts"; + +const POLL_BASE_DELAY = "1 second"; +const POLL_MAX_DELAY_MILLIS = 10_000; + +const decodeJsonText = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); + +const textDecoder = new TextDecoder(); +const encodeJsonValue = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +/** + * Emits the `{type:"result"}` frame of a stream-json run. `Output.result` would merge the announced + * target into object data, which the json document never carries. + */ +const writeResultFrame = Effect.fnUntraced(function* (data: unknown) { + const output = yield* Output; + return yield* output.event({ + type: "result", + data, + timestamp: DateTime.formatIso(yield* DateTime.now), + }); +}); + +/** Writes the request a dry run would send: a text preview, the JSON document, or a result frame. */ +export const writeDryRun = Effect.fnUntraced(function* ( + preview: ApiRequestPreview, + format: OutputFormat, +) { + const output = yield* Output; + switch (format) { + case "text": + return yield* output.raw(renderDryRunText(preview)); + case "json": + return yield* output.raw(`${encodeJsonValue(preview)}\n`); + case "stream-json": + return yield* writeResultFrame(preview); + } +}); + +const stringField = (source: unknown, key: string): string | undefined => { + if (!Predicate.isObject(source)) return undefined; + const value: unknown = Reflect.get(source, key); + return typeof value === "string" ? value : undefined; +}; + +/** Reads a response body; a body that cannot be read is a transport failure. */ +const readBytes = (response: HttpClientResponse.HttpClientResponse) => + response.arrayBuffer.pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.mapError( + (cause) => + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request: response.request, cause }), + }), + ), + ); + +const permissionHint = (operationId: string): string | undefined => { + const sets = operationPermissions[operationId]?.fga ?? []; + if (sets.length === 0) return undefined; + const alternatives = sets.map((set) => set.join(" + ")).join(" or "); + return `Your token needs the permissions: ${alternatives}.`; +}; + +const statusHint = (operationId: string, status: number): string | undefined => + status === 401 + ? "Run `supabase login`" + : status === 403 + ? permissionHint(operationId) + : undefined; + +/** + * The error fields of a Management API failure body: v2 nests `{code, message, description?}` + * under `error`, v1 puts `message` (and sometimes `code`, `hint`) at the top level. + */ +const apiErrorFields = (body: unknown) => { + const nested = Predicate.isObject(body) ? Reflect.get(body, "error") : undefined; + const source = Predicate.isObject(nested) ? nested : body; + const message = stringField(source, "message"); + const description = stringField(source, "description"); + return { + message: + message === undefined || message === "" + ? description + : description === undefined || description === "" + ? message + : `${message}: ${description}`, + hint: stringField(source, "hint"), + }; +}; + +const statusError = Effect.fnUntraced(function* ( + operationId: string, + response: HttpClientResponse.HttpClientResponse, +) { + const text = textDecoder.decode( + yield* readBytes(response).pipe(Effect.orElseSucceed(() => new Uint8Array())), + ); + const body = Option.getOrUndefined(decodeJsonText(text)); + const fields = apiErrorFields(body); + const { entitlement } = planGateFromResponse(response.status, text); + const ownHint = fields.hint === undefined ? undefined : sanitizeErrorBody(fields.hint); + return yield* new ApiCommandStatusError({ + status: response.status, + message: + fields.message === undefined || fields.message === "" + ? `Unexpected status ${response.status}` + : `${sanitizeErrorBody(fields.message)} (HTTP ${response.status})`, + suggestion: + ownHint === undefined || ownHint.trim() === "" + ? entitlement === undefined + ? statusHint(operationId, response.status) + : undefined + : ownHint, + ...(entitlement === undefined ? {} : { entitlement }), + }); +}); + +/** A 2xx response of an executed operation, with its body read once. */ +export interface ApiCommandResponse { + readonly status: number; + readonly bytes: Uint8Array; + readonly headers: Headers.Headers; +} + +/** + * Sends the decoded input of `entry` through `api` and returns the 2xx response; any other status + * fails with the API's own message and hint. + */ +export const sendApiRequest = Effect.fnUntraced(function* ( + api: ApiClient, + entry: Pick, + decoded: OperationInput, +) { + const response = yield* api.executeRaw(definitionOf(entry), decoded); + if (response.status < 200 || response.status >= 300) { + return yield* statusError(entry.operationId, response); + } + const result: ApiCommandResponse = { + status: response.status, + bytes: yield* readBytes(response), + headers: response.headers, + }; + return result; +}); + +const parseResponse = (response: ApiCommandResponse): unknown => + Option.getOrUndefined(decodeJsonText(textDecoder.decode(response.bytes))); + +const invalidJsonResponse = () => + new ApiCommandUnexpectedResponseError({ + message: "The API returned a success response that is not valid JSON.", + suggestion: "Retry the command; if it keeps failing, report it with the command you ran.", + }); + +/** + * Writes a success response. Machine output requires valid JSON: json passes the bytes through + * untouched and stream-json wraps the parsed value in a result frame; a 2xx without a body is + * `null` there and `Done.` for a person. + */ +export const writeApiResponse = Effect.fnUntraced(function* ( + response: ApiCommandResponse, + format: OutputFormat, +) { + const output = yield* Output; + if (response.bytes.length === 0) { + switch (format) { + case "text": + return yield* output.raw("Done.\n"); + case "json": + return yield* output.raw("null\n"); + case "stream-json": + return yield* writeResultFrame(null); + } + } + const text = textDecoder.decode(response.bytes); + const parsed = decodeJsonText(text); + if (format === "text") { + if (Option.isNone(parsed)) { + const lines = text.endsWith("\n") ? text.slice(0, -1) : text; + return yield* output.raw(`${lines.split("\n").map(singleLine).join("\n")}\n`); + } + return yield* output.raw(renderResponseText(parsed.value)); + } + if (Option.isNone(parsed)) return yield* invalidJsonResponse(); + return format === "json" + ? yield* output.rawBytes(response.bytes) + : yield* writeResultFrame(parsed.value); +}); + +interface WaitInput { + readonly api: ApiClient; + readonly wait: ApiCommandWait; + /** The operation the wait polls; its decoded input is `readInput`. */ + readonly readEntry: ApiPollRead; + /** The command to name in a failure suggestion: the read's own, or the one that inspects a poll-only read. */ + readonly statusEntry: ApiCommandEntry; + /** The flat input of the read operation, as assembled from flags or the change response. */ + readonly readInput: Readonly>; + readonly ref: string; + readonly timeoutMillis: number; + /** Called after each successful poll with the status it read. */ + readonly onPoll?: (status: string | undefined) => Effect.Effect; +} + +export interface PollOutcome { + readonly done: boolean; + readonly response: ApiCommandResponse; +} + +/** The delay a `Retry-After` header asks for, as delta-seconds or an HTTP date. */ +const retryAfterMillis = (headers: Headers.Headers, now: number): number | undefined => { + const value = Option.getOrUndefined(Headers.get(headers, "retry-after"))?.trim(); + if (value === undefined || value === "") return undefined; + if (/^\d+$/u.test(value)) return Number(value) * 1000; + const date = Date.parse(value); + return Number.isNaN(date) ? undefined : Math.max(0, date - now); +}; + +/** Backoff from 1s doubling to a 10s cap; a longer `Retry-After` on the last read wins. */ +export const pollSchedule = Schedule.exponential(POLL_BASE_DELAY).pipe( + Schedule.setInputType(), + Schedule.modifyDelay(({ input, duration, now }) => + Effect.succeed( + Math.max( + Math.min(Duration.toMillis(duration), POLL_MAX_DELAY_MILLIS), + retryAfterMillis(input.response.headers, now) ?? 0, + ), + ), + ), +); + +const failureReason = (reason: unknown): string | undefined => { + if (reason === undefined || reason === null || reason === "") return undefined; + return sanitizeErrorBody(typeof reason === "string" ? reason : encodeJsonValue(reason)); +}; + +/** One poll read: the response, its decoded JSON body and the status the wait reads from it. */ +interface PollRead { + readonly response: ApiCommandResponse; + readonly body: unknown; + readonly status: string | undefined; +} + +const readPoll = (wait: ApiCommandWait, response: ApiCommandResponse): PollRead => { + const body = parseResponse(response); + const status = readPointer(body, wait.status); + return { response, body, status: typeof status === "string" ? status : undefined }; +}; + +const classify = ( + wait: ApiCommandWait, + read: PollRead, + statusHint: string, +): Effect.Effect< + PollOutcome, + ApiCommandOperationFailedError | ApiCommandUnexpectedResponseError +> => { + const { response, body, status } = read; + if (status === undefined) { + return Effect.fail( + new ApiCommandUnexpectedResponseError({ + message: `${wait.read} returned no status at ${wait.status}.`, + suggestion: statusHint, + }), + ); + } + if (wait.failed.includes(status)) { + const reason = + wait.error === undefined ? undefined : failureReason(readPointer(body, wait.error)); + return Effect.fail( + new ApiCommandOperationFailedError({ + status, + message: reason ?? `The operation failed with status "${status}".`, + suggestion: statusHint, + }), + ); + } + const done = wait.succeeded.includes(status); + return Effect.succeed({ done, response }); +}; + +/** The command that re-reads the operation's state, built from the values the wait polls with. */ +const statusCommand = ( + readEntry: ApiCommandEntry, + ref: string, + readInput: Readonly>, +): string => { + const valueOf = (binding: { readonly name: string }) => readInput[binding.name]; + const positional = readEntry.bindings.flatMap((binding) => { + const value = valueOf(binding); + return binding.source === "argument" && value !== undefined ? [String(value)] : []; + }); + const flags = readEntry.bindings.flatMap((binding) => { + const value = valueOf(binding); + return binding.source === "flag" && value !== undefined + ? [`--${binding.flag} ${String(value)}`] + : []; + }); + return ["supabase", ...readEntry.command, ...positional, ...flags, `--remote=${ref}`].join(" "); +}; + +/** + * The input of a linked wait's read: the project ref plus each read parameter taken from the + * change response by pointer. Generation guarantees the response carries them, so a missing one + * is a defect. + */ +export const linkedReadInput = Effect.fnUntraced(function* (input: { + readonly wait: ApiCommandWait; + /** The operation that produced `changed`. */ + readonly changedOperationId: string; + readonly ref: string; + readonly changed: ApiCommandResponse; +}) { + const changedBody = parseResponse(input.changed); + const readInput: Record = { ref: input.ref }; + for (const [param, pointer] of Object.entries(input.wait.params)) { + const value = readPointer(changedBody, pointer); + if (value === undefined || value === null) { + return yield* Effect.die( + new Error( + `${input.changedOperationId} did not return ${pointer}, which ${input.wait.read} needs to wait.`, + ), + ); + } + readInput[param] = value; + } + return readInput; +}); + +/** + * Polls the read operation until it reports a terminal status and returns the final response. A + * failed status, a timeout, or any non-2xx read (a 409 included) ends the wait with an error; the + * failure reason only supplies its message. + */ +export const waitForOperation = Effect.fn("api-command.wait")(function* (input: WaitInput) { + const { wait, readEntry, readInput } = input; + const decoded = yield* Schema.decodeEffect(definitionOf(readEntry).inputSchema, { + onExcessProperty: "error", + })(readInput).pipe(Effect.orDie); + const statusInput = input.statusEntry.operationId === readEntry.operationId ? readInput : {}; + const suggestion = `Check it with \`${statusCommand(input.statusEntry, input.ref, statusInput)}\`.`; + const attempts = yield* Ref.make(0); + const lastStatus = yield* Ref.make(null); + + const poll = Ref.update(attempts, (count) => count + 1).pipe( + Effect.andThen(sendApiRequest(input.api, readEntry, decoded)), + Effect.flatMap((response) => { + const read = readPoll(wait, response); + return Ref.set(lastStatus, read.status ?? null).pipe( + Effect.andThen(classify(wait, read, suggestion)), + Effect.tap(() => input.onPoll?.(read.status) ?? Effect.void), + ); + }), + Effect.withTracerEnabled(false), + ); + + const outcome = yield* poll.pipe( + Effect.repeat({ schedule: pollSchedule, until: (result) => result.done }), + Effect.timeoutOrElse({ + duration: input.timeoutMillis, + orElse: () => + Ref.get(lastStatus).pipe( + Effect.flatMap((status) => + Effect.fail( + new ApiCommandWaitTimeoutError({ + message: `Timed out waiting for ${wait.read} to report ${wait.succeeded.join(" or ")}. Last observed status: ${status === null ? "unavailable" : sanitizeErrorBody(status)}.`, + suggestion, + }), + ), + ), + ), + }), + Effect.tapError((error) => + Ref.get(attempts).pipe( + Effect.flatMap((count) => + Effect.annotateCurrentSpan({ "wait.attempts": count, "wait.outcome": error._tag }), + ), + ), + ), + ); + yield* Effect.annotateCurrentSpan({ + "wait.attempts": yield* Ref.get(attempts), + "wait.outcome": "succeeded", + }); + return outcome.response; +}); diff --git a/apps/cli/src/commands/api/api-command-execute.unit.test.ts b/apps/cli/src/commands/api/api-command-execute.unit.test.ts new file mode 100644 index 0000000000..1f1f1bfdc9 --- /dev/null +++ b/apps/cli/src/commands/api/api-command-execute.unit.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "@effect/vitest"; +import { Effect, Fiber } from "effect"; +import * as Headers from "effect/http/Headers"; +import * as TestClock from "effect/testing/TestClock"; + +import { pollSchedule, type PollOutcome } from "./api-command-execute.ts"; + +const outcome = (headers: Record = {}): PollOutcome => ({ + done: false, + response: { status: 200, bytes: new Uint8Array(), headers: Headers.fromInput(headers) }, +}); + +/** Seconds, on the controlled clock, at which each of `reads` polls runs. */ +const pollTimes = (reads: ReadonlyArray) => + Effect.gen(function* () { + const clock = yield* TestClock.testClockWith(Effect.succeed); + const times: Array = []; + const fiber = yield* Effect.sync(() => { + const read = reads[Math.min(times.length, reads.length - 1)] ?? outcome(); + times.push(clock.currentTimeMillisUnsafe() / 1000); + return read; + }).pipe( + Effect.repeat({ schedule: pollSchedule, times: reads.length - 1 }), + Effect.forkChild({ startImmediately: true }), + ); + for (let second = 0; second < 60; second += 1) yield* TestClock.adjust("1 second"); + yield* Fiber.join(fiber); + return times; + }); + +describe("poll schedule", () => { + it.effect("backs off from 1s doubling to a 10s cap", () => + Effect.gen(function* () { + const times = yield* pollTimes(Array.from({ length: 7 }, () => outcome())); + expect(times).toEqual([0, 1, 3, 7, 15, 25, 35]); + }), + ); + + it.effect("waits for a longer Retry-After given in seconds", () => + Effect.gen(function* () { + const times = yield* pollTimes([outcome({ "retry-after": "5" }), outcome()]); + expect(times).toEqual([0, 5]); + }), + ); + + it.effect("waits for a Retry-After given as an HTTP date", () => + Effect.gen(function* () { + const date = "Thu, 01 Jan 1970 00:00:04 GMT"; + const times = yield* pollTimes([outcome({ "retry-after": date }), outcome()]); + expect(times).toEqual([0, 4]); + }), + ); + + it.effect("never waits less than the backoff for a shorter Retry-After", () => + Effect.gen(function* () { + const times = yield* pollTimes([outcome({ "retry-after": "0" }), outcome()]); + expect(times).toEqual([0, 1]); + }), + ); +}); diff --git a/apps/cli/src/commands/api/api-command-features.ts b/apps/cli/src/commands/api/api-command-features.ts new file mode 100644 index 0000000000..4cc459eb2a --- /dev/null +++ b/apps/cli/src/commands/api/api-command-features.ts @@ -0,0 +1,45 @@ +import { Effect, type FileSystem, type Path } from "effect"; + +import { routingArgsFor } from "../../command-internal/routing-args.ts"; +import { + type ExperimentalFeature, + type ExperimentalFeatureFlagError, + readExperimentalFeatureConfig, + resolveExperimentalFeature, +} from "../../shared/config/experimental-feature.ts"; +import { nouns } from "./api-command-policy.ts"; + +const nounFeatures = (noun: string | undefined): ReadonlyArray => { + if (noun === undefined) + return [...new Set(Object.values(nouns).map(({ experimental }) => experimental))]; + const definition = Object.entries(nouns).find(([name]) => name === noun)?.[1]; + return definition === undefined ? [] : [definition.experimental]; +}; + +/** + * Resolves the experimental features that gate generated API command groups, reading + * configuration only for the features this invocation can reach: every noun feature when no + * command is named (root help and completion), the named noun's feature otherwise. + */ +export const resolveApiCommandFeatures = Effect.fn("ApiCommands.resolveFeatures")( + function* (input: { + readonly args: ReadonlyArray; + readonly cwd: string; + }): Effect.fn.Return< + ReadonlyArray, + ExperimentalFeatureFlagError, + FileSystem.FileSystem | Path.Path + > { + const routing = routingArgsFor(input.args); + if (routing === undefined) return []; + const { routingArgs, path } = routing; + const enabled = yield* Effect.filter(nounFeatures(path[0]), (feature) => + resolveExperimentalFeature({ + feature, + configValue: readExperimentalFeatureConfig({ feature, cwd: input.cwd, args: routingArgs }), + }), + ); + yield* Effect.annotateCurrentSpan("features", enabled); + return enabled; + }, +); diff --git a/apps/cli/src/commands/api/api-command-flags.ts b/apps/cli/src/commands/api/api-command-flags.ts new file mode 100644 index 0000000000..865cc43d15 --- /dev/null +++ b/apps/cli/src/commands/api/api-command-flags.ts @@ -0,0 +1,49 @@ +import { Option } from "effect"; +import { Flag } from "effect/cli"; + +import type { ApiCommandFlag } from "./api-command.model.ts"; + +/** The value a generated flag parses to; `None` records that the flag was absent. */ +export type ApiFlagValue = string | number | boolean | ReadonlyArray; + +const scalarFlag = (flag: ApiCommandFlag): Flag.Flag => { + if (flag.choices !== undefined && flag.choices.length > 0) { + return Flag.Literals(flag.name, flag.choices); + } + switch (flag.type) { + case "string": + return Flag.String(flag.name); + case "json": + return Flag.String(flag.name).pipe(Flag.withMetavar("json")); + case "boolean": + return Flag.Boolean(flag.name); + } +}; + +/** Where a generated flag's value lands in the request. */ +export type ApiFlagLocation = "query" | "body"; + +const describedFlag = (flag: ApiCommandFlag, location: ApiFlagLocation): string => { + const base = flag.description ?? `Set ${flag.name}.`; + const description = flag.type === "json" ? `${base} Takes a JSON value.` : base; + if (!flag.required) return description; + return location === "body" + ? `${description} Required unless the field is in --body or --file.` + : `${description} Required.`; +}; + +/** + * Builds a flag that keeps absence distinct from every value: `Flag.optional` is the outermost + * wrapper, a repeatable flag needs at least one occurrence once present, and a boolean can be + * given as `false`. + */ +export const apiFlag = ( + flag: ApiCommandFlag, + location: ApiFlagLocation, +): Flag.Flag> => { + const described = scalarFlag(flag).pipe(Flag.withDescription(describedFlag(flag, location))); + const shaped: Flag.Flag = flag.repeatable + ? Flag.map(Flag.atLeast(described, 1), (values): ApiFlagValue => values) + : Flag.map(described, (value): ApiFlagValue => value); + return Flag.optional(shaped); +}; diff --git a/apps/cli/src/commands/api/api-command-pointer.ts b/apps/cli/src/commands/api/api-command-pointer.ts new file mode 100644 index 0000000000..0139ac169d --- /dev/null +++ b/apps/cli/src/commands/api/api-command-pointer.ts @@ -0,0 +1,33 @@ +import { Predicate } from "effect"; + +const segmentsOf = (pointer: string): ReadonlyArray => + pointer === "" + ? [] + : pointer + .slice(1) + .split("/") + .map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")); + +/** Reads the value at an RFC 6901 JSON pointer, or `undefined` when any step is missing. */ +export const readPointer = (root: unknown, pointer: string): unknown => { + let current: unknown = root; + for (const segment of segmentsOf(pointer)) { + if (!Predicate.isObject(current)) return undefined; + current = Reflect.get(current, segment); + } + return current; +}; + +const isPlainRecord = (value: unknown): value is Readonly> => + Predicate.isObject(value) && !Array.isArray(value); + +/** Returns a copy of `root` with `value` written at the pointer, creating missing objects. */ +export const writePointer = (root: unknown, pointer: string, value: unknown): unknown => { + const write = (node: unknown, segments: ReadonlyArray): unknown => { + const [head, ...rest] = segments; + if (head === undefined) return value; + const record = isPlainRecord(node) ? node : {}; + return { ...record, [head]: write(record[head], rest) }; + }; + return write(root, segmentsOf(pointer)); +}; diff --git a/apps/cli/src/commands/api/api-command-policy.ts b/apps/cli/src/commands/api/api-command-policy.ts new file mode 100644 index 0000000000..531b307ea1 --- /dev/null +++ b/apps/cli/src/commands/api/api-command-policy.ts @@ -0,0 +1,81 @@ +import type { ApiCommandEntry } from "./api-command.model.ts"; +import type { OpenApiOperationId } from "@supabase/api/effect"; +import type { ExperimentalFeature } from "../../shared/config/experimental-feature.ts"; + +export interface ApiNoun { + /** Help text of the noun's group. */ + readonly description: string; + /** Experimental flag (`experimental.`) that gates every command under the noun. */ + readonly experimental: ExperimentalFeature; + /** Help text of each sub-group, keyed by its dotted path below the noun, e.g. `"tables.layout"`. */ + readonly groups?: Readonly>; +} + +/** Only these operations generate commands, and their response `links` lead to the reads a `--wait` polls. */ +export const generatedOperations: ReadonlyArray = [ + "v2-get-warehouse-status", + "v2-get-warehouse-connection", + "v2-enable-warehouse", + "v2-disable-warehouse", + "v2-get-warehouse-teardown", + "v2-list-warehouse-tables", + "v2-get-warehouse-table", + "v2-get-warehouse-table-layout", + "v2-update-warehouse-table-layout", + "v2-get-warehouse-query-stats", + "v2-get-warehouse-capacity", + "v2-add-warehouse-replication", + "v2-remove-warehouse-replication", + "v2-resync-warehouse-replication", + "v2-restart-warehouse-replication", +]; + +export interface ApiCommandPolicy { + readonly confirmDescription?: true; + readonly examples?: ApiCommandEntry["examples"]; +} + +/** CLI presentation choices, independent of the API's operation metadata. */ +export const commandPolicies = { + "v2-disable-warehouse": { confirmDescription: true }, + "v2-update-warehouse-table-layout": { + confirmDescription: true, + examples: [ + { + command: `supabase warehouse tables layout update --partition-by '[{"column":"event_at","transform":{"kind":"day"}}]' --sort-by '{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}'`, + description: + "Partition new files by event day and sort within files; preserve historical files.", + }, + { + command: `supabase warehouse tables layout update --partition-by '[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]' --dry-run`, + description: "Preview eight hash buckets locally without changing the Warehouse.", + }, + { + command: `supabase warehouse tables layout update --partition-by '[]' --sort-by '{"kind":"none"}'`, + description: "Clear partitioning and sorting for future writes.", + }, + { + command: `supabase warehouse tables layout update --partition-by 'null' --sort-by 'null'`, + description: "Stop managing both settings; omitted flags preserve their saved values.", + }, + ], + }, + "v2-add-warehouse-replication": { confirmDescription: true }, + "v2-remove-warehouse-replication": { confirmDescription: true }, + "v2-resync-warehouse-replication": { confirmDescription: true }, + "v2-restart-warehouse-replication": { confirmDescription: true }, +} satisfies Partial>; + +export const nouns = { + warehouse: { + description: "Manage the data warehouse for a project", + experimental: "warehouse", + groups: { + replication: "Manage Warehouse replication selections and rebuilds", + inspect: "Inspect Warehouse workload metrics", + tables: "Inspect tables replicated to Warehouse", + "tables.layout": "Inspect and update the layout of tables replicated to Warehouse", + teardowns: "Inspect Warehouse cleanup operations", + }, + }, +} as const satisfies Readonly>; diff --git a/apps/cli/src/commands/api/api-command-request.ts b/apps/cli/src/commands/api/api-command-request.ts new file mode 100644 index 0000000000..959d7bd27c --- /dev/null +++ b/apps/cli/src/commands/api/api-command-request.ts @@ -0,0 +1,373 @@ +import { operationDefinitions } from "@supabase/api/effect"; +import { Effect, FileSystem, Option, Predicate, Schema, SchemaIssue } from "effect"; + +import { Stdin } from "../../shared/runtime/stdin.service.ts"; +import type { ApiFlagValue } from "./api-command-flags.ts"; +import { readPointer, writePointer } from "./api-command-pointer.ts"; +import { ApiCommandUsageError } from "../../command-internal/command-errors/api-command.errors.ts"; +import type { ApiCommandEntry } from "./api-command.model.ts"; +import { singleLine } from "./api-command.format.ts"; + +/** Parsed flag values keyed by flag name; `None` means the flag was absent. */ +export type ApiFlagValues = Readonly>>; + +const REDACTED_PREVIEW_VALUE = "[redacted]"; + +const isRecord = (value: unknown): value is Readonly> => + Predicate.isObject(value) && !Array.isArray(value); + +/** The operation's typed definition; the entry names it as a key of `operationDefinitions`. */ +export const definitionOf = (entry: Pick) => + operationDefinitions[entry.definition]; + +const parseBodyText = Effect.fnUntraced(function* (text: string, source: string) { + const parsed = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe( + Effect.mapError( + () => + new ApiCommandUsageError({ + message: `${source} is not valid JSON.`, + suggestion: "Pass the whole request body as one JSON object.", + }), + ), + ); + if (!isRecord(parsed)) { + return yield* new ApiCommandUsageError({ + message: `${source} must be a JSON object.`, + suggestion: "Pass the whole request body as one JSON object.", + }); + } + return parsed; +}); + +/** Reads the whole-body override from `--body` (JSON text) or `--file` (a JSON file, `-` for stdin). */ +export const readBodyOverride = Effect.fn("api-command.read-body")(function* (input: { + readonly body: Option.Option; + readonly file: Option.Option; +}) { + if (Option.isSome(input.body) && Option.isSome(input.file)) { + return yield* new ApiCommandUsageError({ + message: "--body and --file cannot be used together.", + suggestion: "Pass the request body with one of them.", + }); + } + if (Option.isSome(input.body)) { + return Option.some(yield* parseBodyText(input.body.value, "--body")); + } + if (Option.isSome(input.file)) { + const path = input.file.value; + if (path === "-") { + const stdin = yield* Stdin; + const piped = yield* stdin.readPipedText; + if (Option.isNone(piped)) { + return yield* new ApiCommandUsageError({ + message: "--file - found no body on stdin.", + suggestion: "Pipe the request body into the command, or pass --body.", + }); + } + return Option.some(yield* parseBodyText(piped.value, "--file -")); + } + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString(path).pipe( + Effect.mapError( + () => + new ApiCommandUsageError({ + message: `Cannot read the --file body at ${path}.`, + suggestion: "Check that the file exists and is readable.", + }), + ), + ); + return Option.some(yield* parseBodyText(text, `--file ${path}`)); + } + return Option.none>>(); +}); + +const initialBody = (entry: ApiCommandEntry): Readonly> | undefined => { + if (entry.body === undefined) return undefined; + return { data: { type: entry.body.type, attributes: {} } }; +}; + +const parseJsonFlag = (flag: string, text: ApiFlagValue) => + Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe( + Effect.mapError( + () => + new ApiCommandUsageError({ + message: `--${flag} is not valid JSON.`, + suggestion: `Pass a JSON value and quote it for the shell, e.g. --${flag} '{"key":"value"}'.`, + }), + ), + ); + +/** + * The flat operation input `{...bodyFields, ...query, ref, }`. A body + * override is the starting point when given, else the synthesized envelope; only flags that were + * passed are written, each at its own pointer. An override may only carry top-level fields the + * request body declares, and the path values are applied last so body data cannot retarget the + * request. + */ +export const assembleInput = Effect.fnUntraced(function* ( + entry: ApiCommandEntry, + ref: string, + flagValues: ApiFlagValues, + bodyOverride: Option.Option>>, + argument?: string, +) { + if (Option.isSome(bodyOverride)) { + const { requestBody } = definitionOf(entry); + const declared: ReadonlyArray = requestBody.kind === "json" ? requestBody.fields : []; + const unknown = Object.keys(bodyOverride.value).find((key) => !declared.includes(key)); + if (unknown !== undefined) { + return yield* new ApiCommandUsageError({ + message: `--body/--file has the field "${unknown}", which the request body does not take.`, + suggestion: + declared.length === 0 + ? "This command takes no request body." + : `Top-level fields: ${declared.join(", ")}.`, + }); + } + } + const jsonFlagNames = new Set( + entry.flags.filter((flag) => flag.type === "json").map((flag) => flag.name), + ); + let body: unknown = Option.getOrElse(bodyOverride, () => initialBody(entry)); + const query: Record = {}; + const positional: Record = {}; + for (const binding of entry.bindings) { + if (binding.source === "argument") { + if (argument !== undefined) { + if (argument === "" || argument === "." || argument === "..") { + return yield* new ApiCommandUsageError({ + message: `<${binding.argument}> must not be empty, "." or "..".`, + suggestion: "Pass the identifier of the resource.", + }); + } + positional[binding.name] = argument; + } + continue; + } + if (binding.source !== "flag") continue; + const value = flagValues[binding.flag]; + if (value === undefined || Option.isNone(value)) continue; + if (binding.location === "query") query[binding.name] = value.value; + if (binding.location === "body") { + const parsed = jsonFlagNames.has(binding.flag) + ? yield* parseJsonFlag(binding.flag, value.value) + : value.value; + body = writePointer(body, binding.pointer, parsed); + } + } + return { ...(isRecord(body) ? body : {}), ...query, ref, ...positional }; +}); + +type Path = ReadonlyArray; + +/** Input fields of which a request needs at least one; a single path means that field is required. */ +type Requirement = ReadonlyArray; + +const pathKey = (path: Path) => path.map(String).join("/"); + +/** + * Requirements an issue tree reports missing: every required key is one requirement, and a union + * whose branches each miss one key is one requirement of alternatives. `undefined` when the tree + * holds any other failure. + */ +const missingKeyPaths = ( + issue: SchemaIssue.Issue, + path: Path, +): ReadonlyArray | undefined => { + switch (issue._tag) { + case "MissingKey": + return [[path]]; + case "Pointer": + return missingKeyPaths(issue.issue, [...path, ...issue.path]); + case "Filter": + case "Encoding": + return missingKeyPaths(issue.issue, path); + case "Composite": { + const requirements: Requirement[] = []; + for (const child of issue.issues) { + const childRequirements = missingKeyPaths(child, path); + if (childRequirements === undefined) return undefined; + requirements.push(...childRequirements); + } + return requirements.length === 0 ? undefined : requirements; + } + case "AnyOf": { + const alternatives = new Map(); + for (const child of issue.issues) { + const childRequirements = missingKeyPaths(child, path); + if (childRequirements?.length !== 1) return undefined; + for (const alternative of childRequirements[0]!) { + alternatives.set(pathKey(alternative), alternative); + } + } + return alternatives.size === 0 ? undefined : [[...alternatives.values()]]; + } + default: + return undefined; + } +}; + +/** The flag binding that supplies the input field at `path`, if one covers it. */ +const flagAt = (entry: ApiCommandEntry, path: Path) => { + const pointer = `/${path.map(String).join("/")}`; + for (const binding of entry.bindings) { + if (binding.source !== "flag") continue; + if (binding.location === "body" && binding.pointer === pointer) return binding; + if (binding.location === "query" && path.length === 1 && path[0] === binding.name) { + return binding; + } + } + return undefined; +}; + +const pointerOf = (path: Path) => path.map((key) => `/${String(key)}`).join(""); + +/** The CLI surface that supplies the input at `path`: a flag, a positional argument, or the JSON pointer. */ +const surfaceAt = (entry: ApiCommandEntry, path: Path): string => { + const pointer = pointerOf(path); + for (const binding of entry.bindings) { + if (binding.source === "argument" && path[0] === binding.name) return `<${binding.argument}>`; + if (binding.source !== "flag") continue; + if (binding.location === "query" && path[0] === binding.name) return `--${binding.flag}`; + if ( + binding.location === "body" && + (pointer === binding.pointer || pointer.startsWith(`${binding.pointer}/`)) + ) { + return `--${binding.flag}`; + } + } + return pointer === "" ? "the request" : pointer; +}; + +const formatIssues = SchemaIssue.makeFormatterStandardSchemaV1(); +const missingKeyMessage = formatIssues(new SchemaIssue.MissingKey(undefined)).issues[0]?.message; + +/** One line per distinct failure, each naming the flag or argument that supplies the value. */ +const describeIssues = (entry: ApiCommandEntry, issue: SchemaIssue.Issue): string => { + const { issues } = formatIssues(issue); + const failures = issues.some((found) => found.message !== missingKeyMessage) + ? issues.filter((found) => found.message !== missingKeyMessage) + : issues; + const lines = new Set( + failures.map((found) => { + const path = (found.path ?? []).map((segment) => + typeof segment === "object" ? segment.key : segment, + ); + return `${surfaceAt(entry, path)}: ${found.message}`; + }), + ); + return [...lines].join("; "); +}; + +const invalidRequest = (entry: ApiCommandEntry, error: Schema.SchemaError) => { + const requirements = missingKeyPaths(error.issue, []); + const alternatives = requirements?.length === 1 ? requirements[0]! : undefined; + if (alternatives !== undefined && alternatives.length > 1) { + const bindings = alternatives.map((path) => flagAt(entry, path)); + if (bindings.every((binding) => binding !== undefined)) { + const names = bindings.map((binding) => `--${binding.flag}`).join(", "); + return new ApiCommandUsageError({ + message: `Pass at least one of ${names}`, + suggestion: bindings.every((binding) => binding.location === "body") + ? "Pass one of the flags, or include one of the fields in --body/--file." + : "Pass one of the flags.", + }); + } + } + const paths = requirements?.every((requirement) => requirement.length === 1) + ? requirements.map((requirement) => requirement[0]!) + : undefined; + const missing = paths?.map((path) => flagAt(entry, path)); + if (missing !== undefined && missing.every((binding) => binding !== undefined)) { + const names = missing.map((binding) => `--${binding.flag}`).join(", "); + const plural = missing.length === 1 ? "" : "s"; + const allBody = missing.every((binding) => binding.location === "body"); + return new ApiCommandUsageError({ + message: `Missing required flag${plural} ${names}`, + suggestion: allBody + ? `Pass the flag${plural}, or include the field${plural} in --body/--file.` + : `Pass the flag${plural}.`, + }); + } + return new ApiCommandUsageError({ + message: `The request is not valid: ${describeIssues(entry, error.issue)}`, + suggestion: "Check the flags, or the --body/--file contents.", + }); +}; + +/** + * Decodes an assembled input with the operation's input schema, rejecting unknown keys, so a + * request that cannot be formed fails before consent or any network call. + */ +export const decodeInput = (entry: ApiCommandEntry, input: unknown) => + Schema.decodeUnknownEffect(definitionOf(entry).inputSchema, { onExcessProperty: "error" })( + input, + ).pipe(Effect.mapError((error) => invalidRequest(entry, error))); + +/** What a request would send: method, path, query, headers and body, with sensitive flag values masked. */ +export interface ApiRequestPreview { + readonly method: string; + readonly path: string; + readonly query: Readonly>; + readonly headers: Readonly>; + readonly body: unknown; +} + +const pick = (source: object, keys: ReadonlyArray): Record => { + const picked: Record = {}; + for (const key of keys) { + const value: unknown = Reflect.get(source, key); + if (value !== undefined) picked[key] = value; + } + return picked; +}; + +/** Describes the request a decoded input would send. */ +export const previewRequest = (entry: ApiCommandEntry, decoded: object): ApiRequestPreview => { + const definition = definitionOf(entry); + const path = definition.pathParams.reduce( + (current, name) => + current.replace(`{${name}}`, encodeURIComponent(String(Reflect.get(decoded, name)))), + definition.path, + ); + const sensitive = new Set(entry.flags.filter((flag) => flag.sensitive).map((flag) => flag.name)); + let body: unknown = null; + if (definition.requestBody.kind === "json") { + body = pick(decoded, definition.requestBody.fields); + for (const binding of entry.bindings) { + if (binding.location !== "body" || !sensitive.has(binding.flag)) continue; + if (readPointer(body, binding.pointer) !== undefined) { + body = writePointer(body, binding.pointer, REDACTED_PREVIEW_VALUE); + } + } + } + return { + method: definition.method, + path, + query: pick(decoded, definition.queryParams), + headers: pick(decoded, definition.headerParams), + body, + }; +}; + +const detailLine = (name: string, value: unknown): string => + singleLine(`${name}: ${typeof value === "string" ? value : (JSON.stringify(value) ?? "null")}`); + +/** + * The `name: value` lines a consent prompt lists for a validated request: each path parameter + * other than the project ref, each query parameter and each body field, with an envelope body + * listing the fields of its `data.attributes`. Sensitive flag values stay masked. + */ +export const consentDetails = (entry: ApiCommandEntry, decoded: object): ReadonlyArray => { + const { pathParams } = definitionOf(entry); + const preview = previewRequest(entry, decoded); + const attributes = readPointer(preview.body, "/data/attributes"); + const bodyFields = isRecord(attributes) ? attributes : {}; + return [ + ...pathParams + .filter((name) => name !== "ref") + .map((name) => detailLine(name, Reflect.get(decoded, name))), + ...Object.entries(preview.query).map(([name, value]) => detailLine(name, value)), + ...Object.entries(bodyFields).map(([name, value]) => detailLine(name, value)), + ]; +}; diff --git a/apps/cli/src/commands/api/api-command.format.ts b/apps/cli/src/commands/api/api-command.format.ts new file mode 100644 index 0000000000..7d20361aca --- /dev/null +++ b/apps/cli/src/commands/api/api-command.format.ts @@ -0,0 +1,245 @@ +import { renderGlamourTable } from "../../output/glamour-table.ts"; +import type { ApiRequestPreview } from "./api-command-request.ts"; + +const INDENT = " "; +const SAMPLE_SERIES_KEY = "points"; +const SAMPLE_PREVIEW_LIMIT = 10; +const ACRONYMS: ReadonlySet = new Set(["id", "url", "fdw", "dns", "api", "sql", "tls"]); + +type JsonObject = Readonly>; + +const isObject = (value: unknown): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isScalar = (value: unknown): boolean => value === null || typeof value !== "object"; + +const CONTROL_ESCAPES: Readonly> = { + "\r": "\\r", + "\n": "\\n", + "\t": "\\t", +}; + +/** + * Keeps a value on one line and inert in a terminal: line breaks, tabs and the other control + * characters (C0, DEL, C1), bidi controls and line separators become visible `\uXXXX` escapes. + */ +export const singleLine = (text: string): string => + text.replace( + // oxlint-disable-next-line no-control-regex -- escaping control characters is the purpose + /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, + (char) => CONTROL_ESCAPES[char] ?? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); + +const compactJson = (value: unknown): string => singleLine(JSON.stringify(value) ?? "null"); + +/** `snake_case` becomes a sentence-case label; known acronyms stay upper-case. */ +const humanize = (key: string): string => + singleLine(key) + .split("_") + .filter((word) => word !== "") + .map((word, index) => { + const lower = word.toLowerCase(); + if (ACRONYMS.has(lower)) return lower.toUpperCase(); + return index === 0 ? `${lower.charAt(0).toUpperCase()}${lower.slice(1)}` : lower; + }) + .join(" "); + +const scalarText = (value: unknown): string => { + if (value === null || value === undefined) return "-"; + if (typeof value === "boolean") return value ? "yes" : "no"; + if (typeof value === "string") return value === "" ? "-" : singleLine(value); + return singleLine(String(value)); +}; + +const cellText = (value: unknown): string => + isScalar(value) || value === undefined ? scalarText(value) : compactJson(value); + +const isObjectArray = (value: unknown): value is ReadonlyArray => + Array.isArray(value) && value.length > 0 && value.every(isObject); + +/** A table indented under its label; the table's own blank framing lines are dropped. */ +const tableLines = ( + headers: ReadonlyArray, + rows: ReadonlyArray>, + indent: string, +): ReadonlyArray => + renderGlamourTable(headers, rows) + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => `${indent}${line}`); + +const objectTable = ( + items: ReadonlyArray, + columns: ReadonlyArray, + indent: string, +): ReadonlyArray => + tableLines( + columns.map((column) => humanize(column).toUpperCase()), + items.map((item) => columns.map((column) => cellText(item[column]))), + indent, + ); + +const unionKeys = (items: ReadonlyArray): ReadonlyArray => { + const seen = new Set(); + for (const item of items) for (const key of Object.keys(item)) seen.add(key); + return [...seen]; +}; + +/** The inline text of a value that fits on one line, or `undefined` when it needs its own block. */ +const inlineText = (value: unknown): string | undefined => { + if (isScalar(value) || value === undefined) return scalarText(value); + if (Array.isArray(value)) { + if (value.length === 0) return "-"; + if (value.every(isScalar)) return value.map(scalarText).join(", "); + return undefined; + } + return isObject(value) && Object.keys(value).length > 0 ? undefined : "-"; +}; + +const blockLines = (entries: ReadonlyArray, indent: string) => { + const rows = entries.map(([key, value]) => { + const series = key === SAMPLE_SERIES_KEY && Array.isArray(value) && value.length > 0; + return { label: humanize(key), value, series, inline: series ? undefined : inlineText(value) }; + }); + const width = Math.max( + 0, + ...rows.flatMap((row) => (row.inline === undefined ? [] : [row.label.length])), + ); + const lines: Array = []; + for (const { label, value, series, inline } of rows) { + if (inline !== undefined) { + lines.push(`${indent}${label.padEnd(width)}${INDENT}${inline}`); + continue; + } + lines.push(`${indent}${label}`); + if (Array.isArray(value)) { + lines.push(...arrayLines(value, indent, series ? SAMPLE_PREVIEW_LIMIT : value.length)); + } else if (isObject(value)) { + lines.push(...blockLines(Object.entries(value), `${indent}${INDENT}`)); + } + } + return lines; +}; + +const isFlatObjectArray = (value: unknown): value is ReadonlyArray => + isObjectArray(value) && value.every((item) => Object.values(item).every(isScalar)); + +/** Sample series under a `points` key keep only their last samples in response order; other arrays render whole. */ +const arrayLines = ( + items: ReadonlyArray, + indent: string, + limit: number, +): ReadonlyArray => { + const offset = Math.max(0, items.length - limit); + const preview = items.slice(offset); + const notice = + offset === 0 + ? [] + : [ + `${indent}${INDENT}Showing last ${preview.length} of ${items.length} samples; ${offset} omitted; use --output-format json for all samples.`, + ]; + if (isFlatObjectArray(preview)) { + return [...notice, ...objectTable(preview, unionKeys(preview), indent)]; + } + if (preview.every(isScalar)) + return [...notice, `${indent}${INDENT}${preview.map(scalarText).join(", ")}`]; + return [ + ...notice, + ...preview.flatMap((item, index) => { + const label = `Item ${offset + index + 1}`; + return isObject(item) + ? [ + `${indent}${INDENT}${label}`, + ...blockLines(Object.entries(item), `${indent}${INDENT}${INDENT}`), + ] + : blockLines([[label, item]], `${indent}${INDENT}`); + }), + ]; +}; + +const isResource = (value: unknown): value is JsonObject & { readonly attributes: JsonObject } => + isObject(value) && typeof value["type"] === "string" && isObject(value["attributes"]); + +const resourceEntries = (resource: JsonObject & { readonly attributes: JsonObject }) => { + const id = resource["id"]; + return [ + ...(id === undefined || id === null ? [] : ([["id", id]] as const)), + ...Object.entries(resource.attributes), + ]; +}; + +const resourceLines = (document: JsonObject): ReadonlyArray | undefined => { + const keys = Object.keys(document); + const data = document["data"]; + if (keys.length !== 1 || keys[0] !== "data") return undefined; + if (Array.isArray(data) && data.length === 0) return ["No results"]; + if (isResource(data)) { + return [humanize(String(data["type"])), ...blockLines(resourceEntries(data), INDENT)]; + } + if (Array.isArray(data) && data.every(isResource)) { + const rows = data.map((resource) => Object.fromEntries(resourceEntries(resource))); + const columns = unionKeys(rows).filter((column) => + rows.some((row) => row[column] !== undefined), + ); + const nested = new Set(columns.filter((column) => rows.some((row) => !isScalar(row[column])))); + const summary = columns.filter((column) => !nested.has(column)); + const details = data.flatMap((resource, index) => { + const entries = resourceEntries(resource).filter( + ([key, value]) => nested.has(key) && value !== undefined, + ); + if (entries.length === 0) return []; + const id = resource["id"]; + const name = id === undefined || id === null ? `item ${index + 1}` : scalarText(id); + return ["", `${humanize(String(resource["type"]))} ${name}`, ...blockLines(entries, INDENT)]; + }); + return [ + humanize(String(data[0]?.["type"])), + ...(summary.length === 0 ? [] : objectTable(rows, summary, "")), + ...details, + ]; + } + return undefined; +}; + +/** Renders a decoded JSON response as the text a person reads; always ends with a newline. */ +export const renderResponseText = (value: unknown): string => { + if (isObject(value)) { + const lines = resourceLines(value) ?? blockLines(Object.entries(value), ""); + return `${(lines.length === 0 ? ["-"] : lines).join("\n")}\n`; + } + if (Array.isArray(value) && value.length > 0) { + return `${arrayLines(value, "", value.length).join("\n")}\n`; + } + return `${inlineText(value) ?? compactJson(value)}\n`; +}; + +const rawBlock = (title: string, values: Readonly>) => { + const entries = Object.entries(values); + if (entries.length === 0) return []; + const width = Math.max(...entries.map(([key]) => key.length)); + return [ + title, + ...entries.map( + ([key, value]) => `${INDENT}${singleLine(key).padEnd(width)}${INDENT}${cellText(value)}`, + ), + ]; +}; + +/** Renders the request a dry run would send: a summary line, query and headers, then the body. */ +export const renderDryRunText = (preview: ApiRequestPreview): string => { + const body = + preview.body === null || preview.body === undefined + ? [] + : [ + "Body", + ...JSON.stringify(preview.body, null, 2) + .split("\n") + .map((line) => `${INDENT}${singleLine(line)}`), + ]; + return `${[ + `Dry run: ${singleLine(preview.method)} ${singleLine(preview.path)}`, + ...rawBlock("Query", preview.query), + ...rawBlock("Headers", preview.headers), + ...body, + ].join("\n")}\n`; +}; diff --git a/apps/cli/src/commands/api/api-command.format.unit.test.ts b/apps/cli/src/commands/api/api-command.format.unit.test.ts new file mode 100644 index 0000000000..22be6bab9c --- /dev/null +++ b/apps/cli/src/commands/api/api-command.format.unit.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "@effect/vitest"; +import { renderResponseText } from "./api-command.format.ts"; + +describe("renderResponseText", () => { + it("keeps known acronyms upper-case in labels", () => { + expect(renderResponseText({ project_id: "p", base_url: "u", fdw_name: "f", name: "n" })).toBe( + ["Project ID p", "Base URL u", "FDW name f", "Name n", ""].join("\n"), + ); + }); + + it("escapes line breaks and control characters so every value stays on one line", () => { + expect(renderResponseText({ message: "a\nb\tc\u0001d" })).toBe("Message a\\nb\\tc\\u0001d\n"); + }); + + it("escapes C1, bidi and line-separator characters so terminals cannot reorder or split a value", () => { + expect(renderResponseText({ message: "a\u202eb\u009bc\u2028d" })).toBe( + "Message a\\u202eb\\u009bc\\u2028d\n", + ); + }); + + it("escapes control characters in keys so labels stay on one line", () => { + expect(renderResponseText({ "a\nb\u001bc": 1 })).toBe("A\\nb\\u001bc 1\n"); + }); + + it("prints a dash for null and empty strings, arrays and objects", () => { + expect(renderResponseText({ owner: null, note: "", tags: [], limits: {} })).toBe( + ["Owner -", "Note -", "Tags -", "Limits -", ""].join("\n"), + ); + }); + + it("joins arrays of scalars with commas", () => { + expect(renderResponseText({ regions: ["eu", "us"], flags: [true, false] })).toBe( + ["Regions eu, us", "Flags yes, no", ""].join("\n"), + ); + }); + + it("indents nested objects under their label", () => { + expect(renderResponseText({ name: "n", limits: { max: 1, nested: { deep: true } } })).toBe( + ["Name n", "Limits", " Max 1", " Nested", " Deep yes", ""].join("\n"), + ); + }); + + it("prints a clear line for an empty resource collection", () => { + expect(renderResponseText({ data: [] })).toBe("No results\n"); + }); + + it.each([ + { name: "scalar", item: (index: number): unknown => `sample-${index}` }, + { name: "object", item: (index: number): unknown => ({ value: `sample-${index}` }) }, + ])("shows the last 10 $name samples of a points series in response order", ({ item }) => { + const points = Array.from({ length: 12 }, (_, index) => item(index)); + const output = renderResponseText({ points }); + expect(output).not.toMatch(/sample-[01]\b/); + expect(output.indexOf("sample-2")).toBeGreaterThanOrEqual(0); + expect(output.indexOf("sample-2")).toBeLessThan(output.indexOf("sample-11")); + expect(output).toContain( + "Showing last 10 of 12 samples; 2 omitted; use --output-format json for all samples.", + ); + expect(renderResponseText({ points: points.slice(2) })).not.toContain("omitted"); + }); + + it("bounds points series nested inside a top-level array of objects", () => { + const points = Array.from({ length: 12 }, (_, index) => `point-${index}`); + const output = renderResponseText([{ points }]); + expect(output).not.toMatch(/point-[01]\b/); + expect(output).toContain("point-11"); + expect(output).toContain("2 omitted"); + }); + + it("renders every item of an array that is not a points series", () => { + const tables = Array.from({ length: 12 }, (_, index) => ({ name: `table-${index}` })); + const output = renderResponseText({ tables }); + expect(output).toContain("table-0"); + expect(output).toContain("table-11"); + expect(output).not.toContain("omitted"); + }); +}); diff --git a/apps/cli/src/commands/api/api-command.model.ts b/apps/cli/src/commands/api/api-command.model.ts new file mode 100644 index 0000000000..f647118a1b --- /dev/null +++ b/apps/cli/src/commands/api/api-command.model.ts @@ -0,0 +1,104 @@ +import type { OperationId } from "@supabase/api/effect"; + +/** Where a generated command's input lands in the API request. */ +export type ApiCommandBinding = + | { + readonly location: "path"; + /** Path parameter name. */ + readonly name: string; + /** The value comes from the command target (`--project-ref` or the linked project), not a flag. */ + readonly source: "target"; + } + | { + readonly location: "path"; + readonly name: string; + /** The value comes from the command's positional argument. */ + readonly source: "argument"; + /** Name of the positional argument that supplies the value. */ + readonly argument: string; + } + | { + readonly location: "query"; + /** Query parameter name. */ + readonly name: string; + readonly source: "flag"; + /** Name of the flag that supplies the value. */ + readonly flag: string; + } + | { + readonly location: "body"; + /** Body field name. */ + readonly name: string; + /** JSON Pointer to the field in the whole request body, e.g. `/data/attributes/schema`. */ + readonly pointer: string; + readonly source: "flag"; + readonly flag: string; + }; + +/** One flag of a generated command, derived from a query parameter or a request body field. */ +export interface ApiCommandFlag { + /** Kebab-case flag name without the leading dashes. */ + readonly name: string; + /** `json` takes a JSON value for a body field that is not a scalar or an array of scalars. */ + readonly type: "string" | "boolean" | "json"; + readonly choices?: readonly string[]; + readonly repeatable: boolean; + readonly required: boolean; + /** A body field reviewed as a secret; its value is never echoed or recorded. */ + readonly sensitive?: true; + readonly description?: string; +} + +/** What `--wait` polls after a change and when it is done. */ +export interface ApiCommandWait { + /** Operation id of the read operation to poll; the command's own when it polls itself. */ + readonly read: string; + /** Read parameter name to JSON pointer into the change response. */ + readonly params: Readonly>; + /** JSON pointer to the status in the read response. */ + readonly status: string; + readonly succeeded: readonly string[]; + readonly failed: readonly string[]; + /** JSON pointer to the failure reason in the read response. */ + readonly error?: string; +} + +/** A generated command as plain data; the runtime turns each entry into a CLI command. */ +export interface ApiCommandEntry { + /** Noun, optional sub-groups and the method, e.g. `["warehouse", "enable"]`. */ + readonly command: readonly string[]; + /** Kebab-case operation id from the OpenAPI spec. */ + readonly operationId: string; + /** Key of the operation in the typed client's `operationDefinitions`. */ + readonly definition: OperationId; + readonly summary: string; + readonly description?: string; + readonly readOnly: boolean; + /** Show the API description as impact details before hosted consent. */ + readonly confirmDescription?: true; + /** Request body: an envelope that wraps the fields in `data.attributes`. */ + readonly body?: { + readonly contentType: "application/json"; + /** The envelope's `data.type` value. */ + readonly type: string; + }; + /** The positional argument that carries the operation's one non-`ref` path parameter. */ + readonly argument?: { + readonly name: string; + readonly description?: string; + }; + /** Concrete invocation examples maintained by the CLI command policy. */ + readonly examples?: readonly { readonly command: string; readonly description: string }[]; + readonly flags: readonly ApiCommandFlag[]; + readonly bindings: readonly ApiCommandBinding[]; + readonly wait?: ApiCommandWait; +} + +/** The operation a wait polls: a generated command's entry or a hidden {@link ApiPollTarget}. */ +export type ApiPollRead = Pick; + +/** A response-linked read used for polling without registering a CLI command. */ +export interface ApiPollTarget extends ApiPollRead { + /** Operation id of the generated command that inspects the state after a failed or timed-out wait. */ + readonly inspect: string; +} diff --git a/apps/cli/src/commands/api/api-commands.e2e.test.ts b/apps/cli/src/commands/api/api-commands.e2e.test.ts new file mode 100644 index 0000000000..a06f576405 --- /dev/null +++ b/apps/cli/src/commands/api/api-commands.e2e.test.ts @@ -0,0 +1,353 @@ +import { BunServices } from "@effect/platform-bun"; +import { expect, it } from "@effect/vitest"; +import type { OperationOutput } from "@supabase/api/effect"; +import { Data, Effect, FileSystem, Path, Schema } from "effect"; + +import { makeTempHome, requireCliSuccess, runSupabaseEffect } from "../../../tests/helpers/cli.ts"; + +class ApiCommandsE2eSetupError extends Data.TaggedError("ApiCommandsE2eSetupError")<{ + readonly cause: unknown; +}> { + override get message(): string { + return this.cause instanceof Error ? this.cause.message : String(this.cause); + } +} + +const REF = "abcdefghijklmnopqrst"; +const ACCESS_TOKEN = `sbp_${"a".repeat(40)}`; +const SEL = "ab".repeat(32); +const ENABLE_PATH = `/v2/projects/${REF}/warehouse/enable`; +const SETUP_PATH = `/v2/projects/${REF}/warehouse/setups/current`; + +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); +const decodeLines = (text: string) => + text + .split("\n") + .filter((line) => line !== "") + .map((line) => decodeJson(line)); + +interface Served { + readonly status: number; + readonly body: string; +} + +const json = (status: number, body: unknown): Served => ({ + status, + body: JSON.stringify(body), +}); + +const statusBody = (state: string) => + json(200, { + data: { type: "warehouse_setup", attributes: { selection_id: SEL, status: state } }, + }); + +/** + * Runs the compiled CLI against a local Management API that answers `route`; the project + * lookup every `--remote` run makes is answered here. + */ +const runWarehouse = ( + args: ReadonlyArray, + route: (request: { readonly method: string; readonly pathname: string }) => Served, + options: { readonly stdin?: string } = {}, +) => + Effect.gen(function* () { + const requests: Array = []; + const bodies: Array = []; + const runPromise = Effect.runPromiseWith(yield* Effect.context()); + const server = yield* Effect.acquireRelease( + Effect.try({ + try: () => + Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: (incoming) => + runPromise( + Effect.gen(function* () { + const { pathname } = new URL(incoming.url); + if (pathname === `/v1/projects/${REF}`) return Response.json({}); + requests.push(`${incoming.method} ${pathname}`); + bodies.push(yield* Effect.promise(() => incoming.text())); + const served = route({ method: incoming.method, pathname }); + return new Response(served.body, { + status: served.status, + headers: { "content-type": "application/json" }, + }); + }), + ), + }), + catch: (cause) => new ApiCommandsE2eSetupError({ cause }), + }), + (running) => Effect.promise(() => running.stop(true)), + ); + const home = yield* makeTempHome.pipe( + Effect.mapError((cause) => new ApiCommandsE2eSetupError({ cause })), + ); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profilePath = path.join(home.dir, "api-commands-profile.yaml"); + yield* fs.writeFileString( + profilePath, + [ + "name: api-commands-e2e", + `api_url: "${server.url.origin}"`, + `dashboard_url: "${server.url.origin}"`, + 'project_host: "example.invalid"', + "", + ].join("\n"), + ); + const result = yield* runSupabaseEffect(["warehouse", ...args, `--remote=${REF}`], { + cwd: home.dir, + home: home.dir, + ...(options.stdin === undefined ? {} : { stdin: options.stdin }), + env: { + SUPABASE_ACCESS_TOKEN: ACCESS_TOKEN, + SUPABASE_EXPERIMENTAL_WAREHOUSE: "1", + SUPABASE_NO_KEYRING: "1", + SUPABASE_PROFILE: profilePath, + SUPABASE_TELEMETRY_DISABLED: "1", + SUPABASE_WORKDIR: home.dir, + SUPABASE_YES: undefined, + }, + }); + return { result, requests, bodies }; + }).pipe(Effect.scoped); + +it.live.each([ + { command: "query-stats", metric: "query_rate", unit: "per_second", aggregation: "rate" }, + { command: "capacity", metric: "query_in_flight", unit: "queries", aggregation: "sum" }, +] as const)( + "warehouse inspect $command reaches the public route through the compiled CLI", + ({ command, metric, unit, aggregation }) => + Effect.gen(function* () { + const response = json(200, { + data: [ + { + type: "warehouse_metric", + id: metric, + attributes: { + project_ref: REF, + metric, + unit, + aggregation, + definition: "Executor query invocations.", + requested: { metric, start: 1795000000, end: 1795001800 }, + effective: { start: 1795000000, end: 1795001800, step: 60, rate_window_seconds: 300 }, + scrape_interval_seconds: 60, + last_sample_at: null, + availability: "unavailable", + series: [], + }, + }, + ], + } satisfies + | OperationOutput<"v2GetWarehouseQueryStats"> + | OperationOutput<"v2GetWarehouseCapacity">); + const { result, requests } = yield* runWarehouse( + ["inspect", command, "--since", "30m", "--output-format", "json"], + () => response, + ); + + requireCliSuccess(result, `warehouse inspect ${command}`); + expect(result.stdout, result.stderr).toBe(response.body); + expect(requests).toEqual([`GET /v2/projects/${REF}/warehouse/${command}`]); + }).pipe(Effect.provide(BunServices.layer)), +); + +const conflict = json(409, { + error: { + code: "selection_conflict", + message: "The selection changed", + description: "Re-run enable.", + }, +}); + +it.live("warehouse status reports a 409 as a text failure when stdout is piped", () => + Effect.gen(function* () { + const { result } = yield* runWarehouse(["status"], () => conflict); + + expect(result.exitCode, result.stderr).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("The selection changed: Re-run enable. (HTTP 409)"); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse status reports a 409 as an error document with --output-format json", () => + Effect.gen(function* () { + const { result } = yield* runWarehouse(["status", "--output-format", "json"], () => conflict); + + expect(result.exitCode, result.stderr).toBe(1); + expect(decodeJson(result.stdout)).toMatchObject({ + _tag: "Error", + error: { + code: "ApiCommandStatusError", + message: "The selection changed: Re-run enable. (HTTP 409)", + }, + }); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse status reports a 409 as an error frame with --output-format stream-json", () => + Effect.gen(function* () { + const { result } = yield* runWarehouse( + ["status", "--output-format", "stream-json"], + () => conflict, + ); + + expect(result.exitCode, result.stderr).toBe(1); + const frames = decodeLines(result.stdout); + expect(frames.at(-1)).toMatchObject({ + type: "error", + error: { code: "ApiCommandStatusError" }, + }); + expect(frames.filter((frame) => (frame as { type?: string }).type === "result")).toEqual([]); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse status prints the consolidated status as text when stdout is piped", () => + Effect.gen(function* () { + const response = json(200, { + data: { + type: "warehouse_context", + id: REF, + attributes: { + enabled: true, + status: "ready", + configured_readiness: "ready", + query_connectivity: "not_checked", + tables: { status: "available", items: [] }, + replication: { status: "not_started", apply_lag: null }, + capabilities: { replication_add: false, replication_remove: false }, + }, + }, + }); + const { result, requests } = yield* runWarehouse(["status"], () => response); + + requireCliSuccess(result, "warehouse status"); + expect(result.stdout).toBe( + [ + "Warehouse context", + ` ID ${REF}`, + " Enabled yes", + " Status ready", + " Configured readiness ready", + " Query connectivity not_checked", + " Tables", + " Status available", + " Items -", + " Replication", + " Status not_started", + " Apply lag -", + " Capabilities", + " Replication add no", + " Replication remove no", + "", + ].join("\n"), + ); + expect(requests).toEqual([`GET /v2/projects/${REF}/warehouse/status`]); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live( + "warehouse status --output-format json keeps the API bytes and shows progress on stderr", + () => + Effect.gen(function* () { + const response = json(200, { data: { type: "warehouse_context", id: REF, attributes: {} } }); + const { result } = yield* runWarehouse(["status", "--output-format", "json"], () => response); + + requireCliSuccess(result, "warehouse status --output-format json"); + expect(result.stdout).toBe(response.body); + expect(result.stderr).toContain("[task] start:"); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse status --output-format stream-json emits one result frame", () => + Effect.gen(function* () { + const response = json(200, { data: { type: "warehouse_context", id: REF, attributes: {} } }); + const { result } = yield* runWarehouse( + ["status", "--output-format", "stream-json"], + () => response, + ); + + requireCliSuccess(result, "warehouse status --output-format stream-json"); + const frames = decodeLines(result.stdout); + expect(frames.filter((frame) => (frame as { type?: string }).type === "result")).toEqual([ + { + type: "result", + data: decodeJson(response.body), + timestamp: expect.any(String), + }, + ]); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse enable --wait prints the accepted response after the setup succeeds", () => + Effect.gen(function* () { + const accepted = json(202, { data: { attributes: { selection_id: SEL } } }); + const { result, requests } = yield* runWarehouse( + ["enable", "--schema", "public", "--wait", "--yes", "--output-format", "json"], + (request) => (request.method === "POST" ? accepted : statusBody("succeeded")), + ); + + requireCliSuccess(result, "warehouse enable --wait"); + expect(result.stdout, result.stderr).toBe(accepted.body); + expect(requests).toEqual([`POST ${ENABLE_PATH}`, `GET ${SETUP_PATH}`]); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse enable --wait --output-format stream-json logs progress before the result", () => + Effect.gen(function* () { + const accepted = json(202, { data: { attributes: { selection_id: SEL } } }); + const { result } = yield* runWarehouse( + ["enable", "--schema", "public", "--wait", "--yes", "--output-format", "stream-json"], + (request) => (request.method === "POST" ? accepted : statusBody("succeeded")), + ); + + requireCliSuccess(result, "warehouse enable --wait stream-json"); + const frames = decodeLines(result.stdout) as ReadonlyArray<{ type: string }>; + expect(frames.at(-1)).toEqual({ + type: "result", + data: decodeJson(accepted.body), + timestamp: expect.any(String), + }); + expect(frames.filter((frame) => frame.type === "result")).toHaveLength(1); + expect(frames.slice(0, -1).every((frame) => frame.type === "log")).toBe(true); + expect(frames.length).toBeGreaterThan(1); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse enable without --yes refuses to run when stdin is piped", () => + Effect.gen(function* () { + const { result, requests } = yield* runWarehouse( + ["enable", "--schema", "public", "--output-format", "json"], + () => json(202, {}), + { stdin: "" }, + ); + + expect(result.exitCode, result.stderr).toBe(1); + expect(decodeJson(result.stdout)).toMatchObject({ + _tag: "Error", + error: { + code: "HostedMutationConsentRequiredError", + suggestion: expect.stringContaining("--yes"), + }, + }); + expect(requests).toEqual([]); + }).pipe(Effect.provide(BunServices.layer)), +); + +it.live("warehouse enable --file - reads the request body piped on stdin", () => + Effect.gen(function* () { + const accepted = `{"data":{"type":"warehouse_setup","attributes":{"selection_id":"${SEL}","status":"pending","future_field":{"nested":[1, 2]}}}}`; + const body = '{"data":{"type":"warehouse_setup","attributes":{"schema":"public"}}}'; + const { result, requests, bodies } = yield* runWarehouse( + ["enable", "--file", "-", "--yes", "--output-format", "json"], + () => ({ status: 202, body: accepted }), + { stdin: body }, + ); + + requireCliSuccess(result, "warehouse enable --file -"); + expect(result.stdout, result.stderr).toBe(accepted); + expect(requests).toEqual([`POST ${ENABLE_PATH}`]); + expect(decodeJson(bodies[0] ?? "")).toEqual(decodeJson(body)); + }).pipe(Effect.provide(BunServices.layer)), +); diff --git a/apps/cli/src/commands/api/api-commands.integration.test.ts b/apps/cli/src/commands/api/api-commands.integration.test.ts new file mode 100644 index 0000000000..5d0d6fda84 --- /dev/null +++ b/apps/cli/src/commands/api/api-commands.integration.test.ts @@ -0,0 +1,3024 @@ +import { BunServices } from "@effect/platform-bun"; +import { describe, expect, it } from "@effect/vitest"; +import type { OperationOutput } from "@supabase/api/effect"; +import { + Cause, + Console, + Effect, + Exit, + Fiber, + FileSystem, + Layer, + Option, + Path, + Schema, + Stdio, +} from "effect"; +import { CliOutput, Command } from "effect/cli"; +import * as HttpClientError from "effect/http/HttpClientError"; +import * as TestClock from "effect/testing/TestClock"; + +import { respondToComplete } from "../../cli/complete.ts"; +import { rootCommandForFeatures } from "../../cli/root.ts"; +import { ExperimentalFlag, ROOT_GLOBAL_FLAGS } from "../../command-internal/global-flags.ts"; +import { HostedMutationConsentRequiredError } from "../../command-internal/hosted-consent/hosted-consent.errors.ts"; +import { unsupportedOutputFlagMessage } from "../../command-internal/output-formats.ts"; +import { ExperimentalFeatureFlagError } from "../../shared/config/experimental-feature.ts"; +import { normalizeCause } from "../../shared/output/normalize-error.ts"; +import { textCliOutputFormatter } from "../../shared/output/text-formatter.ts"; +import type { OutputFormat } from "../../shared/output/types.ts"; +import { commandTreeFor } from "../../../tests/helpers/command-flags.ts"; +import { + VALID_REF, + VALID_TOKEN, + buildTestRuntime, + mockCommandPlatformApi, + mockCommandSettings, + useTempWorkdir, + withConfigEnv, +} from "../../../tests/helpers/command-mocks.ts"; +import { describeHostedConsent } from "../../../tests/helpers/hosted-consent.ts"; +import { + fakeConsole, + mockAnalytics, + mockOutput, + mockRuntimeInfo, + mockStdin, + mockTelemetryRuntime, + mockTty, +} from "../../../tests/helpers/mocks.ts"; +import { + ApiCommandOperationFailedError, + ApiCommandStatusError, + ApiCommandUsageError, + ApiCommandUnexpectedResponseError, + ApiCommandWaitTimeoutError, +} from "../../command-internal/command-errors/api-command.errors.ts"; +import type { ApiCommandEntry } from "./api-command.model.ts"; +import { assembleInput, decodeInput, previewRequest } from "./api-command-request.ts"; +import { apiCommands } from "./generated.ts"; +import { readPermissions } from "../../command-internal/command-permissions/command-permissions.annotation.ts"; +import { withApiCommands } from "./runtime.ts"; +import { EventUpgradeSuggested } from "../../shared/telemetry/event-catalog.ts"; +import { resolveApiCommandFeatures } from "./api-command-features.ts"; + +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +const entryOf = (path: string): ApiCommandEntry => { + const entry = apiCommands.find((candidate) => candidate.command.join(" ") === path); + if (entry === undefined) throw new Error(`no generated command "${path}"`); + return entry; +}; + +const enable = entryOf("warehouse enable"); + +const ENABLE_PATH = `/v2/projects/${VALID_REF}/warehouse/enable`; +const STATUS_PATH = `/v2/projects/${VALID_REF}/warehouse/status`; +const SETUP_PATH = `/v2/projects/${VALID_REF}/warehouse/setups/current`; +const TARGET_LOOKUP_PATH = `/v1/projects/${VALID_REF}`; + +const SEL = "ab".repeat(32); + +const ACCEPTED = { + data: { + type: "warehouse_setup", + id: SEL, + attributes: { selection_id: SEL, status: "pending", future_field: { nested: [1, 2] } }, + }, +}; + +const statusBody = (state: string, statusError?: string) => ({ + data: { + type: "warehouse_setup", + attributes: { + selection_id: SEL, + status: state, + ...(statusError === undefined ? {} : { status_error: statusError }), + }, + }, +}); + +const RICH_STATUS = { + data: { + type: "warehouse_setup", + id: SEL, + attributes: { + dns: { hostname: "wh.example.test", region: "us-east-1", status: "active" }, + delete_data: false, + setup_status: "ready", + pipeline_id: 42, + steps: [ + { name: "create_pipeline", status: "succeeded" }, + { name: "import_foreign_schema", status: "failed", message: "line one\nline two" }, + ], + tables: [ + { + schema: "public", + name: "orders", + state: "synced", + lag_ms: 120, + last_synced_at: "2026-01-01T00:00:00Z", + copy_name: '"public"."orders"', + replication_state: "streaming", + }, + { + schema: "public", + name: "users", + state: "copying", + copy_name: '"public"."users"', + warehouse_size_bytes: 2048, + replication_state: "copying", + }, + ], + fdw_status: { + extension_available: true, + extension_installed: true, + wrapper_installed: false, + server_configured: false, + schema_created: false, + foreign_schema_imported: false, + }, + status: "succeeded", + replication_state: "streaming", + }, + }, +}; + +/** One request the CLI sent to the stubbed Management API. */ +interface Sent { + readonly method: string; + readonly path: string; + readonly search: string; + readonly body: unknown; +} + +/** A canned API answer; a string body is sent as is, anything else as JSON. */ +interface Reply { + readonly status: number; + readonly body?: unknown; + /** Fails the body stream mid-read, after the status line was delivered. */ + readonly unreadable?: boolean; +} + +type Route = (request: Sent) => Reply; + +const ok = + (body: unknown): Route => + () => ({ status: 200, body }); +const accepted: Route = () => ({ status: 202, body: ACCEPTED }); + +/** Answers the enable POST with `ACCEPTED` and each later read with the next of `reads`. */ +const enableThenPoll = (reads: ReadonlyArray): Route => { + let read = 0; + return (request) => { + if (request.method === "POST") return { status: 202, body: ACCEPTED }; + const next = reads[Math.min(read, reads.length - 1)]; + read += 1; + return next ?? { status: 200, body: {} }; + }; +}; + +const replyOf = (reply: Reply): Response => { + if (reply.unreadable === true) { + const broken = new ReadableStream({ + pull: (controller) => controller.error(new Error("connection reset")), + }); + return new Response(broken, { + status: reply.status, + headers: { "content-type": "application/json" }, + }); + } + const text = + reply.body === undefined + ? null + : typeof reply.body === "string" + ? reply.body + : encodeJson(reply.body); + return new Response(text, { + status: reply.status, + headers: reply.body === undefined ? {} : { "content-type": "application/json" }, + }); +}; + +/** Replaces `globalThis.fetch` while `body` runs: the one in-process seam under the real leaf. */ +const withApi = (route: Route, sent: Array, seen: Array) => { + const stub = (input: string | URL | Request, init?: RequestInit): Promise => { + const request = input instanceof Request ? input : new Request(String(input), init); + const url = new URL(request.url); + seen.push(`${request.method} ${url.pathname}`); + if (url.pathname === TARGET_LOOKUP_PATH) { + return Promise.resolve(replyOf({ status: 200, body: {} })); + } + return request.text().then((text) => { + const entry: Sent = { + method: request.method, + path: url.pathname, + search: url.search.replace(/^\?/, ""), + body: text === "" ? undefined : decodeJson(text), + }; + sent.push(entry); + return replyOf(route(entry)); + }); + }; + return (body: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = globalThis.fetch; + globalThis.fetch = Object.assign(stub, { preconnect: previous.preconnect }); + return previous; + }), + () => body, + (previous) => + Effect.sync(() => { + globalThis.fetch = previous; + }), + ); +}; + +const warehouseRoot = Command.make("supabase").pipe( + Command.withSubcommands(withApiCommands([], ["warehouse"])), + Command.withGlobalFlags(ROOT_GLOBAL_FLAGS), +); + +const tempRoot = useTempWorkdir("supabase-api-commands-int-"); + +/** What the real root needs around a leaf that is not part of the command tree under test. */ +const cliServices = (workdir: string, args: ReadonlyArray) => + Layer.mergeAll( + BunServices.layer, + CliOutput.layer(textCliOutputFormatter()), + Layer.succeed(ExperimentalFlag, false), + mockTelemetryRuntime({ configDir: workdir }), + mockRuntimeInfo({ cwd: workdir, homeDir: workdir }), + Stdio.layerTest({ args: Effect.succeed(args) }), + ); + +interface CliOpts { + readonly yes?: boolean; + readonly route: Route; + /** Whether an access token is configured; defaults to true. */ + readonly token?: boolean; + readonly root?: typeof warehouseRoot; + readonly analytics?: ReturnType; + /** + * The Output layer's resolved format. Defaults to `text` on a terminal and `json` otherwise, the + * way an agent run resolves it; a person piping the CLI gets `text`, so tests of that say so. + */ + readonly outputFormat?: OutputFormat; + /** Whether stdout is a terminal; defaults to a pipe. */ + readonly stdoutIsTty?: boolean; + /** Runs on an interactive terminal that answers the consent prompt with these responses. */ + readonly confirmResponses?: ReadonlyArray; +} + +/** + * Runs `argv` through the real parser and the real generated leaf; only `globalThis.fetch` is + * stubbed. `run` still needs the test runtime layers (see {@link setup}). + */ +const execute = (argv: ReadonlyArray, opts: CliOpts) => { + const args = [...argv, `--remote=${VALID_REF}`, ...(opts.yes === true ? ["--yes"] : [])]; + const sent: Array = []; + const seen: Array = []; + const run = withConfigEnv( + opts.token === false + ? { SUPABASE_ACCESS_TOKEN: "", SUPABASE_NO_KEYRING: "1", SUPABASE_HOME: tempRoot.current } + : { SUPABASE_ACCESS_TOKEN: VALID_TOKEN, SUPABASE_NO_KEYRING: "1" }, + Command.runWith(opts.root ?? warehouseRoot, { version: "0.0.0-test" })(args), + ).pipe(withApi(opts.route, sent, seen)); + return { args, sent, seen, run }; +}; + +const setup = (argv: ReadonlyArray, opts: CliOpts) => { + const interactive = opts.confirmResponses !== undefined; + const stdoutIsTty = opts.stdoutIsTty ?? interactive; + const format = opts.outputFormat ?? (stdoutIsTty ? "text" : "json"); + const out = mockOutput({ + format, + interactive: stdoutIsTty && format === "text", + ...(interactive ? { promptConfirmResponses: opts.confirmResponses } : {}), + }); + const { args, sent, seen, run } = execute(argv, opts); + const layer = Layer.mergeAll( + buildTestRuntime({ + out, + api: mockCommandPlatformApi({ response: { status: 200, body: {} } }), + ...(opts.analytics === undefined ? {} : { analytics: opts.analytics }), + cliSettings: mockCommandSettings({ workdir: tempRoot.current }), + tty: mockTty({ stdinIsTty: interactive, stdoutIsTty }), + stdin: mockStdin(false), + cliArgs: args, + }), + cliServices(tempRoot.current, args), + ); + return { args, out, sent, seen, run: run.pipe(Effect.provide(layer)) }; +}; + +const failureOf = (exit: Exit.Exit): unknown => + Exit.isFailure(exit) ? Exit.findErrorOption(exit).pipe(Option.getOrUndefined) : undefined; + +const bodiesOf = (sent: ReadonlyArray) => sent.map((request) => request.body); + +const driveClock = (fiber: Fiber.Fiber) => + Effect.raceFirst(Effect.forever(TestClock.adjust("2 seconds")), Fiber.await(fiber)); + +describe("generated warehouse commands", () => { + describe("incremental replication", () => { + it.effect.each(["add", "remove", "resync"])( + "%s sends one literal selector and preserves the immediate API result", + (action) => { + const type = + action === "resync" ? "warehouse_replication_resync" : "warehouse_replication_change"; + const attributes = + action === "resync" + ? { + pipeline_id: "101", + tables: [{ table_id: 42, new_state: { name: "queued" } }], + application_status: "reset", + } + : { + pipeline_id: "101", + application_status: "restart_requested", + tables: [], + changed: true, + }; + const body = { data: { type, id: "101", attributes } }; + const selector = { schema: "sales.*", table: 'Orders "2026"' }; + const { sent, out, run } = setup( + [ + "warehouse", + "replication", + action, + "--schema", + selector.schema, + "--table", + selector.table, + "--output-format", + "json", + ], + { yes: true, route: () => ({ status: 202, body }), outputFormat: "json" }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([ + { + method: "POST", + path: `/v2/projects/${VALID_REF}/warehouse/replication/${action}`, + search: "", + body: { data: { type, attributes: selector } }, + }, + ]); + expect(decodeJson(out.stdoutText)).toEqual(body); + }); + }, + ); + + it.effect.each(["add", "remove"])("%s leaves schema expansion to the server", (action) => { + const { sent, run } = setup(["warehouse", "replication", action, "--schema", "public"], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(bodiesOf(sent)).toEqual([ + { data: { type: "warehouse_replication_change", attributes: { schema: "public" } } }, + ]); + }); + }); + + it.effect.each(["--idempotency-key=key", "--expected-revision=1", "--wait", "--timeout=10s"])( + "rejects resync %s before a request", + (flag) => { + const { console, calls } = fakeConsole(); + const { sent, run } = setup( + ["warehouse", "replication", "resync", "--schema", "public", "--table", "orders", flag], + { yes: true, route: accepted }, + ); + return Effect.gen(function* () { + const exit = yield* run.pipe( + Effect.provideService(Console.Console, console), + Effect.exit, + ); + expect(Exit.isFailure(exit)).toBe(true); + expect(calls.join("\n")).toContain(flag.split("=")[0]); + expect(sent).toEqual([]); + }); + }, + ); + + it.effect( + "shows rebuild effects and local preview in resync help without server operation flags", + () => { + const { console, calls } = fakeConsole(); + const { sent, run } = setup(["warehouse", "replication", "resync", "--help"], { + route: accepted, + }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + const help = calls.join("\n"); + expect(help).toContain("deleted and rebuilt"); + expect(help).toContain("interrupts replication for other tables"); + expect(help).toContain("--schema"); + expect(help).toContain("--table"); + expect(help).toContain("--dry-run"); + for (const flag of ["--idempotency-key", "--expected-revision", "--wait", "--timeout"]) + expect(help).not.toContain(flag); + expect(sent).toEqual([]); + }); + }, + ); + + it.effect("does not replay a resync after an uncertain server failure", () => { + const { sent, run } = setup( + ["warehouse", "replication", "resync", "--schema", "public", "--table", "orders"], + { + yes: true, + route: () => ({ + status: 503, + body: { + error: { + code: "warehouse_setup_unavailable", + message: + "The table may have been reset. Inspect its state before repeating the request.", + }, + }, + }), + }, + ); + return Effect.gen(function* () { + const exit = yield* run.pipe(Effect.exit); + expect(Exit.isFailure(exit)).toBe(true); + expect(sent).toHaveLength(1); + }); + }); + }); + + describe("warehouse replication restart", () => { + const argv = ["warehouse", "replication", "restart"]; + const response = { + data: { + type: "warehouse_replication_restart", + id: "pipeline-1", + attributes: { + pipeline_id: "pipeline-1", + action: "start", + application_status: "accepted", + pipeline_status_before: "stopped", + }, + }, + }; + + it.effect("sends one restart and returns acceptance without polling old readiness", () => { + const { sent, out, run } = setup(argv, { + yes: true, + route: () => ({ status: 202, body: response }), + outputFormat: "json", + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([ + { + method: "POST", + path: `/v2/projects/${VALID_REF}/warehouse/replication/restart`, + search: "", + body: undefined, + }, + ]); + expect(decodeJson(out.stdoutText)).toEqual(response); + }); + }); + + it.effect("does not retry an uncertain restart", () => { + const { sent, run } = setup(argv, { + yes: true, + route: () => ({ + status: 503, + body: { message: "Inspect pipeline state before retrying." }, + }), + }); + return Effect.gen(function* () { + expect(Exit.isFailure(yield* Effect.exit(run))).toBe(true); + expect(sent).toHaveLength(1); + }); + }); + + it.effect("rejects --wait without sending a request", () => { + const { sent, run } = setup([...argv, "--wait"], { yes: true, route: accepted }); + return Effect.gen(function* () { + expect(Exit.isFailure(yield* Effect.exit(run))).toBe(true); + expect(sent).toEqual([]); + }); + }); + }); + + describe("consolidated warehouse status", () => { + const attributes = { + project_ref: VALID_REF, + enabled: true, + status: "degraded", + configured_readiness: "not_ready", + query_connectivity: "not_checked", + observed_at: "2026-11-17T10:00:00Z", + compute: { + status: "available", + region: "us-east-1", + routing_status: "ready", + unavailable_reason: null, + observed_at: "2026-11-17T10:00:00Z", + }, + lifecycle: null, + pipeline: null, + tables: { + status: "available", + unavailable_reason: null, + observed_at: "2026-11-17T10:00:00Z", + items: [], + progress: null, + }, + replication: { + status: "unavailable", + unavailable_reason: "observation_unavailable", + observed_at: null, + apply_lag: null, + }, + capabilities: { + context: true, + query_explain: false, + replication_add: false, + replication_remove: true, + replication_restart: true, + table_layout_read: true, + table_layout_update: false, + table_resync: false, + workload_metrics: true, + }, + } satisfies OperationOutput<"v2GetWarehouseStatus">["data"]["attributes"]; + const body = { + data: { + type: "warehouse_context", + id: VALID_REF, + attributes: { ...attributes, future_field: { retained: true } }, + }, + }; + + it.effect("preserves zero targets, capabilities and unavailable observations as JSON", () => { + const { out, sent, run } = setup(["warehouse", "status"], { route: ok(body) }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([ + { + method: "GET", + path: `/v2/projects/${VALID_REF}/warehouse/status`, + search: "", + body: undefined, + }, + ]); + expect(decodeJson(out.stdoutText)).toEqual(body); + }); + }); + + it.effect("escapes control characters in a non-JSON success body as text", () => { + const { out, run } = setup(["warehouse", "status"], { + route: ok("\u001b[31mred\nsecond\u0007 line\n"), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe("\\u001b[31mred\nsecond\\u0007 line\n"); + }); + }); + + it.effect("fails a non-JSON success body as json instead of writing it to stdout", () => { + const { out, run } = setup(["warehouse", "status", "--output-format", "json"], { + route: ok("\u001b[31mred\nsecond\n"), + outputFormat: "json", + }); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + + expect(failureOf(exit)).toBeInstanceOf(ApiCommandUnexpectedResponseError); + expect(out.stdoutText).toBe(""); + }); + }); + + it.effect("labels configured readiness and unavailable observations in terminal output", () => { + const { out, run } = setup(["warehouse", "status"], { route: ok(body), stdoutIsTty: true }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toMatch(/Enabled\s+yes/); + expect(out.stdoutText).toMatch(/Configured readiness\s+not_ready/); + expect(out.stdoutText).toMatch(/Query connectivity\s+not_checked/); + expect(out.stdoutText).toMatch(/Status\s+unavailable/); + expect(out.stdoutText).toMatch(/Unavailable reason\s+observation_unavailable/); + expect(out.stdoutText).toMatch(/Replication add\s+no/); + expect(out.stdoutText).toMatch(/Replication remove\s+yes/); + expect(out.stdoutText).toMatch(/Observed at\s+2026-11-17T10:00:00Z/); + }); + }); + + it.effect("shows runtime diagnostics beside last-known table errors and progress", () => { + const response = { + data: { + ...body.data, + attributes: { + ...attributes, + pipeline: { + id: "pipeline-1", + status: "failed", + diagnostic: { + code: "process_exited", + message: "The pipeline process exited unsuccessfully.", + exit_code: 1, + }, + observed_at: attributes.observed_at, + unavailable_reason: null, + }, + tables: { + ...attributes.tables, + progress: { + observation: "last_known", + selected: 1, + queued: 0, + copying_table: 0, + copied_table: 0, + following_wal: 0, + error: 1, + unknown: 0, + }, + items: [ + { + id: 16385, + schema: "public", + name: "orders", + replication_state: "error", + state_observation: "last_known", + sync_lag: null, + error: { + reason: "The table layout could not be applied.", + solution: "Inspect the saved layout.", + retry_policy: { policy: "manual_retry" }, + }, + }, + ], + }, + }, + }, + }; + const { out, run } = setup(["warehouse", "status"], { + route: ok(response), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toContain("process_exited"); + expect(out.stdoutText).toContain("The table layout could not be applied."); + expect(out.stdoutText).toContain("manual_retry"); + expect(out.stdoutText).toMatch(/Observation\s+last_known/); + expect(out.stdoutText).toMatch(/Selected\s+1/); + }); + }); + + it.effect("lists every table of a large warehouse in terminal output", () => { + const items = Array.from({ length: 12 }, (_, index) => ({ + id: 20000 + index, + schema: "public", + name: `table_${index}`, + error: null, + state_observation: "current" as const, + replication_state: index === 0 ? ("error" as const) : ("following_wal" as const), + sync_lag: + index === 1 + ? { + active: true, + feedback_age_ms: 5, + flush_lag_bytes: 2048, + flush_lag_ms: 120, + wal_status: "reserved" as const, + write_lag_ms: 80, + } + : null, + })) satisfies OperationOutput<"v2GetWarehouseStatus">["data"]["attributes"]["tables"]["items"]; + const { out, run } = setup(["warehouse", "status"], { + route: ok({ + data: { + ...body.data, + attributes: { ...attributes, tables: { ...attributes.tables, items } }, + }, + }), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toMatch( + /ID\s+20000\n\s+Schema\s+public\n\s+Name\s+table_0\n\s+Error\s+-\n\s+State observation\s+current\n\s+Replication state\s+error\n/, + ); + for (const item of items) expect(out.stdoutText).toContain(String(item.id)); + expect(out.stdoutText).not.toContain("omitted"); + }); + }); + }); + + describe("warehouse tables list", () => { + const tablesPath = `/v2/projects/${VALID_REF}/warehouse/tables`; + const table = (attributes: Readonly>) => ({ + type: "warehouse_table", + attributes: { schema: "public", ...attributes, observed_at: "2026-11-17T10:00:00Z" }, + }); + const body = { + data: [ + { + id: "16385", + ...table({ + name: "orders", + warehouse_name: '"public"."orders"', + status: "live", + replication_state: "following_wal", + lag_ms: 120, + replication_feedback: { + source: "pipeline_apply", + active: true, + wal_status: "reserved", + write_lag_ms: 80, + flush_lag_ms: 120, + flush_lag_bytes: 2048, + feedback_age_ms: 5, + }, + }), + }, + { + id: "16402", + ...table({ + name: "events", + warehouse_name: '"public"."events"', + status: "syncing", + replication_state: "copying_table", + lag_ms: null, + replication_feedback: null, + }), + }, + ], + }; + + it.effect("lists tables in one row each with replication feedback in a block below", () => { + const { out, sent, run } = setup(["warehouse", "tables", "list"], { + route: ok(body), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([{ method: "GET", path: tablesPath, search: "", body: undefined }]); + expect(out.stdoutText).toMatch(/16385\s.*orders.*live.*following_wal.*120/); + expect(out.stdoutText).toMatch(/16402\s.*events.*syncing.*copying_table/); + expect(out.stdoutText).toMatch(/Warehouse table 16385\n[\s\S]*Source\s+pipeline_apply/); + expect(out.stdoutText).toMatch(/Feedback age ms\s+5/); + expect(out.stdoutText).toMatch(/Warehouse table 16402\n\s+Replication feedback\s+-\n/); + }); + }); + + it.effect("passes the document, including replication feedback, through as JSON", () => { + const { out, run } = setup(["warehouse", "tables", "list"], { + route: ok(body), + }); + return Effect.gen(function* () { + yield* run; + expect(decodeJson(out.stdoutText)).toEqual(body); + }); + }); + }); + describe("warehouse inspect query-stats", () => { + const argv = ["warehouse", "inspect", "query-stats"]; + const attributes = { + project_ref: VALID_REF, + metric: "query_duration_p95", + unit: "seconds", + aggregation: "p95", + definition: + "Executor duration through terminal outcome, including assignment wait and streaming.", + requested: { metric: "query_duration_p95", start: 1795000000, end: 1795001800 }, + effective: { start: 1795000000, end: 1795001800, step: 60, rate_window_seconds: 300 }, + scrape_interval_seconds: 60, + last_sample_at: 1795001740, + availability: "partial", + series: [ + { + labels: { method: "DoGet", status: "ok" }, + points: [ + { timestamp: 1795001740, value: 0.2 }, + { timestamp: 1795001800, value: null }, + ], + coverage: { returned_points: 1, expected_points: 2 }, + }, + ], + } satisfies OperationOutput<"v2GetWarehouseQueryStats">["data"][number]["attributes"]; + const response = { + data: [ + { + type: "warehouse_metric", + id: "query_duration_p95", + attributes: { ...attributes, future_observation: { reason: null } }, + }, + ], + }; + + it.effect("shows the last 10 samples of a long series with an omission notice", () => { + const points = Array.from({ length: 12 }, (_, index) => ({ + timestamp: 1795001000 + index * 60, + value: 1001 + index, + })); + const [first] = response.data; + const [firstSeries] = attributes.series; + const { out, run } = setup(argv, { + route: ok({ + data: [ + { + ...first, + attributes: { + ...first?.attributes, + series: [ + { + ...firstSeries, + points, + coverage: { returned_points: 12, expected_points: 12 }, + }, + ], + }, + }, + ], + }), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toContain( + "Showing last 10 of 12 samples; 2 omitted; use --output-format json for all samples.", + ); + expect(out.stdoutText).not.toContain("1001"); + expect(out.stdoutText).not.toContain("1002"); + expect(out.stdoutText).toContain("1003"); + expect(out.stdoutText).toContain("1012"); + }); + }); + + it.effect("forwards a relative range and preserves the full JSON response", () => { + const { sent, out, run } = setup( + [ + ...argv, + "--since", + "30m", + "--attributes", + "query_rate,query_duration_p95", + "--interval", + "5m", + ], + { + route: ok(response), + }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + method: "GET", + path: `/v2/projects/${VALID_REF}/warehouse/query-stats`, + body: undefined, + }); + expect(Object.fromEntries(new URLSearchParams(sent[0]?.search))).toEqual({ + since: "30m", + attributes: "query_rate,query_duration_p95", + interval: "5m", + }); + expect(decodeJson(out.stdoutText)).toEqual(response); + }); + }); + + it.effect("forwards fixed timestamps unchanged and preserves null samples in JSON", () => { + const from = "2026-11-18T09:30:00+01:00"; + const to = "2026-11-18T10:00:00+01:00"; + const { sent, out, run } = setup([...argv, "--from", from, "--to", to], { + route: ok(response), + }); + return Effect.gen(function* () { + yield* run; + expect(Object.fromEntries(new URLSearchParams(sent[0]?.search))).toEqual({ from, to }); + expect(decodeJson(out.stdoutText)).toEqual(response); + }); + }); + + it.effect.each([ + { name: "terminal default", flags: [] }, + { name: "explicit text on a terminal", flags: ["--output-format", "text"] }, + ])("shows ranges, dimensions, and sample values with $name", ({ flags }) => { + const { out, run } = setup([...argv, ...flags], { + route: ok(response), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toContain("query_duration_p95"); + expect(out.stdoutText).toContain("partial"); + expect(out.stdoutText).toMatch(/Requested[\s\S]*1795000000/); + expect(out.stdoutText).toMatch(/Effective[\s\S]*Rate window seconds\s+300/); + expect(out.stdoutText).toMatch(/Method\s+DoGet/); + expect(out.stdoutText).toMatch(/1795001740\s*[|│]?\s*0\.2/); + expect(out.stdoutText).toMatch(/1795001800\s*[|│]?\s*-/); + expect(out.stdoutText.trimStart().startsWith("{")).toBe(false); + }); + }); + }); + describe("warehouse inspect capacity", () => { + const argv = ["warehouse", "inspect", "capacity"]; + const attributes = { + project_ref: VALID_REF, + metric: "activation_duration_p95", + unit: "seconds", + aggregation: "p95", + definition: "Activation duration by kind and result.", + requested: { metric: "activation_duration_p95", start: 1795000000, end: 1795001800 }, + effective: { start: 1795000000, end: 1795001800, step: 60, rate_window_seconds: 300 }, + scrape_interval_seconds: 60, + last_sample_at: 1795001740, + availability: "partial", + series: [ + { + labels: { kind: "cold", result: "success" }, + points: [ + { timestamp: 1795001740, value: 0.2 }, + { timestamp: 1795001800, value: null }, + ], + coverage: { returned_points: 1, expected_points: 2 }, + }, + { + labels: { kind: "warm", result: "success" }, + points: [{ timestamp: 1795001800, value: 0.01 }], + coverage: { returned_points: 1, expected_points: 2 }, + }, + ], + } satisfies OperationOutput<"v2GetWarehouseCapacity">["data"][number]["attributes"]; + const response = { + data: [ + { + type: "warehouse_metric", + id: "activation_duration_p95", + attributes: { ...attributes, future_observation: { reason: null } }, + }, + ], + }; + + it.effect("leaves default selection to the API and preserves all JSON bytes when piped", () => { + const rawResponse = `\n${encodeJson(response).replace('"value":0.2', '"value":0.20')}\n`; + const { sent, out, run } = setup([...argv, "--since", "30m", "--interval", "5m"], { + route: ok(rawResponse), + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + method: "GET", + path: `/v2/projects/${VALID_REF}/warehouse/capacity`, + body: undefined, + }); + expect(Object.fromEntries(new URLSearchParams(sent[0]?.search))).toEqual({ + since: "30m", + interval: "5m", + }); + expect(out.stdoutText).toBe(rawResponse); + }); + }); + + it.effect( + "renders both capacity series, their dimensions, unit, availability, and null sample", + () => { + const { out, run } = setup(argv, { route: ok(response), stdoutIsTty: true }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toMatch(/Kind\s+cold/); + expect(out.stdoutText).toMatch(/Kind\s+warm/); + expect(out.stdoutText.match(/Result\s+success/g)).toHaveLength(2); + expect(out.stdoutText).toMatch(/\bUNIT\b[\s\S]*\bseconds\b/); + expect(out.stdoutText).toMatch(/\bAVAILABILITY\b[\s\S]*\bpartial\b/); + expect(out.stdoutText).toMatch(/1795001800\s*[|│]?\s*-/); + expect(out.stdoutText).toMatch(/1795001800\s*[|│]?\s*0\.01/); + }); + }, + ); + + it.effect( + "forwards fixed timestamps and metric selection and keeps all dimensions in JSON", + () => { + const from = "2026-11-18T09:30:00+01:00"; + const to = "2026-11-18T10:00:00+01:00"; + const selection = "activation_duration_p95,worker_admission_occupied"; + const { sent, out, run } = setup( + [...argv, "--from", from, "--to", to, "--attributes", selection], + { route: ok(response) }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toHaveLength(1); + expect(Object.fromEntries(new URLSearchParams(sent[0]?.search))).toEqual({ + from, + to, + attributes: selection, + }); + expect(decodeJson(out.stdoutText)).toEqual(response); + }); + }, + ); + }); + describe("warehouse tables get", () => { + const tablePath = `/v2/projects/${VALID_REF}/warehouse/tables/16385`; + const body = { + data: { + id: "16385", + type: "warehouse_table", + attributes: { + schema: "public", + name: "orders", + warehouse_name: '"public"."orders"', + status: "live", + replication_state: "following_wal", + lag_ms: 120, + observed_at: "2026-11-17T10:00:00Z", + replication_feedback: { + source: "pipeline_apply", + active: true, + wal_status: "reserved", + write_lag_ms: 80, + flush_lag_ms: 120, + flush_lag_bytes: 2048, + feedback_age_ms: 5, + }, + }, + }, + }; + + it.effect( + "requests the table by OID and renders its attributes and replication feedback", + () => { + const { out, sent, run } = setup(["warehouse", "tables", "get", "16385"], { + route: ok(body), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([{ method: "GET", path: tablePath, search: "", body: undefined }]); + expect(out.stdoutText).toMatch(/Warehouse table/); + expect(out.stdoutText).toMatch(/Name\s+orders/); + expect(out.stdoutText).toMatch(/Replication state\s+following_wal/); + expect(out.stdoutText).toMatch(/Replication feedback\n\s+Source\s+pipeline_apply/); + expect(out.stdoutText).toMatch(/Flush lag bytes\s+2048/); + }); + }, + ); + + it.effect.each(["", ".."])( + "rejects the table id %j as a usage error and sends nothing", + (value) => { + const { sent, run } = setup(["warehouse", "tables", "get", value], { route: ok(body) }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + expect(failure).toMatchObject({ message: ' must not be empty, "." or "..".' }); + expect(sent).toEqual([]); + }); + }, + ); + }); + describe("warehouse tables layout get", () => { + const layoutPath = `/v2/projects/${VALID_REF}/warehouse/tables/16385/layout`; + const body = { + data: { + id: "16385", + type: "warehouse_table_layout", + attributes: { + schema: "public", + name: "events", + desired: { + sort_by: null, + partition_by: [{ column: "account_id", transform: { kind: "bucket", count: 16 } }], + }, + observation_status: "observed", + observed: { + sort_by: [{ expression: '"created_at"', direction: "DESC", nulls: "NULLS_LAST" }], + partition_by: [{ column: "account_id", transform: "bucket(16)" }], + observed_at: "2026-11-18T09:30:00.123456Z", + }, + }, + }, + }; + + it.effect("renders unmanaged desired sorting beside the observed catalog layout", () => { + const { out, sent, run } = setup(["warehouse", "tables", "layout", "get", "16385"], { + route: ok(body), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([{ method: "GET", path: layoutPath, search: "", body: undefined }]); + expect(out.stdoutText).toMatch(/^Warehouse table layout\n/); + expect(out.stdoutText).toMatch(/Desired\n\s+Sort by\s+-\n/); + expect(out.stdoutText).toMatch(/Column\s+account_id[\s\S]*Kind\s+bucket[\s\S]*Count\s+16/); + expect(out.stdoutText).toMatch(/Observation status\s+observed/); + expect(out.stdoutText).toMatch(/account_id \| bucket\(16\)/); + expect(out.stdoutText).toMatch(/Observed at\s+2026-11-18T09:30:00\.123456Z/); + }); + }); + }); + describe("warehouse tables layout update", () => { + const argv = ["warehouse", "tables", "layout", "update", "16385"]; + const layoutPath = `/v2/projects/${VALID_REF}/warehouse/tables/16385/layout`; + const body = { + data: { + type: "warehouse_table_layout", + attributes: { sort_by: { kind: "primary_key" }, partition_by: [] }, + }, + }; + + it.effect.each([ + { flags: [], reset: {} }, + { flags: ["--reset-table"], reset: { reset_table: true } }, + { flags: ["--reset-table", "false"], reset: { reset_table: false } }, + ])( + "sends a layout file with reset option $flags and prints the full API response", + ({ flags, reset }) => { + const response = { + data: { + type: "warehouse_table_layout", + id: "16385", + attributes: { + pipeline_id: "pipeline-1", + schema: "public", + name: "events", + desired: body.data.attributes, + application_status: "waiting_for_start", + reset_table: reset.reset_table ?? false, + observation_status: "not_requested", + observed: null, + future_state: { reason: null }, + }, + }, + }; + const file = `${tempRoot.current}/layout.json`; + const { sent, out, run } = setup([...argv, "--file", file, ...flags], { + yes: true, + route: () => ({ status: 202, body: response }), + }); + return Effect.gen(function* () { + yield* (yield* FileSystem.FileSystem).writeFileString(file, encodeJson(body)); + yield* run; + expect(sent).toEqual([ + { + method: "PATCH", + path: layoutPath, + search: "", + body: { data: { ...body.data, attributes: { ...body.data.attributes, ...reset } } }, + }, + ]); + expect(decodeJson(out.stdoutText)).toEqual(response); + }).pipe(Effect.provide(BunServices.layer)); + }, + ); + + it.effect( + "previews unmanaged sorting while preserving omitted settings without sending a request", + () => { + const clear = { data: { type: "warehouse_table_layout", attributes: { sort_by: null } } }; + const { sent, out, run } = setup([...argv, "--body", encodeJson(clear), "--dry-run"], { + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([]); + expect(decodeJson(out.stdoutText)).toEqual({ + method: "PATCH", + path: layoutPath, + query: {}, + headers: {}, + body: clear, + }); + }); + }, + ); + + it.effect("sends the JSON values of --sort-by and --partition-by in the envelope", () => { + const { sent, run } = setup( + [...argv, "--sort-by", '{"kind":"none"}', "--partition-by", "[]"], + { yes: true, route: accepted }, + ); + return Effect.gen(function* () { + yield* run; + expect(bodiesOf(sent)).toEqual([ + { + data: { + type: "warehouse_table_layout", + attributes: { sort_by: { kind: "none" }, partition_by: [] }, + }, + }, + ]); + }); + }); + + it.effect("accepts every displayed layout JSON example through the parser", () => { + const examples = entryOf("warehouse tables layout update").examples ?? []; + const expected = [ + { + partition_by: [{ column: "event_at", transform: { kind: "day" } }], + sort_by: { + kind: "columns", + columns: [ + { name: "tenant_id", direction: "asc" }, + { name: "event_at", direction: "desc", nulls: "last" }, + ], + }, + }, + { partition_by: [{ column: "tenant_id", transform: { kind: "bucket", count: 8 } }] }, + { partition_by: [], sort_by: { kind: "none" } }, + { partition_by: null, sort_by: null }, + ]; + expect(examples).toHaveLength(expected.length); + return Effect.gen(function* () { + for (const [index, example] of examples.entries()) { + const args = + example.command + .replace(/^supabase /, "") + .replace("", "16385") + .match(/'[^']*'|\S+/g) + ?.map((token) => token.replace(/^'|'$/g, "")) ?? []; + const preview = args.includes("--dry-run"); + const { sent, out, run } = setup(args, { yes: true, route: accepted }); + yield* run; + const body = preview + ? (yield* Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ body: Schema.Unknown })), + )(out.stdoutText)).body + : sent[0]?.body; + expect(body).toEqual({ + data: { type: "warehouse_table_layout", attributes: expected[index] }, + }); + expect(sent).toHaveLength(preview ? 0 : 1); + } + }); + }); + + it.effect("keeps a JSON null from --sort-by as unmanaged sorting", () => { + const { sent, out, run } = setup([...argv, "--sort-by", "null", "--dry-run"], { + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([]); + expect(decodeJson(out.stdoutText)).toMatchObject({ + body: { data: { attributes: { sort_by: null } } }, + }); + }); + }); + + it.effect("lets a JSON flag replace only its own field of --body", () => { + const { sent, run } = setup([...argv, "--body", encodeJson(body), "--sort-by", "null"], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(bodiesOf(sent)).toEqual([ + { + data: { + type: "warehouse_table_layout", + attributes: { sort_by: null, partition_by: [] }, + }, + }, + ]); + }); + }); + + it.effect("rejects --sort-by text that is not JSON, naming the flag, and sends nothing", () => { + const { sent, run } = setup([...argv, "--sort-by", "{"], { yes: true, route: accepted }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + expect(failure).toMatchObject({ message: "--sort-by is not valid JSON." }); + expect(sent).toEqual([]); + }); + }); + + it.effect("rejects a --sort-by value outside the field schema before consent", () => { + const { sent, run } = setup([...argv, "--sort-by", '{"kind":"bogus"}'], { + route: accepted, + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf(ApiCommandUsageError); + expect(sent).toEqual([]); + }); + }); + + it.effect.each([ + { flags: ["--reset-table"] }, + { flags: ["--reset-table", "--dry-run"] }, + { flags: [] }, + ])( + "rejects a patch with neither --sort-by nor --partition-by ($flags) and sends nothing", + ({ flags }) => { + const { sent, run } = setup([...argv, ...flags], { yes: true, route: accepted }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + expect(failure).toMatchObject({ + message: "Pass at least one of --sort-by, --partition-by", + suggestion: "Pass one of the flags, or include one of the fields in --body/--file.", + }); + expect(sent).toEqual([]); + }); + }, + ); + + it.effect.each([ + { + name: "a table id that is not a positive integer", + argv: ["warehouse", "tables", "layout", "update", "abc", "--sort-by", "null"], + named: "", + raw: '["table_id"]', + }, + { + name: "a --partition-by value outside the field schema", + argv: [...argv, "--partition-by", '{"column":1}'], + named: "--partition-by", + raw: '["partition_by"]', + }, + ])("names the flag or argument for $name, once", ({ argv: invalid, named, raw }) => { + const { sent, run } = setup(invalid, { yes: true, route: accepted }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + const { message } = failure as ApiCommandUsageError; + expect(message).toContain(`${named}: `); + expect(message.split(named).length - 1).toBe(1); + expect(message).not.toContain(raw); + expect(sent).toEqual([]); + }); + }); + + it.effect("rejects a non-boolean reset before making a hosted request", () => { + const reset = { + data: { type: "warehouse_table_layout", attributes: { reset_table: "true" } }, + }; + const { sent, run } = setup([...argv, "--body", encodeJson(reset)], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf(ApiCommandUsageError); + expect(sent).toEqual([]); + }); + }); + }); + describe("warehouse connection", () => { + const connectionPath = `/v2/projects/${VALID_REF}/warehouse/connection`; + const host = `${VALID_REF}.warehouse.example.invalid`; + const connection = (attributes: Readonly>) => ({ + data: { + type: "warehouse_connection", + id: VALID_REF, + attributes: { + project_ref: VALID_REF, + observed_at: "2026-11-17T10:00:00Z", + protocol: "arrow_flight_sql", + tls_required: true, + authentication: { + method: "database_username_password", + credential_source: "source_project_database", + default_username: "postgres", + password_guidance: + "Use the same password as this role in the source Supabase database. For postgres, use the project's database password.", + required_membership: "supabase_warehouse_reader", + }, + access_mode: "read_only", + query_connectivity: "not_checked", + ...attributes, + }, + }, + }); + + it.effect("prints the endpoint and source database login guidance from a single read", () => { + const body = connection({ + status: "available", + unavailable_reason: null, + endpoint: `grpc+tls://${host}:443`, + host, + port: 443, + region: "eu-central-1", + routing_status: "ready", + }); + const { out, sent, run } = setup(["warehouse", "connection"], { + route: ok(body), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([ + { method: "GET", path: connectionPath, search: "", body: undefined }, + ]); + expect(out.stdoutText).toMatch(/^Warehouse connection$/m); + expect(out.stdoutText).toMatch(/Status\s+available/); + expect(out.stdoutText).toContain(`grpc+tls://${host}:443`); + expect(out.stdoutText).toMatch(/TLS required\s+yes/); + expect(out.stdoutText).toMatch(/Default username\s+postgres/); + expect(out.stdoutText).toMatch(/Password guidance\s+Use the same password as this role/); + expect(out.stdoutText).toMatch(/Required membership\s+supabase_warehouse_reader/); + expect(out.stdoutText).toMatch(/Query connectivity\s+not_checked/); + }); + }); + + it.effect("shows no connection string for an unconfigured Warehouse", () => { + const body = connection({ + status: "not_configured", + unavailable_reason: null, + endpoint: null, + host: null, + port: null, + region: null, + routing_status: null, + }); + const { out, run } = setup(["warehouse", "connection"], { + route: ok(body), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toMatch(/Status\s+not_configured/); + expect(out.stdoutText).toMatch(/Endpoint\s+-$/m); + expect(out.stdoutText).toMatch(/Host\s+-$/m); + expect(out.stdoutText).not.toMatch(/grpc\+tls|flightsql:/); + }); + }); + }); + describe("warehouse disable", () => { + const operationId = "7579647f-2cdc-466c-982e-425958a2f985"; + const disablePath = `/v2/projects/${VALID_REF}/warehouse`; + const teardownPath = `${disablePath}/teardowns/current`; + const teardown = (lifecycleStatus: string, deleteData = false) => ({ + data: { + type: "warehouse_teardown", + id: operationId, + attributes: { + lifecycle_status: lifecycleStatus, + delete_data: deleteData, + updated_at: "2026-11-17T10:00:00Z", + cleanup_error: null, + unknown_observation: null, + }, + }, + }); + + it.effect.each([false, true])( + "keeps retention as the default and sends explicit deletion=%s", + (deleteData) => { + const body = teardown("disabling", deleteData); + const { sent, out, run } = setup( + ["warehouse", "disable", ...(deleteData ? ["--delete-data"] : [])], + { + yes: true, + route: () => ({ status: 202, body }), + }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toStrictEqual([ + { + method: "DELETE", + path: disablePath, + search: deleteData ? "delete_data=true" : "", + body: undefined, + }, + ]); + expect(out.stdoutText).toBe(encodeJson(body)); + }); + }, + ); + + it.effect("previews permanent deletion without consent or a command request", () => { + const { sent, out, run } = setup(["warehouse", "disable", "--delete-data", "--dry-run"], { + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([]); + expect(decodeJson(out.stdoutText)).toMatchObject({ + method: "DELETE", + path: disablePath, + query: { delete_data: true }, + }); + }); + }); + + it.effect("waits on the accepted cleanup identity and prints the accepted resource", () => { + const accepted = teardown("disabling"); + const { sent, out, run } = setup(["warehouse", "disable", "--wait"], { + yes: true, + route: (request) => + request.method === "DELETE" + ? { status: 202, body: accepted } + : { status: 200, body: teardown("disabled") }, + }); + return Effect.gen(function* () { + yield* run; + expect(sent.map(({ method, path, search }) => ({ method, path, search }))).toStrictEqual([ + { method: "DELETE", path: disablePath, search: "" }, + { method: "GET", path: teardownPath, search: `operation_id=${operationId}` }, + ]); + expect(out.stdoutText).toBe(encodeJson(accepted)); + }); + }); + + it.effect.each([undefined, operationId])( + "reads cleanup without mutation consent using optional operation identity %s", + (requestedId) => { + const body = teardown("disabling"); + const { sent, out, run } = setup( + [ + "warehouse", + "teardowns", + "get", + ...(requestedId === undefined ? [] : ["--operation-id", requestedId]), + ], + { route: () => ({ status: 200, body }) }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toStrictEqual([ + { + method: "GET", + path: teardownPath, + search: requestedId === undefined ? "" : `operation_id=${requestedId}`, + body: undefined, + }, + ]); + expect(out.stdoutText).toBe(encodeJson(body)); + }); + }, + ); + + it.effect("waits for the current cleanup without an operation identity", () => { + const final = teardown("disabled"); + let reads = 0; + const { sent, out, run } = setup(["warehouse", "teardowns", "get", "--wait"], { + route: () => ({ + status: 200, + body: reads++ === 0 ? teardown("disabling") : final, + }), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + expect(sent.map(({ method, path, search }) => ({ method, path, search }))).toStrictEqual([ + { method: "GET", path: teardownPath, search: "" }, + { method: "GET", path: teardownPath, search: "" }, + ]); + expect(out.stdoutText).toBe(encodeJson(final)); + }); + }); + + it.effect("preserves partial cleanup failure and the command for inspecting it", () => { + const failed = teardown("deletion_failed", true); + const { run } = setup(["warehouse", "disable", "--delete-data", "--wait"], { + yes: true, + route: (request) => ({ status: request.method === "DELETE" ? 202 : 200, body: failed }), + }); + return Effect.gen(function* () { + const error = yield* run.pipe(Effect.flip); + expect(error).toBeInstanceOf(ApiCommandOperationFailedError); + expect(error).toMatchObject({ + status: "deletion_failed", + suggestion: expect.stringContaining(`--operation-id ${operationId}`), + }); + }); + }); + + it.effect("reports the last cleanup state on a bounded timeout", () => { + const { run, sent } = setup(["warehouse", "disable", "--wait", "--timeout", "10s"], { + yes: true, + route: (request) => ({ + status: request.method === "DELETE" ? 202 : 200, + body: teardown("disabling"), + }), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const error = yield* Fiber.join(fiber); + expect(error).toBeInstanceOf(ApiCommandWaitTimeoutError); + expect(error).toMatchObject({ + message: expect.stringContaining("Last observed status: disabling"), + suggestion: expect.stringContaining(`--operation-id ${operationId}`), + }); + expect(sent.filter((request) => request.method === "DELETE")).toHaveLength(1); + }); + }); + }); + + describe("warehouse enable request", () => { + it.effect("sends only the schema when no other flag is given", () => { + const { sent, run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(sent.map((request) => `${request.method} ${request.path}`)).toEqual([ + `POST ${ENABLE_PATH}`, + ]); + expect(bodiesOf(sent)).toEqual([ + { data: { type: "warehouse_setup", attributes: { schema: "public" } } }, + ]); + }); + }); + + it.effect("maps a repeated --table to tables and keeps a false boolean", () => { + const { sent, run } = setup( + [ + "warehouse", + "enable", + "--schema", + "public", + "--table", + "a", + "--table", + "b", + "--install-fdw", + "false", + ], + { yes: true, route: accepted }, + ); + return Effect.gen(function* () { + yield* run; + expect(bodiesOf(sent)).toEqual([ + { + data: { + type: "warehouse_setup", + attributes: { schema: "public", tables: ["a", "b"], install_fdw: false }, + }, + }, + ]); + }); + }); + + it.effect("lets a flag win only at its own pointer when merged into --body", () => { + const body = encodeJson({ + data: { + type: "warehouse_setup", + attributes: { schema: "from-body", install_fdw: true, tables: ["t1"] }, + }, + }); + const { sent, run } = setup( + ["warehouse", "enable", "--body", body, "--schema", "from-flag"], + { + yes: true, + route: accepted, + }, + ); + return Effect.gen(function* () { + yield* run; + expect(bodiesOf(sent)).toEqual([ + { + data: { + type: "warehouse_setup", + attributes: { schema: "from-flag", install_fdw: true, tables: ["t1"] }, + }, + }, + ]); + }); + }); + + it.effect("reads the whole body from --file", () => { + const { sent, run } = setup( + ["warehouse", "enable", "--file", `${tempRoot.current}/enable.json`], + { yes: true, route: accepted }, + ); + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.writeFileString( + path.join(tempRoot.current, "enable.json"), + encodeJson({ data: { type: "warehouse_setup", attributes: { schema: "file" } } }), + ); + yield* run; + expect(bodiesOf(sent)).toEqual([ + { data: { type: "warehouse_setup", attributes: { schema: "file" } } }, + ]); + }).pipe(Effect.provide(BunServices.layer)); + }); + + it.effect("rejects an unknown key in --body as a usage error and sends nothing", () => { + const body = encodeJson({ + data: { type: "warehouse_setup", attributes: { schema: "public", bogus: 1 } }, + }); + const { sent, run } = setup(["warehouse", "enable", "--body", body], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf(ApiCommandUsageError); + expect(sent).toEqual([]); + }); + }); + + it.effect.each([ + { + name: "ref", + body: { + ref: "zyxwvutsrqponmlkjihg", + data: { type: "warehouse_setup", attributes: { schema: "public" } }, + }, + }, + { name: "bogus", body: { bogus: 1 } }, + ])( + "rejects the top-level $name key in --body, naming it, and sends nothing", + ({ name, body }) => { + const { sent, run } = setup(["warehouse", "enable", "--body", encodeJson(body)], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + expect(failure).toMatchObject({ message: expect.stringContaining(`"${name}"`) }); + expect(sent).toEqual([]); + }); + }, + ); + + it.effect("names the missing --schema flag and sends nothing", () => { + const { sent, run } = setup(["warehouse", "enable", "--install-fdw", "true"], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandUsageError); + expect(failure).toMatchObject({ + message: "Missing required flag --schema", + suggestion: "Pass the flag, or include the field in --body/--file.", + }); + expect(sent).toEqual([]); + }); + }); + }); + + describe("consent and dry run", () => { + it.effect.each([ + { + command: ["enable"], + path: ENABLE_PATH, + type: "warehouse_setup", + attributes: { schema: "public", tables: ["a"] }, + }, + { + command: ["replication", "resync"], + path: `/v2/projects/${VALID_REF}/warehouse/replication/resync`, + type: "warehouse_replication_resync", + attributes: { schema: "public", table: "a" }, + }, + ])( + "$command prints exactly the request preview and sends nothing under --dry-run", + ({ command, path, type, attributes }) => { + const { out, sent, seen, run } = setup( + ["warehouse", ...command, "--schema", "public", "--table", "a", "--dry-run"], + { token: false, route: accepted }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([]); + expect(seen).toEqual([]); + expect(decodeJson(out.stdoutText)).toEqual({ + method: "POST", + path, + query: {}, + headers: {}, + body: { data: { type, attributes } }, + }); + }); + }, + ); + + it.effect( + "previews a mutation for a literal --remote ref with no access token, no request and no cache write", + () => { + const { out, seen, run } = setup( + ["warehouse", "enable", "--schema", "public", "--dry-run"], + { token: false, route: accepted }, + ); + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* run; + + expect(decodeJson(out.stdoutText)).toMatchObject({ method: "POST", path: ENABLE_PATH }); + expect(seen).toEqual([]); + expect( + yield* fs.exists( + path.join(tempRoot.current, "supabase", ".temp", "linked-project.json"), + ), + ).toBe(false); + }).pipe(Effect.provide(BunServices.layer)); + }, + ); + + it.effect("fails a send with no access token before any request", () => { + const { seen, run } = setup(["warehouse", "enable", "--schema", "public"], { + token: false, + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + + expect(Exit.isFailure(exit) && Cause.pretty(exit.cause)).toContain( + "AccessTokenRequiredError", + ); + expect(seen).toEqual([]); + }); + }); + + it.effect("masks a sensitive field supplied through --body in the preview", () => + Effect.gen(function* () { + const sensitiveEntry: ApiCommandEntry = { + ...enable, + flags: enable.flags.map((flag) => + flag.name === "schema" ? { ...flag, sensitive: true } : flag, + ), + }; + const body = Option.some({ + data: { type: "warehouse_setup", attributes: { schema: "top-secret" } }, + }); + const input = yield* assembleInput(sensitiveEntry, VALID_REF, {}, body); + const decoded = yield* decodeInput(sensitiveEntry, input); + + const preview = previewRequest(sensitiveEntry, decoded); + + expect(encodeJson(preview)).not.toContain("top-secret"); + expect(preview.body).toEqual({ + data: { type: "warehouse_setup", attributes: { schema: "[redacted]" } }, + }); + }), + ); + + it.effect("previews a read with a null body", () => { + const { out, run } = setup(["warehouse", "status", "--dry-run"], { + route: ok({}), + }); + return Effect.gen(function* () { + yield* run; + expect(decodeJson(out.stdoutText)).toEqual({ + method: "GET", + path: STATUS_PATH, + query: {}, + headers: {}, + body: null, + }); + }); + }); + + it.effect.each([ + { name: "a send", argv: ["warehouse", "enable", "--schema", "public"] }, + { name: "a dry run", argv: ["warehouse", "enable", "--schema", "public", "--dry-run"] }, + { name: "a read", argv: ["warehouse", "status"] }, + ])("rejects -o json for $name as a usage error and sends nothing", ({ argv }) => { + const { sent, run } = setup([...argv, "-o", "json"], { yes: true, route: accepted }); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + expect(failureOf(exit)).toEqual( + new ApiCommandUsageError({ + message: unsupportedOutputFlagMessage(argv.slice(0, 2).join(" ")), + }), + ); + expect(sent).toEqual([]); + }); + }); + + it.effect("asks for consent before it needs an access token", () => { + const { seen, run } = setup(["warehouse", "enable", "--schema", "public"], { + token: false, + route: accepted, + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf( + HostedMutationConsentRequiredError, + ); + expect(seen).toEqual([]); + }); + }); + + it.effect("refuses a non-interactive mutation without --yes", () => { + const { sent, run } = setup(["warehouse", "enable", "--schema", "public"], { + route: accepted, + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf( + HostedMutationConsentRequiredError, + ); + expect(sent).toEqual([]); + }); + }); + }); + + describe("responses", () => { + it.effect( + "writes a JSON response with unknown fields unchanged and without a target key", + () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: accepted, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(encodeJson(ACCEPTED)); + expect(out.stdoutText).not.toContain('"target"'); + }); + }, + ); + + it.effect.each([ + { + name: "a v1 body with a top-level message and code", + reply: { status: 422, body: { message: "selection rejected", code: "selection_conflict" } }, + expected: { status: 422, message: "selection rejected (HTTP 422)" }, + }, + { + name: "a v2 body nesting the error, with its description", + reply: { + status: 409, + body: { + error: { code: "conflict", message: "Setup exists", description: "Run status." }, + }, + }, + expected: { status: 409, message: "Setup exists: Run status. (HTTP 409)" }, + }, + { + name: "a v2 401 body", + reply: { + status: 401, + body: { error: { code: "unauthenticated", message: "Invalid access token" } }, + }, + expected: { + status: 401, + message: "Invalid access token (HTTP 401)", + }, + }, + { + name: "a body that carries no message", + reply: { status: 503, body: "bad gateway" }, + expected: { status: 503, message: "Unexpected status 503" }, + }, + ])("fails with the parsed API error for $name", ({ reply, expected }) => { + const { run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => reply, + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandStatusError); + expect(failure).toMatchObject(expected); + }); + }); + + it.effect("fails with a network error when the success body cannot be read", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ status: 202, unreadable: true }), + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(HttpClientError.isHttpClientError(failure)).toBe(true); + expect(out.stdoutText).toBe(""); + }); + }); + + it.effect.each([ + { + name: "a 401", + reply: { status: 401, body: { message: "Invalid access token" } }, + hint: "Run `supabase login`", + }, + { + name: "a 403", + reply: { status: 403, body: { message: "Forbidden" } }, + hint: "Your token needs the permissions:", + }, + { + name: "a 401 that carries its own hint", + reply: { + status: 401, + body: { message: "Expired", hint: "Rotate the token in the dashboard." }, + }, + hint: "Rotate the token in the dashboard.", + }, + { + name: "a 401 whose hint is empty", + reply: { status: 401, body: { message: "Expired", hint: "" } }, + hint: "Run `supabase login`", + }, + { + name: "a 403 whose hint is only whitespace", + reply: { status: 403, body: { message: "Forbidden", hint: " \n\t" } }, + hint: "Your token needs the permissions:", + }, + ])("suggests the fix for $name", ({ reply, hint }) => { + const { run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => reply, + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toBeInstanceOf(ApiCommandStatusError); + expect(failure).toMatchObject({ suggestion: expect.stringContaining(hint) }); + }); + }); + + it.effect("neutralizes terminal control characters in an API-provided suggestion", () => { + const { run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ + status: 401, + body: { message: "Expired", hint: "Rotate\u202e the\u009b token\u2028" }, + }), + }); + return Effect.gen(function* () { + const failure = failureOf(yield* Effect.exit(run)); + expect(failure).toMatchObject({ suggestion: "Rotate the token" }); + }); + }); + + it.effect("reports a plan-gated 403 with its entitlement in the error and telemetry", () => { + const analytics = mockAnalytics(); + const planGate = { + error: { + code: "entitlement_required", + feature: "warehouse", + upgrade_url: "https://supabase.com/dashboard/org/acme/billing", + }, + }; + const { run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ status: 403, body: planGate }), + analytics, + }); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + expect(Exit.isFailure(exit) && normalizeCause(exit.cause)).toMatchObject({ + code: "ApiCommandStatusError", + entitlement: { + feature: "warehouse", + upgrade_url: "https://supabase.com/dashboard/org/acme/billing", + }, + }); + expect(analytics.captured.find((c) => c.event === EventUpgradeSuggested)).toMatchObject({ + properties: { feature_key: "warehouse", org_slug: "acme" }, + }); + }); + }); + + it.effect.each([ + { name: "a 403 without the plan-gate code", status: 403, body: { message: "Forbidden" } }, + { + name: "a 5xx carrying a plan-gate body", + status: 503, + body: { + error: { + code: "entitlement_required", + feature: "warehouse", + upgrade_url: "https://supabase.com/dashboard/org/acme/billing", + }, + }, + }, + ])("reports no entitlement for $name", ({ status, body }) => { + const analytics = mockAnalytics(); + const { run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ status, body }), + analytics, + }); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + expect(Exit.isFailure(exit) && normalizeCause(exit.cause)).not.toHaveProperty( + "entitlement", + ); + expect(analytics.captured.some((c) => c.event === EventUpgradeSuggested)).toBe(false); + }); + }); + }); + + describe("permissions", () => { + const tree = commandTreeFor({ apiFeatures: ["warehouse"] }); + const operationsOf = (path: string) => { + const command = tree.get(path)?.command; + const permissions = Option.getOrUndefined( + command === undefined ? Option.none() : readPermissions(command), + ); + return permissions?.status === "mapped" ? permissions.operations : []; + }; + const sendsRequests = (entry: { + readonly when?: ReadonlyArray<{ flag?: string; is?: boolean }>; + }) => + entry.when?.some((condition) => condition.flag === "dry-run" && condition.is === false) === + true; + + it.each(["warehouse enable", "warehouse disable", "warehouse tables layout update"])( + "%s needs no API operation beyond target resolution on a dry run", + (path) => { + const operations = operationsOf(path); + expect(operations.some((entry) => entry.source === undefined)).toBe(true); + const unconditional = operations.filter((entry) => !sendsRequests(entry)); + expect(unconditional.length).toBeGreaterThan(0); + expect( + unconditional.every( + (entry) => entry.source === "project-ref" || entry.source === "branch-resolution", + ), + ).toBe(true); + }, + ); + + it("requires the wait poll operation only for a request that is sent", () => { + const poll = operationsOf("warehouse enable").find((entry) => + entry.when?.some((condition) => condition.flag === "wait"), + ); + expect(poll).toBeDefined(); + expect(poll !== undefined && sendsRequests(poll)).toBe(true); + }); + + it.effect("renders the cache and poll permissions in help only for a sent request", () => { + const { console, calls } = fakeConsole(); + const { run } = setup(["warehouse", "enable", "--help"], { route: accepted }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + const lines = calls.join("\n").split("\n"); + const section = lines.slice(lines.indexOf("PERMISSIONS")).join("\n"); + expect(section).toContain( + "Optional, without --dry-run (command still runs without these):\n project_admin_read", + ); + expect(section).toContain("Required with --wait, without --dry-run:\n database_read"); + }); + }); + }); + + describe("help", () => { + it.effect("distinguishes Management API capabilities from SQL EXPLAIN in status help", () => { + const { console, calls } = fakeConsole(); + const { run } = setup(["warehouse", "status", "--help"], { route: accepted }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + expect(calls.join("\n")).toContain("Capabilities describe Management API operations"); + expect(calls.join("\n")).toContain("SQL EXPLAIN"); + }); + }); + + it.effect("shows a body file in the layout update example", () => { + const { console, calls } = fakeConsole(); + const { run } = setup(["warehouse", "tables", "layout", "update", "--help"], { + route: accepted, + }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + expect(calls.join("\n")).toContain( + "supabase warehouse tables layout update --file ", + ); + expect(calls.join("\n")).toContain( + `--partition-by '[{"column":"event_at","transform":{"kind":"day"}}]'`, + ); + expect(calls.join("\n")).toContain(`--sort-by '{"kind":"none"}'`); + }); + }); + + it.effect("lists a required body-bound flag in the usage example", () => { + const { console, calls } = fakeConsole(); + const { run } = setup(["warehouse", "replication", "add", "--help"], { route: accepted }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + expect(calls.join("\n")).toContain("supabase warehouse replication add --schema "); + }); + }); + + it.effect("marks a required API flag as required in its description", () => { + const { console, calls } = fakeConsole(); + const { run } = setup(["warehouse", "enable", "--help"], { route: accepted }); + return Effect.gen(function* () { + yield* run.pipe(Effect.provideService(Console.Console, console)); + const lines = calls.join("\n").split("\n"); + const flagLine = (name: string) => lines.find((line) => line.includes(`--${name} `)); + expect(flagLine("schema")).toContain("Required unless the field is in --body or --file."); + expect(flagLine("table")).not.toContain("Required"); + }); + }); + }); + + describe("--wait", () => { + it.effect("polls the read until the setup succeeds, then prints the accepted response", () => { + const { sent, out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([ + { status: 200, body: statusBody("pending") }, + { status: 200, body: statusBody("pending") }, + { status: 200, body: statusBody("succeeded") }, + ]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + const gets = sent.filter((request) => request.method === "GET"); + expect(gets).toHaveLength(3); + expect(gets.every((request) => request.path === SETUP_PATH)).toBe(true); + expect(gets.every((request) => request.search === `selection_id=${SEL}`)).toBe(true); + expect(out.stdoutText).toBe(encodeJson(ACCEPTED)); + }); + }); + + it.effect("fails with the reported status_error when the setup fails", () => { + const { run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: statusBody("failed", "pipeline crashed") }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const failure = yield* Fiber.join(fiber); + expect(failure).toBeInstanceOf(ApiCommandOperationFailedError); + expect(failure).toMatchObject({ message: expect.stringContaining("pipeline crashed") }); + }); + }); + + it.effect("times out on the controlled clock when the status never settles", () => { + const { sent, run } = setup( + ["warehouse", "enable", "--schema", "public", "--wait", "--timeout", "10s"], + { yes: true, route: enableThenPoll([{ status: 200, body: statusBody("pending") }]) }, + ); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + expect(yield* Fiber.join(fiber)).toBeInstanceOf(ApiCommandWaitTimeoutError); + expect(sent.filter((request) => request.method === "GET").length).toBeGreaterThan(1); + }); + }); + + it.effect("fails the wait when a poll response has no readable status", () => { + const { sent, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: "captive portal" }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const failure = yield* Fiber.join(fiber); + expect(failure).toBeInstanceOf(ApiCommandUnexpectedResponseError); + expect(failure).toMatchObject({ suggestion: expect.stringContaining("Check it with") }); + expect(sent.filter((request) => request.method === "GET")).toHaveLength(1); + }); + }); + + it.effect("treats a 409 on the read as terminal and does not poll again", () => { + const { sent, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([ + { + status: 409, + body: { error: { code: "selection_conflict", message: "selection changed" } }, + }, + ]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const failure = yield* Fiber.join(fiber); + expect(failure).toBeInstanceOf(ApiCommandStatusError); + expect(failure).toMatchObject({ status: 409, message: "selection changed (HTTP 409)" }); + expect(sent.filter((request) => request.method === "GET")).toHaveLength(1); + }); + }); + + it.effect("fails with the generic operation error when a failed status has no error", () => { + const { run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: statusBody("failed") }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const failure = yield* Fiber.join(fiber); + expect(failure).toBeInstanceOf(ApiCommandOperationFailedError); + expect(failure).toMatchObject({ + status: "failed", + message: 'The operation failed with status "failed".', + }); + }); + }); + + it.effect( + "succeeds and prints the accepted response when a succeeded status carries an error", + () => { + const settled = statusBody("succeeded", "earlier attempt failed"); + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: settled }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + expect(out.stdoutText).toBe(encodeJson(ACCEPTED)); + }); + }, + ); + + it.effect("keeps polling while a non-terminal status carries an error value", () => { + const { sent, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([ + { status: 200, body: statusBody("pending", "retrying") }, + { status: 200, body: statusBody("succeeded") }, + ]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + expect(sent.filter((request) => request.method === "GET")).toHaveLength(2); + }); + }); + + it.effect( + "ends the wait with a defect when the accepted response lacks the selection id", + () => { + const { sent, run } = setup( + ["warehouse", "enable", "--schema", "public", "--yes", "--wait"], + { + yes: true, + route: (request) => + request.method === "POST" + ? { status: 202, body: { data: { type: "warehouse_setup", attributes: {} } } } + : { status: 200, body: statusBody("succeeded") }, + }, + ); + return Effect.gen(function* () { + const exit = yield* Effect.exit(run); + expect(Exit.isFailure(exit) && Cause.hasDies(exit.cause)).toBe(true); + expect(sent.map((request) => request.method)).toEqual(["POST"]); + }); + }, + ); + + it.effect( + "points a failed or timed-out wait at warehouse status without exposing the internal setup read", + () => { + const failing = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: statusBody("failed", "boom") }]), + }); + const stalling = setup( + ["warehouse", "enable", "--schema", "public", "--wait", "--timeout", "10s"], + { yes: true, route: enableThenPoll([{ status: 200, body: statusBody("pending") }]) }, + ); + const suggestion = `Check it with \`supabase warehouse status --remote=${VALID_REF}\`.`; + return Effect.gen(function* () { + for (const { run } of [failing, stalling]) { + const fiber = yield* run.pipe( + Effect.flip, + Effect.forkChild({ startImmediately: true }), + ); + yield* driveClock(fiber); + expect(yield* Fiber.join(fiber)).toMatchObject({ suggestion }); + } + }); + }, + ); + + it.effect.each([ + { + name: "with --wait", + argv: ["warehouse", "enable", "--schema", "public", "--wait", "--timeout", "soon"], + }, + { name: "without --wait", argv: ["warehouse", "disable", "--timeout", "soon"] }, + ])("rejects an invalid --timeout $name before sending anything", ({ argv }) => { + const { sent, run } = setup(argv, { yes: true, route: accepted }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf(ApiCommandUsageError); + expect(sent).toEqual([]); + }); + }); + }); + + describe("text output", () => { + const STATUS_TEXT = + [ + "Warehouse setup", + ` ID ${SEL}`, + " DNS", + " Hostname wh.example.test", + " Region us-east-1", + " Status active", + " Delete data no", + " Setup status ready", + " Pipeline ID 42", + " Steps", + " NAME | STATUS | MESSAGE ", + " -----------------------|-----------|--------------------", + " create_pipeline | succeeded | - ", + " import_foreign_schema | failed | line one\\nline two ", + " Tables", + " SCHEMA | NAME | STATE | LAG MS | LAST SYNCED AT | COPY NAME | REPLICATION STATE | WAREHOUSE SIZE BYTES ", + " --------|--------|---------|--------|----------------------|-------------------|-------------------|----------------------", + ' public | orders | synced | 120 | 2026-01-01T00:00:00Z | "public"."orders" | streaming | - ', + ' public | users | copying | - | - | "public"."users" | copying | 2048 ', + " FDW status", + " Extension available yes", + " Extension installed yes", + " Wrapper installed no", + " Server configured no", + " Schema created no", + " Foreign schema imported no", + " Status succeeded", + " Replication state streaming", + ].join("\n") + "\n"; + + it.effect("renders the response as text on a terminal by default", () => { + const { out, run } = setup(["warehouse", "status"], { + route: ok(RICH_STATUS), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(STATUS_TEXT); + }); + }); + + it.effect("renders text by default when stdout is piped and no format is requested", () => { + const { out, run } = setup(["warehouse", "status"], { + route: ok(RICH_STATUS), + outputFormat: "text", + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(STATUS_TEXT); + }); + }); + + it.effect("keeps the API bytes for json and shows the request as a task", () => { + const { out, run } = setup(["warehouse", "status", "--output-format", "json"], { + route: ok(RICH_STATUS), + outputFormat: "json", + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(encodeJson(RICH_STATUS)); + expect(out.progressEvents).toEqual([ + { type: "start", message: "Get consolidated Warehouse status and capabilities" }, + ]); + }); + }); + + it.effect("emits one result frame with the parsed response for stream-json", () => { + const { out, run } = setup(["warehouse", "status", "--output-format", "stream-json"], { + route: ok(RICH_STATUS), + outputFormat: "stream-json", + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(""); + expect(out.events).toEqual([ + { type: "result", data: RICH_STATUS, timestamp: expect.any(String) }, + ]); + }); + }); + + it.effect("emits null as the result frame of an empty body for stream-json", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ status: 202 }), + outputFormat: "stream-json", + }); + return Effect.gen(function* () { + yield* run; + expect(out.events).toEqual([{ type: "result", data: null, timestamp: expect.any(String) }]); + }); + }); + + it.effect("fails a non-JSON success body for stream-json without a result frame", () => { + const { out, run } = setup(["warehouse", "status"], { + route: ok("not json"), + outputFormat: "stream-json", + }); + return Effect.gen(function* () { + expect(failureOf(yield* Effect.exit(run))).toBeInstanceOf( + ApiCommandUnexpectedResponseError, + ); + expect(out.events).toEqual([]); + }); + }); + + it.effect("emits the dry-run request as the result frame for stream-json", () => { + const { out, run } = setup(["warehouse", "status", "--dry-run"], { + route: ok({}), + outputFormat: "stream-json", + }); + return Effect.gen(function* () { + yield* run; + expect(out.events).toEqual([ + { + type: "result", + data: { method: "GET", path: STATUS_PATH, query: {}, headers: {}, body: null }, + timestamp: expect.any(String), + }, + ]); + }); + }); + + it.effect("emits the accepted response as the result frame of a stream-json --wait", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + route: enableThenPoll([{ status: 200, body: statusBody("succeeded") }]), + outputFormat: "stream-json", + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + expect(out.events).toEqual([ + { type: "result", data: ACCEPTED, timestamp: expect.any(String) }, + ]); + }); + }); + + it.effect("shows the request as one task that is cleared when it succeeds", () => { + const { out, run } = setup(["warehouse", "status"], { + route: ok(RICH_STATUS), + stdoutIsTty: true, + }); + return Effect.gen(function* () { + yield* run; + expect(out.progressEvents).toEqual([ + { type: "start", message: "Get consolidated Warehouse status and capabilities" }, + ]); + expect(out.taskSettlements).toEqual([{ type: "clear" }]); + }); + }); + + it.effect( + "prints the accepted response as text and tracks the wait in one polling task", + () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + stdoutIsTty: true, + route: enableThenPoll([ + { status: 200, body: statusBody("pending") }, + { status: 200, body: statusBody("succeeded") }, + ]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + expect(out.stdoutText).toBe( + [ + "Warehouse setup", + ` ID ${SEL}`, + ` Selection ID ${SEL}`, + " Status pending", + " Future field", + " Nested 1, 2", + "", + ].join("\n"), + ); + const polling = "Get Warehouse initial synchronization status"; + expect(out.progressEvents).toEqual([ + { type: "start", message: "Enable Warehouse replication" }, + { type: "start", message: polling }, + { type: "message", message: `${polling} (status: pending)` }, + { type: "message", message: `${polling} (status: succeeded)` }, + ]); + expect(out.taskSettlements).toEqual([{ type: "clear" }, { type: "clear" }]); + }); + }, + ); + + it.effect("escapes control characters in the polled status shown in the task", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + stdoutIsTty: true, + route: enableThenPoll([ + { status: 200, body: statusBody("\u001b[31mred") }, + { status: 200, body: statusBody("succeeded") }, + ]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + yield* Fiber.join(fiber); + const shown = out.progressEvents.map((event) => event.message).join("\n"); + expect(shown).toContain("(status: \\u001b[31mred)"); + expect(shown).not.toContain("\u001b"); + }); + }); + + it.effect("fails the polling task and keeps the standard error when the setup fails", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + stdoutIsTty: true, + route: enableThenPoll([{ status: 200, body: statusBody("failed", "pipeline crashed") }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + yield* driveClock(fiber); + const failure = yield* Fiber.join(fiber); + expect(failure).toBeInstanceOf(ApiCommandOperationFailedError); + expect(failure).toMatchObject({ message: expect.stringContaining("pipeline crashed") }); + expect(out.stdoutText).toBe(""); + expect(out.taskSettlements).toEqual([{ type: "clear" }, { type: "fail" }]); + }); + }); + + it.effect("cancels the polling task when the run is interrupted mid-wait", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public", "--wait"], { + yes: true, + stdoutIsTty: true, + route: enableThenPoll([{ status: 200, body: statusBody("pending") }]), + }); + return Effect.gen(function* () { + const fiber = yield* run.pipe(Effect.forkChild({ startImmediately: true })); + yield* TestClock.adjust("2 seconds").pipe( + Effect.andThen(Effect.yieldNow), + Effect.repeat({ until: () => out.progressEvents.some((e) => e.type === "message") }), + ); + yield* Fiber.interrupt(fiber); + expect(out.stdoutText).toBe(""); + expect(out.taskSettlements).toEqual([{ type: "clear" }, { type: "cancel" }]); + }); + }); + + it.effect("prints the dry run as text with its query values", () => { + const { out, sent, run } = setup( + [ + "warehouse", + "teardowns", + "get", + "--operation-id", + "7579647f-2cdc-466c-982e-425958a2f985", + "--dry-run", + "--output-format", + "text", + ], + { route: ok({}), stdoutIsTty: true }, + ); + return Effect.gen(function* () { + yield* run; + expect(sent).toEqual([]); + expect(out.stdoutText).toBe( + [ + `Dry run: GET /v2/projects/${VALID_REF}/warehouse/teardowns/current`, + "Query", + " operation_id 7579647f-2cdc-466c-982e-425958a2f985", + "", + ].join("\n"), + ); + }); + }); + }); + + describe("generic response writing", () => { + it.effect("writes a JSON body byte for byte, unknown fields and spacing included", () => { + const raw = '{"z": 1, "known": {"future": [1, 2]}}'; + const { out, run } = setup(["warehouse", "status"], { + route: () => ({ status: 200, body: raw }), + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe(raw); + }); + }); + + it.effect("writes an empty accepted body as null", () => { + const { out, run } = setup(["warehouse", "enable", "--schema", "public"], { + yes: true, + route: () => ({ status: 202 }), + }); + return Effect.gen(function* () { + yield* run; + expect(out.stdoutText).toBe("null\n"); + }); + }); + }); + + describe("feature gate", () => { + const resolve = ( + env: Record, + cwd: string, + args: ReadonlyArray = ["warehouse"], + ) => + withConfigEnv(env, resolveApiCommandFeatures({ args, cwd })).pipe( + Effect.provide(BunServices.layer), + ); + + const withConfig = (config: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(path.join(tempRoot.current, "supabase"), { recursive: true }); + yield* fs.writeFileString(path.join(tempRoot.current, "supabase", "config.toml"), config); + }).pipe(Effect.provide(BunServices.layer)); + + it.effect("is off by default and absent from the tree and completion", () => + Effect.gen(function* () { + expect(yield* resolve({}, tempRoot.current)).toEqual([]); + expect(commandTreeFor(undefined).has("warehouse enable")).toBe(false); + const completion = respondToComplete(rootCommandForFeatures(), ["__complete", "ware"]); + expect(completion?.candidates ?? []).toHaveLength(0); + }), + ); + + it.effect("is on with SUPABASE_EXPERIMENTAL_WAREHOUSE", () => + Effect.gen(function* () { + expect(yield* resolve({ SUPABASE_EXPERIMENTAL_WAREHOUSE: "1" }, tempRoot.current)).toEqual([ + "warehouse", + ]); + const root = rootCommandForFeatures({ apiFeatures: ["warehouse"] }); + const completion = respondToComplete(root, ["__complete", "ware"]); + expect(completion?.candidates).toContainEqual( + expect.objectContaining({ name: "warehouse" }), + ); + const tree = commandTreeFor({ apiFeatures: ["warehouse"] }); + expect(tree.has("warehouse enable")).toBe(true); + expect(tree.has("warehouse setups get")).toBe(false); + expect(tree.has("warehouse status")).toBe(true); + }), + ); + + it.effect("completes the group and its subcommands after help", () => + Effect.gen(function* () { + const env = { SUPABASE_EXPERIMENTAL_WAREHOUSE: "1" }; + const names = (args: ReadonlyArray) => + Effect.gen(function* () { + const apiFeatures = yield* resolve(env, tempRoot.current, args); + const completion = respondToComplete(rootCommandForFeatures({ apiFeatures }), args); + return completion?.candidates.map((candidate) => candidate.name) ?? []; + }); + expect(yield* names(["__complete", "help", "ware"])).toContain("warehouse"); + expect(yield* names(["__complete", "help", "warehouse", "en"])).toContain("enable"); + }), + ); + + it.effect("is on with experimental.warehouse in the project config", () => + Effect.gen(function* () { + yield* withConfig("[experimental]\nwarehouse = true\n"); + expect(yield* resolve({}, tempRoot.current)).toEqual(["warehouse"]); + }), + ); + + it.effect.each([ + { name: "root help", args: [], features: ["warehouse"] }, + { + name: "shell completion of the group", + args: ["__complete", "ware"], + features: ["warehouse"], + }, + { + name: "help completion of the group", + args: ["__complete", "help", "ware"], + features: ["warehouse"], + }, + { name: "help for the group", args: ["help", "warehouse"], features: ["warehouse"] }, + { name: "inspection parent help", args: ["inspect"], features: [] }, + { + name: "Warehouse inspection", + args: ["warehouse", "inspect", "query-stats"], + features: ["warehouse"], + }, + { + name: "Warehouse capacity inspection", + args: ["warehouse", "inspect", "capacity"], + features: ["warehouse"], + }, + { name: "database inspection", args: ["inspect", "db", "table-stats"], features: [] }, + { name: "inspection report", args: ["inspect", "report"], features: [] }, + { + name: "inspection completion", + args: ["__complete", "inspect", ""], + features: [], + }, + { + name: "database inspection completion", + args: ["__complete", "inspect", "db", ""], + features: [], + }, + { name: "a command of another group", args: ["projects", "list"], features: [] }, + { name: "completion of another group", args: ["__complete", "projects", ""], features: [] }, + { name: "the root version flag", args: ["--version"], features: [] }, + ])("resolves $name by whether it can reach the group", ({ args, features }) => + Effect.gen(function* () { + const env = { SUPABASE_EXPERIMENTAL_WAREHOUSE: "1" }; + expect(yield* resolve(env, tempRoot.current, args)).toEqual(features); + }), + ); + + it.effect("ignores an invalid value when the invocation cannot reach the group", () => + Effect.gen(function* () { + const env = { SUPABASE_EXPERIMENTAL_WAREHOUSE: "maybe" }; + expect(yield* resolve(env, tempRoot.current, ["projects", "list"])).toEqual([]); + expect(yield* resolve(env, tempRoot.current, ["inspect"])).toEqual([]); + expect(yield* resolve(env, tempRoot.current, ["inspect", "db", "table-stats"])).toEqual([]); + expect(yield* resolve(env, tempRoot.current, ["inspect", "report"])).toEqual([]); + }), + ); + + it.effect("fails with a typed error for an invalid environment value", () => + Effect.gen(function* () { + const error = yield* resolve( + { SUPABASE_EXPERIMENTAL_WAREHOUSE: "maybe" }, + tempRoot.current, + ).pipe(Effect.flip); + expect(error).toBeInstanceOf(ExperimentalFeatureFlagError); + }), + ); + }); +}); + +const consentCommand = commandTreeFor({ apiFeatures: ["warehouse"] }).get( + "warehouse enable", +)?.command; + +describeHostedConsent("warehouse enable", { + ...(consentCommand === undefined ? {} : { command: consentCommand }), + invoke: ({ workdir, yes }) => { + const { args, sent, run } = execute(["warehouse", "enable", "--schema", "public"], { + yes, + route: accepted, + }); + return { + run: run.pipe(Effect.provide(cliServices(workdir, args))), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +describe("hosted consent details", () => { + it.effect.each([ + { + name: "a disable that deletes data", + argv: ["warehouse", "disable", "--delete-data"], + shown: ["delete_data: true", "permanently delete the managed catalog schema"], + }, + { + name: "a layout update with a reset", + argv: [ + "warehouse", + "tables", + "layout", + "update", + "16385", + "--body", + encodeJson({ + data: { + type: "warehouse_table_layout", + attributes: { sort_by: null, reset_table: true }, + }, + }), + ], + shown: [ + "table_id: 16385", + "sort_by: null", + "reset_table: true", + "Reads are disrupted during the copy", + ], + }, + { + name: "a body field with terminal control characters", + argv: ["warehouse", "replication", "add", "--schema", "a\u202eb\u009bc"], + shown: ["schema: a\\u202eb\\u009bc"], + }, + ])("lists what $name will send before asking", ({ argv, shown }) => { + const { out, sent, run } = setup(argv, { route: accepted, confirmResponses: [false] }); + return Effect.gen(function* () { + yield* Effect.exit(run); + for (const line of shown) expect(out.stderrText).toContain(line); + expect(sent.filter((request) => request.method !== "GET")).toEqual([]); + }); + }); +}); + +const disableConsentCommand = commandTreeFor({ apiFeatures: ["warehouse"] }).get( + "warehouse disable", +)?.command; +describeHostedConsent("warehouse disable", { + ...(disableConsentCommand === undefined ? {} : { command: disableConsentCommand }), + invoke: ({ workdir, yes }) => { + const { args, sent, run } = execute(["warehouse", "disable"], { yes, route: accepted }); + return { + run: run.pipe(Effect.provide(cliServices(workdir, args))), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +const layoutUpdateConsentCommand = commandTreeFor({ apiFeatures: ["warehouse"] }).get( + "warehouse tables layout update", +)?.command; +describeHostedConsent("warehouse tables layout update", { + ...(layoutUpdateConsentCommand === undefined ? {} : { command: layoutUpdateConsentCommand }), + invoke: ({ workdir, yes }) => { + const body = { data: { type: "warehouse_table_layout", attributes: { sort_by: null } } }; + const { args, sent, run } = execute( + ["warehouse", "tables", "layout", "update", "16385", "--body", encodeJson(body)], + { yes, route: accepted }, + ); + + return { + run: run.pipe(Effect.provide(cliServices(workdir, args))), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +describeHostedConsent("warehouse replication add", { + command: commandTreeFor({ apiFeatures: ["warehouse"] }).get("warehouse replication add")!.command, + invoke: ({ workdir, yes, out }) => { + const { args, sent, run } = execute( + ["warehouse", "replication", "add", "--schema", "public", "--table", "orders"], + { yes, route: accepted }, + ); + return { + run: run.pipe( + Effect.onExit(() => + Effect.sync(() => { + if (out.promptConfirmCalls.length > 0) { + expect(out.stderrText).toContain("interrupting replication for other tables"); + } + }), + ), + Effect.provide(cliServices(workdir, args)), + ), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +describeHostedConsent("warehouse replication remove", { + command: commandTreeFor({ apiFeatures: ["warehouse"] }).get("warehouse replication remove")! + .command, + invoke: ({ workdir, yes, out }) => { + const { args, sent, run } = execute( + ["warehouse", "replication", "remove", "--schema", "public", "--table", "orders"], + { yes, route: accepted }, + ); + return { + run: run.pipe( + Effect.onExit(() => + Effect.sync(() => { + if (out.promptConfirmCalls.length > 0) { + expect(out.stderrText).toContain("retained copy stops receiving updates"); + } + }), + ), + Effect.provide(cliServices(workdir, args)), + ), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +describeHostedConsent("warehouse replication resync", { + command: commandTreeFor({ apiFeatures: ["warehouse"] }).get("warehouse replication resync")! + .command, + invoke: ({ workdir, yes, out }) => { + const { args, sent, run } = execute( + ["warehouse", "replication", "resync", "--schema", "public", "--table", "orders"], + { yes, route: accepted }, + ); + return { + run: run.pipe( + Effect.onExit(() => + Effect.sync(() => { + if (out.promptConfirmCalls.length > 0) { + expect(out.stderrText).toContain("deleted and rebuilt"); + expect(out.stderrText).toContain("interrupts replication for other tables"); + } + }), + ), + Effect.provide(cliServices(workdir, args)), + ), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); + +describeHostedConsent("warehouse replication restart", { + command: commandTreeFor({ apiFeatures: ["warehouse"] }).get("warehouse replication restart")! + .command, + invoke: ({ workdir, yes }) => { + const { args, sent, run } = execute(["warehouse", "replication", "restart"], { + yes, + route: accepted, + }); + return { + run: run.pipe(Effect.provide(cliServices(workdir, args))), + mutations: () => sent.filter((request) => request.method !== "GET").length, + }; + }, +}); diff --git a/apps/cli/src/commands/api/generated.md b/apps/cli/src/commands/api/generated.md new file mode 100644 index 0000000000..424d5b48ff --- /dev/null +++ b/apps/cli/src/commands/api/generated.md @@ -0,0 +1,295 @@ + + +# Generated API commands + +Reference for the commands generated from the Management API contract. + +## `supabase warehouse connection` + +Get Warehouse Flight SQL connection details + +Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: `usql -W 'flightsql://postgres@:443?tls=enabled'`. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/connection` (`v2-get-warehouse-connection`), success 200 json. + +## `supabase warehouse disable` + +Disable Warehouse replication and access + +Stops replication and removes the Warehouse publication, FDW and dependent foreign tables, reader group, catalog access and query routing asynchronously. Stored Warehouse data is retained by default. Set delete_data=true to permanently delete the managed catalog schema and dedicated Storage bucket; destination SQL and Storage write permissions are also required. Legacy shared buckets and source Postgres tables are preserved. Reader memberships are not restored on re-enablement. Safe retries return the existing cleanup identity; changing an in-progress data policy returns a conflict. Poll the linked teardown for completion or partial cleanup failures. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `DELETE /v2/projects/{ref}/warehouse` (`v2-disable-warehouse`), success 202 json. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| --------------- | ------- | -------- | ---------- | ------------------- | +| `--delete-data` | boolean | no | no | query `delete_data` | + +### Wait + +- Polls: `GET /v2/projects/{ref}/warehouse/teardowns/current` (`v2-get-warehouse-teardown`). +- Read parameters from the change response: `operation_id` from `/data/id`. +- Status at `/data/attributes/lifecycle_status`; succeeded: `disabled`; failed: `deletion_failed`. +- Failure message from `/data/attributes/cleanup_error`. +- Failure hint names `supabase warehouse teardowns get --operation-id --remote=`. + +## `supabase warehouse enable` + +Enable Warehouse replication + +Enables replication for the currently eligible tables in a schema, or the named tables in that schema. Resolves source identities under the mutation lock without a preview or revision. Repeating the same selection is safe; a different existing selection is rejected. Schema selection excludes future tables; selected partition roots include future partitions. Acceptance does not imply completed synchronization. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `POST /v2/projects/{ref}/warehouse/enable` (`v2-enable-warehouse`), success 202 json. +- Body: JSON envelope `data.type = warehouse_setup`, fields under `data.attributes`. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ----------------------------------------------------- | ------- | ---------------------------------------------- | ---------- | ----------------------------------------------- | +| `--warehouse-region ` | string | no | no | body `/data/attributes/warehouse_region` | +| `--destination-project-ref ` | string | no | no | body `/data/attributes/destination_project_ref` | +| `--install-fdw` | boolean | no | no | body `/data/attributes/install_fdw` | +| `--schema ` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/schema` | +| `--table ` | string | no | yes | body `/data/attributes/tables` | + +### Wait + +- Polls: `GET /v2/projects/{ref}/warehouse/setups/current` (`v2-get-warehouse-setup`, poll-only read). +- Read parameters from the change response: `selection_id` from `/data/attributes/selection_id`. +- Status at `/data/attributes/status`; succeeded: `succeeded`; failed: `failed`. +- Failure message from `/data/attributes/status_error`. +- Failure hint names `supabase warehouse status --remote=`. + +## `supabase warehouse inspect capacity` + +Inspect Warehouse capacity diagnostics + +Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use `--since` or specify both `--from` and `--to`; the default is the last 30 minutes. + +Each measurement includes its definition, unit, aggregation, requested and effective ranges, `rate_window_seconds`, source-sample freshness, availability, coverage, and full series with dimension labels such as `reason`, `kind`, and `result`. + +Executor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or `null`; they do not establish healthy or idle capacity. + +Point timestamps are evaluation times; `last_sample_at` is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. + +Each request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/capacity` (`v2-get-warehouse-capacity`), success 200 json. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| --------------------------- | --------------------------------------------- | -------- | ---------- | ------------------ | +| `--attributes ` | string | no | no | query `attributes` | +| `--from ` | string | no | no | query `from` | +| `--interval ` | string (`10m`, `1d`, `1h`, `1m`, `30m`, `5m`) | no | no | query `interval` | +| `--since ` | string | no | no | query `since` | +| `--to ` | string | no | no | query `to` | + +## `supabase warehouse inspect query-stats` + +Inspect Warehouse workload query statistics + +Returns aggregate workload measurements over a bounded time range, using the project’s stored Warehouse placement. Use since or both from and to; the default is the last 30 minutes. Each measurement includes its definition, unit, aggregation, requested and effective ranges, rate_window_seconds, source-sample freshness, availability, and full series with dimension labels. Point timestamps are evaluation times; last_sample_at is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. Do not average interval percentiles into a whole-range percentile. Executor invocations include metadata/schema work and are not counts of user SQL statements. Timeouts are included in errors; cancellation is separate. Missing and unavailable values remain null. No query history, individual-query attribution, raw queries, or backend selectors are exposed. Each request returns up to eight measurements. A failure of one measurement does not discard the other results. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/query-stats` (`v2-get-warehouse-query-stats`), success 200 json. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| --------------------------- | --------------------------------------------- | -------- | ---------- | ------------------ | +| `--attributes ` | string | no | no | query `attributes` | +| `--from ` | string | no | no | query `from` | +| `--interval ` | string (`10m`, `1d`, `1h`, `1m`, `30m`, `5m`) | no | no | query `interval` | +| `--since ` | string | no | no | query `since` | +| `--to ` | string | no | no | query `to` | + +## `supabase warehouse replication add` + +Add source tables to Warehouse replication + +Adds one eligible source table or the currently eligible tables in a schema to an enabled Warehouse. Existing selections and layouts are preserved; already-selected tables are unchanged. Schema selection excludes future tables, except future partitions of selected partition roots. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline remains stopped and requires an explicit start before copying. Initial copy adds source reads; duration is unknown. Unsafe reattachment of retained data is rejected. The response describes configuration and restart acceptance, not completed copy or streaming. Failures may have partial effects; inspect table and pipeline state before retrying. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `POST /v2/projects/{ref}/warehouse/replication/add` (`v2-add-warehouse-replication`), success 202 json. +- Body: JSON envelope `data.type = warehouse_replication_change`, fields under `data.attributes`. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ------------------- | ------ | ---------------------------------------------- | ---------- | ------------------------------ | +| `--schema ` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/schema` | +| `--table
` | string | no | no | body `/data/attributes/table` | + +## `supabase warehouse replication remove` + +Remove source tables from Warehouse replication + +Removes one selected source table or all selected tables in a schema as a batch. Source PostgreSQL rows and existing Warehouse data are retained. The retained copy stops receiving updates. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline stays stopped. Removing an unselected target is unchanged. Removing the last target leaves Warehouse enabled with an empty selection. Publication changes and restart acceptance do not establish observed exclusion by active replication. Failures may have partial effects; inspect the selection and pipeline before retrying. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `POST /v2/projects/{ref}/warehouse/replication/remove` (`v2-remove-warehouse-replication`), success 202 json. +- Body: JSON envelope `data.type = warehouse_replication_change`, fields under `data.attributes`. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ------------------- | ------ | ---------------------------------------------- | ---------- | ------------------------------ | +| `--schema ` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/schema` | +| `--table
` | string | no | no | body `/data/attributes/table` | + +## `supabase warehouse replication restart` + +Start or restart Warehouse replication + +Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `POST /v2/projects/{ref}/warehouse/replication/restart` (`v2-restart-warehouse-replication`), success 202 json. + +## `supabase warehouse replication resync` + +Reset and rebuild one Warehouse table + +Resets replication for one selected source table using its currently saved layout. Source rows, saved layouts and completed replication state for unrelated tables are preserved. In-progress initial copies of other tables may restart from scratch. The Warehouse copy is deleted and rebuilt when replication resumes; table reads may be unavailable, freshness can lag, and the source incurs additional reads. Stopping and restarting the pipeline interrupts replication for other tables. Duration is unknown. The pipeline must be started and initial sync enabled for the table before the reset. The immediate response retains ETL reset states; it does not establish recopy completion. Inspect warehouse tables get and warehouse status separately. Do not automatically retry an uncertain response: repeating this request may reset the table again. There is no server-side preview, revision check, idempotency key or operation polling. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `POST /v2/projects/{ref}/warehouse/replication/resync` (`v2-resync-warehouse-replication`), success 202 json. +- Body: JSON envelope `data.type = warehouse_replication_resync`, fields under `data.attributes`. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ------------------- | ------ | ---------------------------------------------- | ---------- | ------------------------------ | +| `--schema ` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/schema` | +| `--table
` | string | yes, unless `--body` or `--file` has the field | no | body `/data/attributes/table` | + +## `supabase warehouse status` + +Get consolidated Warehouse status and capabilities + +Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/status` (`v2-get-warehouse-status`), success 200 json. + +## `supabase warehouse tables get` + +Get a table replicated to Warehouse + +Returns one source table selected for Warehouse replication by its source OID, from the same observations and with the same status and freshness attributes as the Warehouse tables list. Returns 404 when the table is not selected for replication, including when Warehouse is not set up, its publication is missing, or it is being disabled. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/tables/{table_id}` (`v2-get-warehouse-table`), success 200 json. +- Positional argument ``, bound to path parameter `table_id`. + +## `supabase warehouse tables layout get` + +Get the layout of a table replicated to Warehouse + +Returns the sorting and partitioning rules saved for one replicated table, by source OID, beside the layout the DuckLake catalog records for it. The two are reported separately and can differ: the replicator applies saved rules when it starts and then hourly, and a stopped pipeline applies them on its next start. observation_status reports whether the catalog was read; desired rules are returned even when it was not. A catalog layout governs files written after it changes and does not establish that existing files are sorted or partitioned. Returns 404 when the table is not replicated, including when Warehouse is not set up, is being disabled or failed to clean up. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/tables/{table_id}/layout` (`v2-get-warehouse-table-layout`), success 200 json. +- Positional argument ``, bound to path parameter `table_id`. + +## `supabase warehouse tables layout update` + +Update the layout of a table replicated to Warehouse + +Partition new files by event day and sort within files; preserve historical files. + +```sh +supabase warehouse tables layout update --partition-by '[{"column":"event_at","transform":{"kind":"day"}}]' --sort-by '{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}' +``` + +Preview eight hash buckets locally without changing the Warehouse. + +```sh +supabase warehouse tables layout update --partition-by '[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]' --dry-run +``` + +Clear partitioning and sorting for future writes. + +```sh +supabase warehouse tables layout update --partition-by '[]' --sort-by '{"kind":"none"}' +``` + +Stop managing both settings; omitted flags preserve their saved values. + +```sh +supabase warehouse tables layout update --partition-by 'null' --sort-by 'null' +``` + +Updates saved sorting and partitioning rules for one source table object identifier (OID). Provide sort_by or partition_by; empty and reset-only patches are rejected. Omitted settings are preserved. Null makes a setting unmanaged. An empty partition list clears partitioning, and the none sort selector clears sorting. The backend validates the source schema and preserves other tables. When the layout changes, an active pipeline is restarted. A stopped pipeline stays stopped. reset_table defaults to false, preserving historical files and replication progress. When the layout changes, --reset-table resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never restarts the pipeline or resets the table. Acceptance and application_status report orchestration. Run warehouse tables layout get to compare the desired and observed rules. Run warehouse tables get to check table replication status. These reads do not establish completion of this specific update. There is no revision, idempotency, resolved preview, or durable operation contract. A failed update can leave partial effects, including a completed reset. Inspect the saved layout, pipeline, and table state before retrying. + +- Access: mutation, consent defaults to No (`--yes` when it cannot prompt). +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Consent: prints the API description before the interactive confirmation. +- Request: `PATCH /v2/projects/{ref}/warehouse/tables/{table_id}/layout` (`v2-update-warehouse-table-layout`), success 202 json. +- Body: JSON envelope `data.type = warehouse_table_layout`, fields under `data.attributes`. +- Positional argument ``, bound to path parameter `table_id`. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ----------------------- | ------- | -------- | ---------- | ------------------------------------ | +| `--partition-by ` | json | no | no | body `/data/attributes/partition_by` | +| `--reset-table` | boolean | no | no | body `/data/attributes/reset_table` | +| `--sort-by ` | json | no | no | body `/data/attributes/sort_by` | + +## `supabase warehouse tables list` + +List tables replicated to Warehouse + +Lists the source tables selected for Warehouse replication with their replication status and freshness, from the same observations as the Warehouse status. Freshness comes from the replication slot that carries each table: its own sync slot until it follows changes, then the pipeline apply slot; one slot never stands in for the other. lag_ms is that slot's flush lag. Postgres reports no lag time for a caught-up slot without new WAL, so lag_ms can be null while replication_feedback.flush_lag_bytes is 0; neither is ever filled with zero when unknown. observed_at is when the API read the replication state, not when data last synchronized. A stopped, failed or unreadable pipeline reports its tables as stopped or unknown rather than live, and keeps each table's last recorded state. Returns an empty list when Warehouse is not set up, its publication is missing, or it is being disabled or failed to clean up. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/tables` (`v2-list-warehouse-tables`), success 200 json. + +## `supabase warehouse teardowns get` + +Get Warehouse cleanup status + +Reads the current durable cleanup state without contacting ETL or inspecting the FDW. Disabling means cleanup is in progress; disabled means cleanup completed; deletion_failed means cleanup may be partial. The original data policy and failure reason remain available. Optionally supply operation_id to observe a specific disable attempt. Returns a conflict if no cleanup state is available or the supplied identity does not match the current operation. + +- Access: read-only, no consent. +- Experimental: enable with `experimental.warehouse` or `SUPABASE_EXPERIMENTAL_WAREHOUSE=1`. +- Request: `GET /v2/projects/{ref}/warehouse/teardowns/current` (`v2-get-warehouse-teardown`), success 200 json. + +### Flags + +| Flag | Type | Required | Repeatable | Binds to | +| ------------------------------- | ------ | -------- | ---------- | -------------------- | +| `--operation-id ` | string | no | no | query `operation_id` | + +### Wait + +- Polls: `GET /v2/projects/{ref}/warehouse/teardowns/current` (`v2-get-warehouse-teardown`, the command's own read). +- Status at `/data/attributes/lifecycle_status`; succeeded: `disabled`; failed: `deletion_failed`. +- Failure message from `/data/attributes/cleanup_error`. +- Failure hint names `supabase warehouse teardowns get [--operation-id ] --remote=`. diff --git a/apps/cli/src/commands/api/generated.ts b/apps/cli/src/commands/api/generated.ts new file mode 100644 index 0000000000..750afc0ba7 --- /dev/null +++ b/apps/cli/src/commands/api/generated.ts @@ -0,0 +1,759 @@ +// Generated by scripts/generate-api-commands.ts. Do not edit. +import type { ApiCommandEntry, ApiPollTarget } from "./api-command.model.ts"; + +export const apiCommands = [ + { + command: ["warehouse", "connection"], + operationId: "v2-get-warehouse-connection", + definition: "v2GetWarehouseConnection", + summary: "Get Warehouse Flight SQL connection details", + description: + "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: `usql -W 'flightsql://postgres@:443?tls=enabled'`.", + readOnly: true, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + ], + }, + { + command: ["warehouse", "disable"], + operationId: "v2-disable-warehouse", + definition: "v2DisableWarehouse", + summary: "Disable Warehouse replication and access", + description: + "Stops replication and removes the Warehouse publication, FDW and dependent foreign tables, reader group, catalog access and query routing asynchronously. Stored Warehouse data is retained by default. Set delete_data=true to permanently delete the managed catalog schema and dedicated Storage bucket; destination SQL and Storage write permissions are also required. Legacy shared buckets and source Postgres tables are preserved. Reader memberships are not restored on re-enablement. Safe retries return the existing cleanup identity; changing an in-progress data policy returns a conflict. Poll the linked teardown for completion or partial cleanup failures.", + readOnly: false, + confirmDescription: true, + flags: [ + { + name: "delete-data", + type: "boolean", + repeatable: false, + required: false, + description: + "Permanently delete managed Warehouse data. Defaults to false (retain data). Source Postgres tables and legacy shared buckets are preserved.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "query", + name: "delete_data", + source: "flag", + flag: "delete-data", + }, + ], + wait: { + read: "v2-get-warehouse-teardown", + params: { + operation_id: "/data/id", + }, + status: "/data/attributes/lifecycle_status", + succeeded: ["disabled"], + failed: ["deletion_failed"], + error: "/data/attributes/cleanup_error", + }, + }, + { + command: ["warehouse", "enable"], + operationId: "v2-enable-warehouse", + definition: "v2EnableWarehouse", + summary: "Enable Warehouse replication", + description: + "Enables replication for the currently eligible tables in a schema, or the named tables in that schema. Resolves source identities under the mutation lock without a preview or revision. Repeating the same selection is safe; a different existing selection is rejected. Schema selection excludes future tables; selected partition roots include future partitions. Acceptance does not imply completed synchronization.", + readOnly: false, + body: { + contentType: "application/json", + type: "warehouse_setup", + }, + flags: [ + { + name: "warehouse-region", + type: "string", + repeatable: false, + required: false, + description: + "Optional Warehouse compute region, independent of the source and catalog regions. Defaults to the existing assignment, or ap-southeast-1 in staging and eu-west-1 in production for a new assignment. DNS routing requires a registered cluster in that environment. Unsupported regions and changes to an existing assignment are rejected. Ignored when targets is empty.", + }, + { + name: "destination-project-ref", + type: "string", + repeatable: false, + required: false, + description: + "Supabase project to use for both the DuckLake PostgreSQL catalog and Supabase Storage. Defaults to this project on first setup and to the configured destination on later requests. The destination must be active and healthy, and another project requires SQL and Storage admin write permissions. An existing destination cannot be changed through setup. Ignored when targets is empty.", + }, + { + name: "install-fdw", + type: "boolean", + repeatable: false, + required: false, + description: + "Whether to configure and install the Warehouse FDW in the project database. Defaults to false. Ignored when targets is empty.", + }, + { + name: "schema", + type: "string", + repeatable: false, + required: true, + description: + "Source PostgreSQL schema. Without tables, selects its currently eligible tables only.", + }, + { + name: "table", + type: "string", + repeatable: true, + required: false, + description: + "Table names in schema. Omit to select the currently eligible tables in that schema.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "body", + name: "warehouse_region", + pointer: "/data/attributes/warehouse_region", + source: "flag", + flag: "warehouse-region", + }, + { + location: "body", + name: "destination_project_ref", + pointer: "/data/attributes/destination_project_ref", + source: "flag", + flag: "destination-project-ref", + }, + { + location: "body", + name: "install_fdw", + pointer: "/data/attributes/install_fdw", + source: "flag", + flag: "install-fdw", + }, + { + location: "body", + name: "schema", + pointer: "/data/attributes/schema", + source: "flag", + flag: "schema", + }, + { + location: "body", + name: "tables", + pointer: "/data/attributes/tables", + source: "flag", + flag: "table", + }, + ], + wait: { + read: "v2-get-warehouse-setup", + params: { + selection_id: "/data/attributes/selection_id", + }, + status: "/data/attributes/status", + succeeded: ["succeeded"], + failed: ["failed"], + error: "/data/attributes/status_error", + }, + }, + { + command: ["warehouse", "inspect", "capacity"], + operationId: "v2-get-warehouse-capacity", + definition: "v2GetWarehouseCapacity", + summary: "Inspect Warehouse capacity diagnostics", + description: + "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use `--since` or specify both `--from` and `--to`; the default is the last 30 minutes.\n\nEach measurement includes its definition, unit, aggregation, requested and effective ranges, `rate_window_seconds`, source-sample freshness, availability, coverage, and full series with dimension labels such as `reason`, `kind`, and `result`.\n\nExecutor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or `null`; they do not establish healthy or idle capacity.\n\nPoint timestamps are evaluation times; `last_sample_at` is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range.\n\nEach request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.", + readOnly: true, + flags: [ + { + name: "attributes", + type: "string", + repeatable: false, + required: false, + description: + "Up to eight distinct measurements. Defaults to `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_p95`, `activation_duration_p95`. Supply a comma-separated list. Allowed measurements: `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_mean`, `assignment_wait_p95`, `activation_rate`, `activation_duration_mean`, `activation_duration_p95`.", + }, + { + name: "from", + type: "string", + repeatable: false, + required: false, + description: + "Range start as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, within the last 30 days. Requires `--to`; cannot be combined with `--since`.", + }, + { + name: "interval", + type: "string", + choices: ["10m", "1d", "1h", "1m", "30m", "5m"], + repeatable: false, + required: false, + description: + "Defaults to `1m`. The effective step increases to stay within 1,441 points per series. Rate and latency windows are at least `5m`.", + }, + { + name: "since", + type: "string", + repeatable: false, + required: false, + description: + "Look back from server time, for example `30m`, `2h`, or `1d`. Defaults to `30m` when `--from`/`--to` are omitted. Maximum `30d`. Cannot be combined with `--from`/`--to`.", + }, + { + name: "to", + type: "string", + repeatable: false, + required: false, + description: + "Range end as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, no later than server time. Requires `--from`; cannot be combined with `--since`. The service tolerates up to 60 seconds of request delay or clock skew.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "query", + name: "attributes", + source: "flag", + flag: "attributes", + }, + { + location: "query", + name: "from", + source: "flag", + flag: "from", + }, + { + location: "query", + name: "interval", + source: "flag", + flag: "interval", + }, + { + location: "query", + name: "since", + source: "flag", + flag: "since", + }, + { + location: "query", + name: "to", + source: "flag", + flag: "to", + }, + ], + }, + { + command: ["warehouse", "inspect", "query-stats"], + operationId: "v2-get-warehouse-query-stats", + definition: "v2GetWarehouseQueryStats", + summary: "Inspect Warehouse workload query statistics", + description: + "Returns aggregate workload measurements over a bounded time range, using the project’s stored Warehouse placement. Use since or both from and to; the default is the last 30 minutes. Each measurement includes its definition, unit, aggregation, requested and effective ranges, rate_window_seconds, source-sample freshness, availability, and full series with dimension labels. Point timestamps are evaluation times; last_sample_at is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. Do not average interval percentiles into a whole-range percentile. Executor invocations include metadata/schema work and are not counts of user SQL statements. Timeouts are included in errors; cancellation is separate. Missing and unavailable values remain null. No query history, individual-query attribution, raw queries, or backend selectors are exposed. Each request returns up to eight measurements. A failure of one measurement does not discard the other results.", + readOnly: true, + flags: [ + { + name: "attributes", + type: "string", + repeatable: false, + required: false, + description: + "Up to eight distinct workload measurements. Defaults to invocation rate, latency p50/p95/p99, error rate, and timeout rate. Supply a comma-separated list. Allowed measurements: query_rate, query_error_rate, query_timeout_rate, query_canceled_rate, query_duration_mean, query_duration_p50, query_duration_p95, query_duration_p99, duckdb_duration_mean, rpc_rate, rpc_duration_mean, rpc_duration_p95.", + }, + { + name: "from", + type: "string", + repeatable: false, + required: false, + description: + "Range start as an ISO timestamp, within the last 30 days. Requires to; cannot be combined with since.", + }, + { + name: "interval", + type: "string", + choices: ["10m", "1d", "1h", "1m", "30m", "5m"], + repeatable: false, + required: false, + description: + "Defaults to 1m. The effective step increases to stay within 1441 points per series. Rate and latency windows are at least 5m.", + }, + { + name: "since", + type: "string", + repeatable: false, + required: false, + description: + "Look back from server time, for example 30m, 2h, or 1d. Defaults to 30m when from/to are omitted. Maximum 30d. Cannot be combined with from/to.", + }, + { + name: "to", + type: "string", + repeatable: false, + required: false, + description: + "Range end as an ISO timestamp, no later than server time. Requires from; cannot be combined with since. The service tolerates up to 60 seconds of request delay or clock skew.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "query", + name: "attributes", + source: "flag", + flag: "attributes", + }, + { + location: "query", + name: "from", + source: "flag", + flag: "from", + }, + { + location: "query", + name: "interval", + source: "flag", + flag: "interval", + }, + { + location: "query", + name: "since", + source: "flag", + flag: "since", + }, + { + location: "query", + name: "to", + source: "flag", + flag: "to", + }, + ], + }, + { + command: ["warehouse", "replication", "add"], + operationId: "v2-add-warehouse-replication", + definition: "v2AddWarehouseReplication", + summary: "Add source tables to Warehouse replication", + description: + "Adds one eligible source table or the currently eligible tables in a schema to an enabled Warehouse. Existing selections and layouts are preserved; already-selected tables are unchanged. Schema selection excludes future tables, except future partitions of selected partition roots. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline remains stopped and requires an explicit start before copying. Initial copy adds source reads; duration is unknown. Unsafe reattachment of retained data is rejected. The response describes configuration and restart acceptance, not completed copy or streaming. Failures may have partial effects; inspect table and pipeline state before retrying.", + readOnly: false, + confirmDescription: true, + body: { + contentType: "application/json", + type: "warehouse_replication_change", + }, + flags: [ + { + name: "schema", + type: "string", + repeatable: false, + required: true, + description: "Literal source PostgreSQL schema. Omit table to select its current tables.", + }, + { + name: "table", + type: "string", + repeatable: false, + required: false, + description: "Literal source table name. Omit to select the schema.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "body", + name: "schema", + pointer: "/data/attributes/schema", + source: "flag", + flag: "schema", + }, + { + location: "body", + name: "table", + pointer: "/data/attributes/table", + source: "flag", + flag: "table", + }, + ], + }, + { + command: ["warehouse", "replication", "remove"], + operationId: "v2-remove-warehouse-replication", + definition: "v2RemoveWarehouseReplication", + summary: "Remove source tables from Warehouse replication", + description: + "Removes one selected source table or all selected tables in a schema as a batch. Source PostgreSQL rows and existing Warehouse data are retained. The retained copy stops receiving updates. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline stays stopped. Removing an unselected target is unchanged. Removing the last target leaves Warehouse enabled with an empty selection. Publication changes and restart acceptance do not establish observed exclusion by active replication. Failures may have partial effects; inspect the selection and pipeline before retrying.", + readOnly: false, + confirmDescription: true, + body: { + contentType: "application/json", + type: "warehouse_replication_change", + }, + flags: [ + { + name: "schema", + type: "string", + repeatable: false, + required: true, + description: "Literal source PostgreSQL schema. Omit table to select its current tables.", + }, + { + name: "table", + type: "string", + repeatable: false, + required: false, + description: "Literal source table name. Omit to select the schema.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "body", + name: "schema", + pointer: "/data/attributes/schema", + source: "flag", + flag: "schema", + }, + { + location: "body", + name: "table", + pointer: "/data/attributes/table", + source: "flag", + flag: "table", + }, + ], + }, + { + command: ["warehouse", "replication", "restart"], + operationId: "v2-restart-warehouse-replication", + definition: "v2RestartWarehouseReplication", + summary: "Start or restart Warehouse replication", + description: + "Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response.", + readOnly: false, + confirmDescription: true, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + ], + }, + { + command: ["warehouse", "replication", "resync"], + operationId: "v2-resync-warehouse-replication", + definition: "v2ResyncWarehouseReplication", + summary: "Reset and rebuild one Warehouse table", + description: + "Resets replication for one selected source table using its currently saved layout. Source rows, saved layouts and completed replication state for unrelated tables are preserved. In-progress initial copies of other tables may restart from scratch. The Warehouse copy is deleted and rebuilt when replication resumes; table reads may be unavailable, freshness can lag, and the source incurs additional reads. Stopping and restarting the pipeline interrupts replication for other tables. Duration is unknown. The pipeline must be started and initial sync enabled for the table before the reset. The immediate response retains ETL reset states; it does not establish recopy completion. Inspect warehouse tables get and warehouse status separately. Do not automatically retry an uncertain response: repeating this request may reset the table again. There is no server-side preview, revision check, idempotency key or operation polling.", + readOnly: false, + confirmDescription: true, + body: { + contentType: "application/json", + type: "warehouse_replication_resync", + }, + flags: [ + { + name: "schema", + type: "string", + repeatable: false, + required: true, + description: "Literal source PostgreSQL schema of the table.", + }, + { + name: "table", + type: "string", + repeatable: false, + required: true, + description: "Literal name of the single source table to reset and recopy.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "body", + name: "schema", + pointer: "/data/attributes/schema", + source: "flag", + flag: "schema", + }, + { + location: "body", + name: "table", + pointer: "/data/attributes/table", + source: "flag", + flag: "table", + }, + ], + }, + { + command: ["warehouse", "status"], + operationId: "v2-get-warehouse-status", + definition: "v2GetWarehouseStatus", + summary: "Get consolidated Warehouse status and capabilities", + description: + "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection.", + readOnly: true, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + ], + }, + { + command: ["warehouse", "tables", "get"], + operationId: "v2-get-warehouse-table", + definition: "v2GetWarehouseTable", + summary: "Get a table replicated to Warehouse", + description: + "Returns one source table selected for Warehouse replication by its source OID, from the same observations and with the same status and freshness attributes as the Warehouse tables list. Returns 404 when the table is not selected for replication, including when Warehouse is not set up, its publication is missing, or it is being disabled.", + readOnly: true, + argument: { + name: "table-id", + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "path", + name: "table_id", + source: "argument", + argument: "table-id", + }, + ], + }, + { + command: ["warehouse", "tables", "layout", "get"], + operationId: "v2-get-warehouse-table-layout", + definition: "v2GetWarehouseTableLayout", + summary: "Get the layout of a table replicated to Warehouse", + description: + "Returns the sorting and partitioning rules saved for one replicated table, by source OID, beside the layout the DuckLake catalog records for it. The two are reported separately and can differ: the replicator applies saved rules when it starts and then hourly, and a stopped pipeline applies them on its next start. observation_status reports whether the catalog was read; desired rules are returned even when it was not. A catalog layout governs files written after it changes and does not establish that existing files are sorted or partitioned. Returns 404 when the table is not replicated, including when Warehouse is not set up, is being disabled or failed to clean up.", + readOnly: true, + argument: { + name: "table-id", + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "path", + name: "table_id", + source: "argument", + argument: "table-id", + }, + ], + }, + { + command: ["warehouse", "tables", "layout", "update"], + operationId: "v2-update-warehouse-table-layout", + definition: "v2UpdateWarehouseTableLayout", + summary: "Update the layout of a table replicated to Warehouse", + description: + "Updates saved sorting and partitioning rules for one source table object identifier (OID). Provide sort_by or partition_by; empty and reset-only patches are rejected. Omitted settings are preserved. Null makes a setting unmanaged. An empty partition list clears partitioning, and the none sort selector clears sorting. The backend validates the source schema and preserves other tables. When the layout changes, an active pipeline is restarted. A stopped pipeline stays stopped. reset_table defaults to false, preserving historical files and replication progress. When the layout changes, --reset-table resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never restarts the pipeline or resets the table. Acceptance and application_status report orchestration. Run warehouse tables layout get to compare the desired and observed rules. Run warehouse tables get to check table replication status. These reads do not establish completion of this specific update. There is no revision, idempotency, resolved preview, or durable operation contract. A failed update can leave partial effects, including a completed reset. Inspect the saved layout, pipeline, and table state before retrying.", + readOnly: false, + confirmDescription: true, + examples: [ + { + command: + 'supabase warehouse tables layout update --partition-by \'[{"column":"event_at","transform":{"kind":"day"}}]\' --sort-by \'{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}\'', + description: + "Partition new files by event day and sort within files; preserve historical files.", + }, + { + command: + 'supabase warehouse tables layout update --partition-by \'[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]\' --dry-run', + description: "Preview eight hash buckets locally without changing the Warehouse.", + }, + { + command: + "supabase warehouse tables layout update --partition-by '[]' --sort-by '{\"kind\":\"none\"}'", + description: "Clear partitioning and sorting for future writes.", + }, + { + command: + "supabase warehouse tables layout update --partition-by 'null' --sort-by 'null'", + description: "Stop managing both settings; omitted flags preserve their saved values.", + }, + ], + body: { + contentType: "application/json", + type: "warehouse_table_layout", + }, + argument: { + name: "table-id", + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }, + flags: [ + { + name: "partition-by", + type: "json", + repeatable: false, + required: false, + description: + 'Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{"column":"event_at","transform":{"kind":"day"}}]`. Bucket example: `[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.', + }, + { + name: "reset-table", + type: "boolean", + repeatable: false, + required: false, + description: + "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", + }, + { + name: "sort-by", + type: "json", + repeatable: false, + required: false, + description: + 'Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}`. Sort by the primary key with `{"kind":"primary_key"}` or clear sorting with `{"kind":"none"}`.', + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "path", + name: "table_id", + source: "argument", + argument: "table-id", + }, + { + location: "body", + name: "partition_by", + pointer: "/data/attributes/partition_by", + source: "flag", + flag: "partition-by", + }, + { + location: "body", + name: "reset_table", + pointer: "/data/attributes/reset_table", + source: "flag", + flag: "reset-table", + }, + { + location: "body", + name: "sort_by", + pointer: "/data/attributes/sort_by", + source: "flag", + flag: "sort-by", + }, + ], + }, + { + command: ["warehouse", "tables", "list"], + operationId: "v2-list-warehouse-tables", + definition: "v2ListWarehouseTables", + summary: "List tables replicated to Warehouse", + description: + "Lists the source tables selected for Warehouse replication with their replication status and freshness, from the same observations as the Warehouse status. Freshness comes from the replication slot that carries each table: its own sync slot until it follows changes, then the pipeline apply slot; one slot never stands in for the other. lag_ms is that slot's flush lag. Postgres reports no lag time for a caught-up slot without new WAL, so lag_ms can be null while replication_feedback.flush_lag_bytes is 0; neither is ever filled with zero when unknown. observed_at is when the API read the replication state, not when data last synchronized. A stopped, failed or unreadable pipeline reports its tables as stopped or unknown rather than live, and keeps each table's last recorded state. Returns an empty list when Warehouse is not set up, its publication is missing, or it is being disabled or failed to clean up.", + readOnly: true, + flags: [], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + ], + }, + { + command: ["warehouse", "teardowns", "get"], + operationId: "v2-get-warehouse-teardown", + definition: "v2GetWarehouseTeardown", + summary: "Get Warehouse cleanup status", + description: + "Reads the current durable cleanup state without contacting ETL or inspecting the FDW. Disabling means cleanup is in progress; disabled means cleanup completed; deletion_failed means cleanup may be partial. The original data policy and failure reason remain available. Optionally supply operation_id to observe a specific disable attempt. Returns a conflict if no cleanup state is available or the supplied identity does not match the current operation.", + readOnly: true, + flags: [ + { + name: "operation-id", + type: "string", + repeatable: false, + required: false, + description: + "Optional cleanup operation identity returned by disable. Omit to read the current cleanup; when supplied, a different current operation returns a conflict.", + }, + ], + bindings: [ + { + location: "path", + name: "ref", + source: "target", + }, + { + location: "query", + name: "operation_id", + source: "flag", + flag: "operation-id", + }, + ], + wait: { + read: "v2-get-warehouse-teardown", + params: {}, + status: "/data/attributes/lifecycle_status", + succeeded: ["disabled"], + failed: ["deletion_failed"], + error: "/data/attributes/cleanup_error", + }, + }, +] as const satisfies readonly ApiCommandEntry[]; + +export const apiPollTargets = [ + { + operationId: "v2-get-warehouse-setup", + definition: "v2GetWarehouseSetup", + summary: "Get Warehouse initial synchronization status", + inspect: "v2-get-warehouse-status", + }, +] as const satisfies readonly ApiPollTarget[]; diff --git a/apps/cli/src/commands/api/runtime.ts b/apps/cli/src/commands/api/runtime.ts new file mode 100644 index 0000000000..4a8f78e457 --- /dev/null +++ b/apps/cli/src/commands/api/runtime.ts @@ -0,0 +1,412 @@ +import { Cause, Effect, Exit, Layer, Option } from "effect"; +import { Argument, Command, Flag } from "effect/cli"; + +import { CommandPlatformApiFactory } from "../../auth/command-platform-api-factory.service.ts"; +import { ApiCommandUsageError } from "../../command-internal/command-errors/api-command.errors.ts"; +import { withPermissions } from "../../command-internal/command-permissions/command-permissions.annotation.ts"; +import { + compose, + type OperationEntry, + withCondition, +} from "../../command-internal/command-permissions/model.ts"; +import { parseDuration } from "../../command-internal/duration.ts"; +import { GLOBAL_OUTPUT_FORMATS, OutputFlag } from "../../command-internal/global-flags.ts"; +import { requireHostedMutationConsent } from "../../command-internal/hosted-consent/hosted-consent.ts"; +import { unsupportedOutputFlagMessage } from "../../command-internal/output-formats.ts"; +import { identityStitchLayer } from "../../command-internal/identity-stitch.ts"; +import { lazyManagementApiRuntimeLayer } from "../../command-internal/management-api-runtime.layer.ts"; +import { branchResolution } from "../../command-internal/target/branch-resolution.ts"; +import { resolveProjectTarget } from "../../command-internal/target/resolve-project-target.ts"; +import { projectTargetFlags } from "../../command-internal/target/target-flags.ts"; +import { withTargetPolicy } from "../../command-internal/target/target-policy.ts"; +import { projectRefPicker } from "../../config/project-ref.layer.ts"; +import { Output } from "../../shared/output/output.service.ts"; +import { stdinLayer } from "../../shared/runtime/stdin.layer.ts"; +import { withCommandTelemetry } from "../../telemetry/command-telemetry.ts"; +import { LinkedProjectCache } from "../../telemetry/linked-project-cache.service.ts"; +import { linkedProjectCache } from "../../telemetry/linked-project-cache.layer.ts"; +import { TelemetryState } from "../../telemetry/telemetry-state.service.ts"; +import { + linkedReadInput, + sendApiRequest, + waitForOperation, + writeApiResponse, + writeDryRun, +} from "./api-command-execute.ts"; +import { type ApiFlagLocation, apiFlag } from "./api-command-flags.ts"; +import { type ApiNoun, nouns } from "./api-command-policy.ts"; +import { singleLine } from "./api-command.format.ts"; +import { + assembleInput, + consentDetails, + decodeInput, + previewRequest, + readBodyOverride, +} from "./api-command-request.ts"; +import type { + ApiCommandEntry, + ApiCommandFlag, + ApiCommandWait, + ApiPollRead, +} from "./api-command.model.ts"; +import { apiCommands, apiPollTargets } from "./generated.ts"; + +const DEFAULT_WAIT_TIMEOUT = "10m"; +const NANOSECONDS_PER_MILLISECOND = 1_000_000; + +/** A command's `--wait`: the wait declared on its entry and the entry of the operation it polls. */ +interface ResolvedWait { + readonly wait: ApiCommandWait; + readonly readEntry: ApiPollRead; + readonly statusEntry: ApiCommandEntry; +} + +const resolveWait = (entry: ApiCommandEntry): ResolvedWait | undefined => { + const { wait } = entry; + if (wait === undefined) return undefined; + const publicRead = apiCommands.find((candidate) => candidate.operationId === wait.read); + if (publicRead !== undefined) return { wait, readEntry: publicRead, statusEntry: publicRead }; + const hidden = apiPollTargets.find((candidate) => candidate.operationId === wait.read); + const inspect = apiCommands.find((candidate) => candidate.operationId === hidden?.inspect); + return hidden === undefined || inspect === undefined + ? undefined + : { wait, readEntry: hidden, statusEntry: inspect }; +}; + +const flagLocation = (entry: ApiCommandEntry, flag: ApiCommandFlag): ApiFlagLocation => { + for (const binding of entry.bindings) { + if (binding.source === "flag" && binding.flag === flag.name) return binding.location; + } + return "body"; +}; + +/** The config of a generated command: target flags, runtime flags, one flag per API field and the positional. */ +const flagConfig = (entry: ApiCommandEntry, waitable: boolean) => ({ + ...projectTargetFlags(), + ...(entry.argument === undefined + ? {} + : { + argument: Argument.String(entry.argument.name).pipe( + Argument.withDescription(entry.argument.description ?? `Set ${entry.argument.name}.`), + ), + }), + ...(entry.body === undefined + ? {} + : { + body: Flag.optional( + Flag.String("body").pipe( + Flag.withDescription( + "Whole request body as JSON; other flags replace fields at their own location.", + ), + ), + ), + file: Flag.optional( + Flag.String("file").pipe( + Flag.withDescription("Read the whole request body from a JSON file, or - for stdin."), + ), + ), + }), + dryRun: Flag.Boolean("dry-run").pipe( + Flag.withDescription("Print the request instead of sending it."), + Flag.withDefault(false), + ), + ...(!waitable + ? {} + : { + wait: Flag.Boolean("wait").pipe( + Flag.withDescription("Wait until the operation reaches a final status."), + Flag.withDefault(false), + ), + timeout: Flag.String("timeout").pipe( + Flag.withDescription("How long --wait polls, as a duration such as 90s or 10m."), + Flag.withDefault(DEFAULT_WAIT_TIMEOUT), + ), + }), + api: Object.fromEntries( + entry.flags.map((flag) => [flag.name, apiFlag(flag, flagLocation(entry, flag))]), + ), +}); + +const parseTimeoutMillis = (value: string) => + Effect.try({ + try: () => parseDuration(value) / NANOSECONDS_PER_MILLISECOND, + catch: () => + new ApiCommandUsageError({ + message: `--timeout ${value} is not a valid duration.`, + suggestion: "Use a duration such as 90s or 10m.", + }), + }).pipe( + Effect.filterOrFail( + (millis) => millis > 0, + () => + new ApiCommandUsageError({ + message: `--timeout ${value} must be greater than zero.`, + suggestion: "Use a duration such as 90s or 10m.", + }), + ), + ); + +const summaryText = (entry: Pick): string => + entry.summary.replace(/\.$/, ""); + +/** + * Runs `use` under an output task, handing it the task's message updater; the task is cleared on + * success and marked failed or cancelled otherwise. + */ +const withTask = ( + message: string, + use: (update: (message: string) => Effect.Effect) => Effect.Effect, +) => + Effect.gen(function* () { + const output = yield* Output; + const task = yield* output.task(message); + return yield* use(task.message).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? task.clear + : Cause.hasInterruptsOnly(exit.cause) + ? task.cancel() + : task.fail(), + ), + ); + }); + +/** The parsed flags of a generated command. */ +interface ApiCommandFlags { + readonly remote: Parameters[0]["remote"]; + readonly projectRef: Parameters[0]["projectRef"]; + readonly argument?: string; + readonly body?: Option.Option; + readonly file?: Option.Option; + readonly dryRun: boolean; + readonly wait?: boolean; + readonly timeout?: string; + readonly api: Parameters[2]; +} + +/** Runs one generated command: assemble and validate the request, consent, send, optionally wait, print. */ +const handle = Effect.fn("api-command.run")(function* ( + entry: ApiCommandEntry, + resolved: ResolvedWait | undefined, + flags: ApiCommandFlags, +) { + yield* Effect.annotateCurrentSpan("operation.id", entry.operationId); + const telemetryState = yield* TelemetryState; + const cache = yield* LinkedProjectCache; + const output = yield* Output; + const outputFlag = yield* OutputFlag; + const format = output.format; + yield* Effect.annotateCurrentSpan("output.presentation", format); + yield* Effect.gen(function* () { + if (Option.isSome(outputFlag)) { + return yield* new ApiCommandUsageError({ + message: unsupportedOutputFlagMessage(entry.command.join(" ")), + }); + } + const timeoutMillis = + flags.timeout === undefined ? 0 : yield* parseTimeoutMillis(flags.timeout); + const ref = yield* resolveProjectTarget(flags); + yield* Effect.gen(function* () { + const waiting = resolved !== undefined && flags.wait === true; + const override = yield* readBodyOverride({ + body: flags.body ?? Option.none(), + file: flags.file ?? Option.none(), + }); + const input = yield* assembleInput(entry, ref, flags.api, override, flags.argument); + const decoded = yield* decodeInput(entry, input); + + if (flags.dryRun) { + yield* Effect.annotateCurrentSpan("run.outcome", "dry_run"); + return yield* writeDryRun(previewRequest(entry, decoded), format); + } + if (!entry.readOnly) { + yield* requireHostedMutationConsent({ + action: summaryText(entry), + details: [ + ...(entry.confirmDescription && entry.description ? [entry.description] : []), + ...consentDetails(entry, decoded), + ], + }); + } + const api = yield* (yield* CommandPlatformApiFactory).make; + + if (waiting) { + // A read that polls itself already returns the shape it prints; any other wait prints + // the response the change was accepted with, once the polled operation has succeeded. + const selfPolling = resolved.readEntry.operationId === entry.operationId; + const accepted = selfPolling + ? undefined + : yield* withTask(summaryText(entry), () => sendApiRequest(api, entry, decoded)); + const readInput = + accepted === undefined + ? input + : yield* linkedReadInput({ + wait: resolved.wait, + changedOperationId: entry.operationId, + ref, + changed: accepted, + }); + const polling = summaryText(resolved.readEntry); + const settled = yield* withTask(polling, (update) => + waitForOperation({ + api, + wait: resolved.wait, + readEntry: resolved.readEntry, + statusEntry: resolved.statusEntry, + readInput, + ref, + timeoutMillis, + onPoll: (status) => + update(status === undefined ? polling : `${polling} (status: ${singleLine(status)})`), + }), + ); + yield* Effect.annotateCurrentSpan("run.outcome", "waited"); + return yield* writeApiResponse(accepted ?? settled, format); + } + const response = yield* withTask(summaryText(entry), () => + sendApiRequest(api, entry, decoded), + ); + yield* Effect.annotateCurrentSpan("run.outcome", "sent"); + return yield* writeApiResponse(response, format); + }).pipe(Effect.ensuring(flags.dryRun ? Effect.void : cache.cache(ref))); + }).pipe(Effect.ensuring(telemetryState.flush)); +}); + +const exampleFor = (entry: ApiCommandEntry): string => { + const required = entry.flags + .filter((flag) => flag.required) + .map((flag) => `--${flag.name}${flag.type === "boolean" ? "" : ` <${flag.name}>`}`); + const positional = entry.argument === undefined ? [] : [`<${entry.argument.name}>`]; + const requiresBodyFlag = entry.bindings.some( + (binding) => + binding.location === "body" && + binding.source === "flag" && + entry.flags.some((flag) => flag.required && flag.name === binding.flag), + ); + const body = entry.body === undefined || requiresBodyFlag ? [] : ["--file "]; + return ["supabase", ...entry.command, ...positional, ...required, ...body].join(" "); +}; + +// `--dry-run` returns before the API client exists, so the command, the poll and the cache lookup +// run only without it. +const sendsRequests = { flag: "dry-run", is: false } as const; + +const permissionsOf = (entry: ApiCommandEntry, resolved: ResolvedWait | undefined) => { + const polled = resolved?.readEntry.operationId; + const operations: ReadonlyArray = [ + { operationId: entry.operationId, kind: "required", when: [sendsRequests] }, + ...(polled === undefined || polled === entry.operationId + ? [] + : [ + { + operationId: polled, + kind: "required" as const, + when: [sendsRequests, { flag: "wait", is: true }], + }, + ]), + ]; + const noApiEffectFlags = [ + ...(entry.body === undefined ? [] : ["body", "file"]), + ...(resolved === undefined ? [] : ["timeout"]), + ...(polled === entry.operationId ? ["wait"] : []), + ...entry.flags.map((flag) => flag.name), + ]; + return compose( + { operations, noApiEffectFlags }, + projectRefPicker, + withCondition(linkedProjectCache, sendsRequests), + branchResolution, + ); +}; + +const leafOf = (entry: ApiCommandEntry) => { + const verb = entry.command[entry.command.length - 1] ?? entry.operationId; + const resolved = resolveWait(entry); + const config = flagConfig(entry, resolved !== undefined); + return Command.make(verb, config).pipe( + Command.withDescription(entry.description ?? entry.summary), + Command.withShortDescription(`${entry.summary} (experimental)`), + Command.withExamples([ + { command: exampleFor(entry), description: entry.summary }, + ...(entry.examples ?? []), + ]), + withPermissions(permissionsOf(entry, resolved)), + Command.withHandler((flags) => { + const { api: _generated, argument: _argument, ...recorded } = flags; + return handle(entry, resolved, flags).pipe( + withCommandTelemetry({ flags: recorded, outputFormats: GLOBAL_OUTPUT_FORMATS }), + ); + }), + // `stdinLayer`: `--file -` reads the request body from piped stdin. `identityStitchLayer` is + // shared by the lazy runtime and the post-run telemetry. + Command.provide( + Layer.mergeAll( + lazyManagementApiRuntimeLayer(entry.command).pipe(Layer.provide(identityStitchLayer)), + identityStitchLayer, + stdinLayer, + ), + ), + withTargetPolicy({ group: "hosted", consent: entry.readOnly ? "none" : "no" }), + ); +}; + +type ApiLeaf = ReturnType; + +/** A generated group: it fails and requires what its generated leaves do. */ +type ApiGroup = Command.Command, Command.Services>; + +const startsWith = (command: ReadonlyArray, prefix: ReadonlyArray): boolean => + prefix.every((word, index) => command[index] === word); + +const leafCache = new WeakMap(); + +const cachedLeaf = (entry: ApiCommandEntry): ApiLeaf => { + const cached = leafCache.get(entry); + if (cached !== undefined) return cached; + const leaf = leafOf(entry); + leafCache.set(entry, leaf); + return leaf; +}; + +const groupDescription = (path: ReadonlyArray, noun: ApiNoun): string | undefined => + path.length === 1 ? noun.description : noun.groups?.[path.slice(1).join(".")]; + +/** The group at `path`, holding the generated commands below it. */ +const groupAt = (path: ReadonlyArray, noun: ApiNoun): ApiGroup => { + const name = path[path.length - 1] ?? ""; + const under = apiCommands.filter((entry) => startsWith(entry.command, path)); + const childNames = new Set( + under.flatMap((entry) => + entry.command.length > path.length + 1 + ? entry.command.slice(path.length, path.length + 1) + : [], + ), + ); + const leaves = under + .filter((entry) => entry.command.length === path.length + 1) + .map((entry) => cachedLeaf(entry)); + const groups = [...childNames].map((child) => groupAt([...path, child], noun)); + const description = `${groupDescription(path, noun) ?? name} (experimental)`; + return Command.make(name).pipe( + Command.withDescription(description), + Command.withShortDescription(description), + Command.withSubcommands([...leaves, ...groups]), + ); +}; + +/** + * `handWritten` with the generated Management API commands of every enabled noun added as a new + * group, in alphabetical position. + */ +export const withApiCommands = >( + handWritten: C, + enabledFeatures: ReadonlyArray, +): ReadonlyArray => { + const merged: Array = [...handWritten]; + for (const [name, noun] of Object.entries(nouns)) { + if (!enabledFeatures.includes(noun.experimental)) continue; + const position = merged.findIndex((command) => command.name > name); + merged.splice(position < 0 ? merged.length : position, 0, groupAt([name], noun)); + } + return merged; +}; diff --git a/apps/cli/src/commands/db/diff/diff.layers.ts b/apps/cli/src/commands/db/diff/diff.layers.ts index b4a6774255..bc5aee8556 100644 --- a/apps/cli/src/commands/db/diff/diff.layers.ts +++ b/apps/cli/src/commands/db/diff/diff.layers.ts @@ -2,7 +2,7 @@ import { Layer } from "effect"; import { commandRuntimeLayer } from "../../../shared/runtime/command-runtime.layer.ts"; import { identityStitchLayer } from "../../../command-internal/identity-stitch.ts"; -import { linkedDbResolverRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; import { telemetryStateLayer } from "../../../telemetry/telemetry-state.layer.ts"; import { migraRuntimeLayer, @@ -16,6 +16,6 @@ export const dbDiffRuntimeLayer = Layer.mergeAll( migraRuntimeLayer, identityStitchLayer, telemetryStateLayer, - linkedDbResolverRuntimeLayer(["db", "diff"]).pipe(Layer.provide(identityStitchLayer)), + lazyManagementApiRuntimeLayer(["db", "diff"]).pipe(Layer.provide(identityStitchLayer)), commandRuntimeLayer(["db", "diff"]), ); diff --git a/apps/cli/src/commands/db/pull/pull.layers.ts b/apps/cli/src/commands/db/pull/pull.layers.ts index b482763533..e72ecdcaf3 100644 --- a/apps/cli/src/commands/db/pull/pull.layers.ts +++ b/apps/cli/src/commands/db/pull/pull.layers.ts @@ -2,7 +2,7 @@ import { Layer } from "effect"; import { commandRuntimeLayer } from "../../../shared/runtime/command-runtime.layer.ts"; import { identityStitchLayer } from "../../../command-internal/identity-stitch.ts"; -import { linkedDbResolverRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; import { telemetryStateLayer } from "../../../telemetry/telemetry-state.layer.ts"; import { migraRuntimeLayer, @@ -17,7 +17,7 @@ const dbSchemaPullRuntimeLayer = (command: ReadonlyArray) => migraRuntimeLayer, identityStitchLayer, telemetryStateLayer, - linkedDbResolverRuntimeLayer(command).pipe(Layer.provide(identityStitchLayer)), + lazyManagementApiRuntimeLayer(command).pipe(Layer.provide(identityStitchLayer)), commandRuntimeLayer(command), ); diff --git a/apps/cli/src/commands/db/query/query.layers.ts b/apps/cli/src/commands/db/query/query.layers.ts index d6d2376e1d..969a0627f8 100644 --- a/apps/cli/src/commands/db/query/query.layers.ts +++ b/apps/cli/src/commands/db/query/query.layers.ts @@ -5,7 +5,7 @@ import { dbConfigLayer } from "../../../command-internal/db-config.layer.ts"; import { dbConnectionLayer } from "../../../command-internal/db-connection.sql-pg.layer.ts"; import { debugLoggerLayer } from "../../../command-internal/debug-logger.layer.ts"; import { identityStitchLayer } from "../../../command-internal/identity-stitch.ts"; -import { linkedDbResolverRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../../command-internal/management-api-runtime.layer.ts"; import { telemetryOutputFormatLayer } from "../../../telemetry/telemetry-output-format.layer.ts"; import { aiToolLayer } from "../../../shared/telemetry/ai-tool.layer.ts"; import { randomLayer } from "../../../shared/runtime/random.layer.ts"; @@ -15,7 +15,7 @@ import { stdinLayer } from "../../../shared/runtime/stdin.layer.ts"; * Runtime layer for `supabase db query`. * * The `--local`/`--db-url` paths go through `DbConfigResolver` + `DbConnection` (auth-free). The - * `--linked` path POSTs to the Management API, supplied by `linkedDbResolverRuntimeLayer`, which + * `--linked` path POSTs to the Management API, supplied by `lazyManagementApiRuntimeLayer`, which * exposes the access token lazily so building the runtime resolves no token — `--local`/`--db-url` * run without a login, since only the handler's `--linked` branch checks `getAccessToken`. */ @@ -38,5 +38,5 @@ export const dbQueryRuntimeLayer = Layer.mergeAll( stdinLayer, telemetryOutputFormatLayer, identityStitchLayer, - linkedDbResolverRuntimeLayer(["db", "query"]).pipe(Layer.provide(identityStitchLayer)), + lazyManagementApiRuntimeLayer(["db", "query"]).pipe(Layer.provide(identityStitchLayer)), ); diff --git a/apps/cli/src/commands/db/schema/declarative/generate/generate.layers.ts b/apps/cli/src/commands/db/schema/declarative/generate/generate.layers.ts index 0d67151702..ce76493bf0 100644 --- a/apps/cli/src/commands/db/schema/declarative/generate/generate.layers.ts +++ b/apps/cli/src/commands/db/schema/declarative/generate/generate.layers.ts @@ -3,7 +3,7 @@ import { Layer } from "effect"; import { commandRuntimeLayer } from "../../../../../shared/runtime/command-runtime.layer.ts"; import { stdinLayer } from "../../../../../shared/runtime/stdin.layer.ts"; import { identityStitchLayer } from "../../../../../command-internal/identity-stitch.ts"; -import { linkedDbResolverRuntimeLayer } from "../../../../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../../../../command-internal/management-api-runtime.layer.ts"; import { telemetryStateLayer } from "../../../../../telemetry/telemetry-state.layer.ts"; import { pgDeltaCommandRuntimeLayer, @@ -15,7 +15,7 @@ export const dbSchemaDeclarativeGenerateRuntimeLayer = Layer.mergeAll( pgDeltaCommandRuntimeLayer, identityStitchLayer, telemetryStateLayer, - linkedDbResolverRuntimeLayer(["db", "schema", "declarative", "generate"]).pipe( + lazyManagementApiRuntimeLayer(["db", "schema", "declarative", "generate"]).pipe( Layer.provide(identityStitchLayer), ), commandRuntimeLayer(["db", "schema", "declarative", "generate"]), diff --git a/apps/cli/src/commands/experimental/compute/compute-backend.ts b/apps/cli/src/commands/experimental/compute/compute-backend.ts index 9bda8bf290..3bc76be1b6 100644 --- a/apps/cli/src/commands/experimental/compute/compute-backend.ts +++ b/apps/cli/src/commands/experimental/compute/compute-backend.ts @@ -4,24 +4,17 @@ import { readExperimentalFeatureConfig, resolveExperimentalFeature, } from "../../../shared/config/experimental-feature.ts"; -import { extractCommandPath, hasRootVersionFlag } from "../../../shared/cli/run.ts"; +import { routingArgsFor } from "../../../command-internal/routing-args.ts"; export const resolveComputeEnabled = (input: { readonly args: ReadonlyArray; readonly cwd: string; }): Effect.Effect => Effect.gen(function* () { - const routingArgs = - input.args[0] === "__complete" || input.args[0] === "__completeNoDesc" - ? input.args.slice(0, -1) - : input.args; - if (hasRootVersionFlag(routingArgs)) return false; - const commandPath = extractCommandPath(routingArgs); - const completePath = - commandPath[0] === "__complete" || commandPath[0] === "__completeNoDesc" - ? commandPath.slice(1) - : commandPath; - if (completePath[0] !== undefined && completePath[0] !== "compute") return false; + const routing = routingArgsFor(input.args); + if (routing === undefined) return false; + const { routingArgs, path } = routing; + if (path[0] !== undefined && path[0] !== "compute") return false; return yield* resolveExperimentalFeature({ feature: "compute", configValue: readExperimentalFeatureConfig({ diff --git a/apps/cli/src/commands/logs/logs.command.ts b/apps/cli/src/commands/logs/logs.command.ts index 607c84a643..7b18418ccf 100644 --- a/apps/cli/src/commands/logs/logs.command.ts +++ b/apps/cli/src/commands/logs/logs.command.ts @@ -14,7 +14,7 @@ import { targetFlags } from "../../command-internal/target/target-flags.ts"; import { withTargetPolicy } from "../../command-internal/target/target-policy.ts"; import { withCommandTelemetry } from "../../telemetry/command-telemetry.ts"; import { withJsonErrorHandling } from "../../shared/output/json-error-handling.ts"; -import { linkedDbResolverRuntimeLayer } from "../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../command-internal/management-api-runtime.layer.ts"; import { stdinLayer } from "../../shared/runtime/stdin.layer.ts"; import { stackTargetResolverLayer, stackApiLayer } from "../../command-internal/stack-target.ts"; import { logsTerminalLayer } from "./logs.browser.ts"; @@ -178,7 +178,7 @@ export const logsCommandFor = () => Command.provide(stdinLayer), Command.provide(stackTargetResolverLayer.pipe(Layer.provideMerge(stackApiLayer))), Command.provide( - linkedDbResolverRuntimeLayer(["logs"]).pipe(Layer.provide(identityStitchLayer)), + lazyManagementApiRuntimeLayer(["logs"]).pipe(Layer.provide(identityStitchLayer)), ), withTargetPolicy({ group: "selectable", @@ -210,7 +210,7 @@ export const logsCommandFor = () => ), Command.provide(stackTargetResolverLayer.pipe(Layer.provideMerge(stackApiLayer))), Command.provide( - linkedDbResolverRuntimeLayer(["logs", "sources"]).pipe( + lazyManagementApiRuntimeLayer(["logs", "sources"]).pipe( Layer.provide(identityStitchLayer), ), ), diff --git a/apps/cli/src/commands/migration/migration.layers.ts b/apps/cli/src/commands/migration/migration.layers.ts index 564fc9115f..8a8eacfd2f 100644 --- a/apps/cli/src/commands/migration/migration.layers.ts +++ b/apps/cli/src/commands/migration/migration.layers.ts @@ -9,7 +9,7 @@ import { dbConnectionLayer } from "../../command-internal/db-connection.sql-pg.l import { debugLoggerLayer } from "../../command-internal/debug-logger.layer.ts"; import { dockerRunLayer } from "../../command-internal/docker-run.layer.ts"; import { identityStitchLayer } from "../../command-internal/identity-stitch.ts"; -import { linkedDbResolverRuntimeLayer } from "../../command-internal/management-api-runtime.layer.ts"; +import { lazyManagementApiRuntimeLayer } from "../../command-internal/management-api-runtime.layer.ts"; import { telemetryStateLayer } from "../../telemetry/telemetry-state.layer.ts"; import { stackApiLayer } from "../../command-internal/stack-api.ts"; import { bundledPostgresClientLayer } from "../../command-internal/bundled-postgres-client.ts"; @@ -51,7 +51,7 @@ export const migrationDbRuntimeLayer = (commandPath: ReadonlyArray) => identityStitchLayer, telemetryStateLayer, stdinLayer, - linkedDbResolverRuntimeLayer(commandPath).pipe(Layer.provide(identityStitchLayer)), + lazyManagementApiRuntimeLayer(commandPath).pipe(Layer.provide(identityStitchLayer)), commandRuntimeLayer(commandPath), ); diff --git a/apps/cli/src/commands/pull/pull.layers.ts b/apps/cli/src/commands/pull/pull.layers.ts index 691423306a..714d175f13 100644 --- a/apps/cli/src/commands/pull/pull.layers.ts +++ b/apps/cli/src/commands/pull/pull.layers.ts @@ -27,7 +27,7 @@ import { /** * Runtime layer for `supabase pull`: composes `db pull`'s db-specific pieces with the eager * Management API stack and `MachineErrorContext` for single-envelope machine failures. Excludes - * `dbSchemaPullRuntimeLayer`'s `linkedDbResolverRuntimeLayer` piece, which independently binds + * `dbSchemaPullRuntimeLayer`'s `lazyManagementApiRuntimeLayer` piece, which independently binds * the same services via a different (lazy) factory — merging both would race over which * factory wins, since concurrent layer builds settle a shared singleton in build order. */ diff --git a/apps/cli/src/config/cli-config-flag-ownership.unit.test.ts b/apps/cli/src/config/cli-config-flag-ownership.unit.test.ts index 9574efc248..c053a5e799 100644 --- a/apps/cli/src/config/cli-config-flag-ownership.unit.test.ts +++ b/apps/cli/src/config/cli-config-flag-ownership.unit.test.ts @@ -14,7 +14,11 @@ const declarations: ReadonlyArray<{ path: string; names: ReadonlyArray } const ownerOf = new Map(declarations.flatMap(({ path, names }) => names.map((n) => [n, path]))); const commands = walkCommandTree( - rootCommandForFeatures({ stackBackend: "stack", computeEnabled: true }), + rootCommandForFeatures({ + stackBackend: "stack", + computeEnabled: true, + apiFeatures: ["warehouse"], + }), ); const ownedFlags = commands.flatMap((entry) => diff --git a/apps/cli/src/shared/cli/value-consuming-flags.ts b/apps/cli/src/shared/cli/value-consuming-flags.ts index beadd98680..161f02afea 100644 --- a/apps/cli/src/shared/cli/value-consuming-flags.ts +++ b/apps/cli/src/shared/cli/value-consuming-flags.ts @@ -1,3 +1,4 @@ +import { apiCommands } from "../../commands/api/generated.ts"; import { GEN_TYPES_LANGUAGE_VALUE_FLAG_NAMES } from "../../commands/gen/types/types.languages.ts"; /** @@ -111,6 +112,12 @@ export const VALUE_CONSUMING_LONG_FLAGS = new Set([ "stack", "stack-id", "preparation", + // Runtime flags of the generated API commands, plus each generated flag that is not a boolean. + "body", + "timeout", + ...apiCommands.flatMap((entry) => + entry.flags.filter((flag) => flag.type !== "boolean").map((flag) => flag.name), + ), ]); /** Single-character short flags (no `-` prefix) that consume the next token. */ diff --git a/apps/cli/src/shared/config/experimental-feature.ts b/apps/cli/src/shared/config/experimental-feature.ts index 5d0d9c14c4..13497985cb 100644 --- a/apps/cli/src/shared/config/experimental-feature.ts +++ b/apps/cli/src/shared/config/experimental-feature.ts @@ -23,6 +23,7 @@ export class ExperimentalFeatureFlagError extends Data.TaggedError("Experimental const featureSchemas = { stack: CliConfigSchema.fields.experimental.to.fields.stack, compute: CliConfigSchema.fields.experimental.to.fields.compute, + warehouse: CliConfigSchema.fields.experimental.to.fields.warehouse, } as const; const firstExplicitLongFlagValue = ( @@ -44,7 +45,7 @@ const readEnv = (name: string) => /** Reads one experimental feature, treating unavailable or invalid configuration as unset. */ export const readExperimentalFeatureConfig = (input: { - readonly feature: keyof typeof featureSchemas; + readonly feature: ExperimentalFeature; readonly args: ReadonlyArray; readonly cwd: string; }): Effect.Effect => @@ -76,14 +77,18 @@ export const readExperimentalFeatureConfig = (input: { const featureKeys = { stack: CliConfigKeys.experimental.stack, compute: CliConfigKeys.experimental.compute, + warehouse: CliConfigKeys.experimental.warehouse, } as const; +/** Name of an `experimental.` config key. */ +export type ExperimentalFeature = keyof typeof featureKeys; + /** * Resolves one experimental boolean: a shell boolean override, else the project * config. Remotes and project `.env*` files do not apply. */ export const resolveExperimentalFeature = (input: { - readonly feature: keyof typeof featureKeys; + readonly feature: ExperimentalFeature; readonly configValue: Effect.Effect; }): Effect.Effect => Effect.gen(function* () { diff --git a/apps/cli/src/shared/output/description-contract.unit.test.ts b/apps/cli/src/shared/output/description-contract.unit.test.ts index c5435666d4..26f9dd5bea 100644 --- a/apps/cli/src/shared/output/description-contract.unit.test.ts +++ b/apps/cli/src/shared/output/description-contract.unit.test.ts @@ -65,6 +65,7 @@ describe("command description contract", () => { const root = rootCommandForFeatures({ stackBackend, computeEnabled, + apiFeatures: ["warehouse"], projectState: Exit.succeed(stackBackend), }); expect(violationsForTree(root)).toEqual([]); diff --git a/apps/cli/src/shared/telemetry/__fixtures__/error-tags.txt b/apps/cli/src/shared/telemetry/__fixtures__/error-tags.txt index 5975f3d006..4e5a9fe506 100644 --- a/apps/cli/src/shared/telemetry/__fixtures__/error-tags.txt +++ b/apps/cli/src/shared/telemetry/__fixtures__/error-tags.txt @@ -1,4 +1,9 @@ AccessTokenRequiredError +ApiCommandOperationFailedError +ApiCommandStatusError +ApiCommandUnexpectedResponseError +ApiCommandUsageError +ApiCommandWaitTimeoutError ApiMaxRetriesError BackupListNetworkError BackupListUnexpectedStatusError diff --git a/apps/cli/tests/helpers/command-flags.unit.test.ts b/apps/cli/tests/helpers/command-flags.unit.test.ts index 8375f88d86..904b2ffe24 100644 --- a/apps/cli/tests/helpers/command-flags.unit.test.ts +++ b/apps/cli/tests/helpers/command-flags.unit.test.ts @@ -53,5 +53,7 @@ describe("commandTreeFor", () => { it("only includes feature-gated commands for the variant that enables them", () => { expect(tree.has("compute list")).toBe(false); expect(commandTreeFor({ computeEnabled: true }).has("compute list")).toBe(true); + expect(tree.has("warehouse enable")).toBe(false); + expect(commandTreeFor({ apiFeatures: ["warehouse"] }).has("warehouse enable")).toBe(true); }); }); diff --git a/apps/cli/tests/helpers/hosted-consent.ts b/apps/cli/tests/helpers/hosted-consent.ts index 167bd0691c..029d9e9232 100644 --- a/apps/cli/tests/helpers/hosted-consent.ts +++ b/apps/cli/tests/helpers/hosted-consent.ts @@ -39,6 +39,8 @@ type HostedConsentServices = Layer.Success>; interface HostedConsentEnv { readonly workdir: string; + /** Whether this case grants consent with `--yes`, for scenarios that run through argv. */ + readonly yes: boolean; readonly out: ReturnType; readonly api: ReturnType; } @@ -136,7 +138,7 @@ export function describeHostedConsent(path: string, scenario: HostedConsentScena yield* scenario.setup(workdir).pipe(Effect.provide(BunServices.layer)); } - const invocation = scenario.invoke({ workdir, out, api }); + const invocation = scenario.invoke({ workdir, yes: options.yes ?? false, out, api }); const shellEnv = (body: Effect.Effect) => options.shellYes === true ? withConfigEnv({ SUPABASE_YES: "1" }, body) diff --git a/apps/cli/tests/helpers/mocks.ts b/apps/cli/tests/helpers/mocks.ts index 8b5683f4a1..9690035306 100644 --- a/apps/cli/tests/helpers/mocks.ts +++ b/apps/cli/tests/helpers/mocks.ts @@ -228,6 +228,8 @@ export function mockProcessControl( }; } +const optionalMessage = (message: string | undefined) => (message === undefined ? {} : { message }); + export function mockOutput( opts: { format?: OutputFormat; @@ -246,6 +248,7 @@ export function mockOutput( const messages: OutputMessage[] = []; const failures: Array["fail"]>[0]> = []; const progressEvents: ProgressEvent[] = []; + const taskSettlements: Array<{ type: "clear" | "fail" | "cancel"; message?: string }> = []; const events: OutputEvent[] = []; const rawChunks: Array<{ text: string; stream: "stdout" | "stderr" }> = []; const promptConfirmCalls: Array<{ @@ -321,6 +324,7 @@ export function mockOutput( }), fail: (nextMessage?: string) => Effect.sync(() => { + taskSettlements.push({ type: "fail", ...optionalMessage(nextMessage) }); if (nextMessage !== undefined) { messages.push({ type: "error", message: nextMessage }); } @@ -333,11 +337,14 @@ export function mockOutput( }), cancel: (nextMessage?: string) => Effect.sync(() => { + taskSettlements.push({ type: "cancel", ...optionalMessage(nextMessage) }); if (nextMessage !== undefined) { messages.push({ type: "warn", message: nextMessage }); } }), - clear: Effect.void, + clear: Effect.sync(() => { + taskSettlements.push({ type: "clear" }); + }), }; }), event: (event) => @@ -464,6 +471,7 @@ export function mockOutput( messages, failures, progressEvents, + taskSettlements, events, promptConfirmCalls, promptSelectCalls, diff --git a/package.json b/package.json index 6eea79a7f4..806821e40f 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "scripts": { "prepare": "effect-tsgo patch --no-typescript --oxlint && husky", "build": "pnpm exec turbo run build", - "generate": "pnpm exec turbo run @supabase/api#generate @supabase/stack#generate && pnpm exec turbo run supabase#schemas:generate", + "generate": "pnpm exec turbo run @supabase/api#generate @supabase/stack#generate && pnpm exec turbo run supabase#api-commands:generate supabase#schemas:generate", "test:live": "pnpm exec turbo run supabase#test:live --concurrency=1 --", "record": "pnpm exec turbo run @supabase/cli-e2e#record --", "test:smoke": "pnpm exec turbo run supabase#test:smoke --", @@ -14,7 +14,7 @@ "test:integration": "pnpm exec turbo run test:integration:run --continue=always --", "test:e2e": "pnpm exec turbo run supabase#build && pnpm exec turbo run test:e2e:run --only --concurrency=1 --continue=always --", "test:vitest": "bun --bun vitest run --project '!*e2e*' --project '!*live*'", - "check:all": "pnpm exec turbo run types:check lint:check fmt:check knip:check lint:actions:check", + "check:all": "pnpm exec turbo run types:check lint:check fmt:check knip:check lint:actions:check api-commands:check", "fix:all": "pnpm exec turbo run knip:fix && pnpm exec turbo run lint:fix && pnpm exec turbo run fmt:fix", "lint:check": "oxlint --config .oxlintrc.json", "lint:fix": "oxlint --config .oxlintrc.json --fix --fix-suggestions", diff --git a/packages/api/scripts/openapi-overrides.json b/packages/api/scripts/openapi-overrides.json index 0d43e170f2..1a4df091e1 100644 --- a/packages/api/scripts/openapi-overrides.json +++ b/packages/api/scripts/openapi-overrides.json @@ -152,5 +152,4556 @@ "path": "/components/schemas/SnippetResponse_Output/properties/content/nullable", "value": true, "$comment": "The platform returns a null `content` for a snippet that has no stored content." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1status", + "value": { + "get": { + "description": "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-status", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseContextResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse feature or project metadata unavailable" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Get consolidated Warehouse status and capabilities", + "tags": ["Projects Warehouse"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse", + "method": "status" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The consolidated Warehouse status contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseContextResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "capabilities": { + "description": "Complete operations supported by this API, not caller authorization. Each operation still requires its feature, entitlement and project permission checks.", + "properties": { + "context": { + "type": "boolean" + }, + "query_explain": { + "description": "Whether the Management API supports a query-explain operation. SQL EXPLAIN through the Warehouse connection is independent of this flag.", + "type": "boolean" + }, + "replication_add": { + "type": "boolean" + }, + "replication_remove": { + "type": "boolean" + }, + "replication_restart": { + "type": "boolean" + }, + "table_layout_read": { + "type": "boolean" + }, + "table_layout_update": { + "type": "boolean" + }, + "table_resync": { + "type": "boolean" + }, + "workload_metrics": { + "description": "Query statistics and capacity inspection are supported by the Management API. Metric availability is reported separately.", + "type": "boolean" + } + }, + "required": [ + "context", + "query_explain", + "replication_add", + "replication_remove", + "replication_restart", + "table_layout_read", + "table_layout_update", + "table_resync", + "workload_metrics" + ], + "type": "object" + }, + "compute": { + "description": "Configured Warehouse compute and region, which may differ from the source database region. Live availability and capacity are not reported.", + "properties": { + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "region": { + "nullable": true, + "type": "string" + }, + "routing_status": { + "enum": ["error", null, "pending", "ready", "removed"], + "nullable": true, + "type": "string" + }, + "status": { + "enum": ["available", "not_provisioned", "unavailable"], + "type": "string" + }, + "unavailable_reason": { + "enum": [ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" + ], + "nullable": true, + "type": "string" + } + }, + "required": [ + "observed_at", + "region", + "routing_status", + "status", + "unavailable_reason" + ], + "type": "object" + }, + "configured_readiness": { + "description": "Readiness inferred from configuration and replication observations; no query is executed.", + "enum": ["not_ready", "ready", "unavailable"], + "type": "string" + }, + "enabled": { + "description": "Whether Warehouse is enabled, independently of selected table count. Null means provisioning could not be determined.", + "nullable": true, + "type": "boolean" + }, + "lifecycle": { + "nullable": true, + "properties": { + "delete_data": { + "type": "boolean" + }, + "status": { + "enum": ["deletion_failed", "disabled", "disabling"], + "type": "string" + }, + "updated_at": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + } + }, + "required": ["delete_data", "status", "updated_at"], + "type": "object" + }, + "observed_at": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "pipeline": { + "nullable": true, + "properties": { + "diagnostic": { + "description": "Safe classification of the current runtime failure. Does not include worker logs or establish its underlying cause.", + "nullable": true, + "properties": { + "code": { + "enum": [ + "configuration_error", + "crash_loop", + "image_unavailable", + "out_of_memory", + "process_exited", + "runtime_failed", + "startup_failed" + ], + "type": "string" + }, + "exit_code": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "nullable": true, + "type": "integer" + }, + "message": { + "type": "string" + } + }, + "required": ["code", "exit_code", "message"], + "type": "object" + }, + "id": { + "minLength": 1, + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "status": { + "enum": [ + "failed", + "started", + "starting", + "stopped", + "stopping", + "unavailable", + "unknown" + ], + "type": "string" + }, + "unavailable_reason": { + "enum": [ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" + ], + "nullable": true, + "type": "string" + } + }, + "required": ["diagnostic", "id", "observed_at", "status", "unavailable_reason"], + "type": "object" + }, + "project_ref": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "query_connectivity": { + "enum": ["not_checked"], + "type": "string" + }, + "replication": { + "properties": { + "apply_lag": { + "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", + "nullable": true, + "properties": { + "active": { + "type": "boolean" + }, + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "flush_lag_bytes": { + "maximum": 9007199254740991, + "minimum": 0, + "nullable": true, + "type": "integer" + }, + "flush_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + } + }, + "required": [ + "active", + "feedback_age_ms", + "flush_lag_bytes", + "flush_lag_ms", + "wal_status", + "write_lag_ms" + ], + "type": "object" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "status": { + "enum": [ + "available", + "not_provisioned", + "not_started", + "stopped", + "unavailable" + ], + "type": "string" + }, + "unavailable_reason": { + "enum": [ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" + ], + "nullable": true, + "type": "string" + } + }, + "required": ["apply_lag", "observed_at", "status", "unavailable_reason"], + "type": "object" + }, + "status": { + "description": "Warehouse setup and replication status. Ready means the Warehouse connection is configured and tables are replicating ongoing changes. It does not guarantee that a query will succeed.", + "enum": [ + "degraded", + "disabled", + "disabling", + "not_provisioned", + "ready", + "starting", + "stopped", + "stopping", + "unavailable" + ], + "type": "string" + }, + "tables": { + "properties": { + "items": { + "items": { + "properties": { + "error": { + "nullable": true, + "properties": { + "reason": { + "type": "string" + }, + "retry_policy": { + "oneOf": [ + { + "properties": { + "policy": { + "enum": ["no_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "policy": { + "enum": ["manual_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "next_retry": { + "type": "string" + }, + "policy": { + "enum": ["timed_retry"], + "type": "string" + } + }, + "required": ["next_retry", "policy"], + "type": "object" + } + ] + }, + "solution": { + "nullable": true, + "type": "string" + } + }, + "required": ["reason", "retry_policy", "solution"], + "type": "object" + }, + "id": { + "exclusiveMinimum": true, + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "name": { + "type": "string" + }, + "replication_state": { + "enum": [ + "copied_table", + "copying_table", + "error", + "following_wal", + null, + "queued" + ], + "nullable": true, + "type": "string" + }, + "schema": { + "type": "string" + }, + "state_observation": { + "enum": ["current", "last_known", "unavailable"], + "type": "string" + }, + "sync_lag": { + "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", + "nullable": true, + "properties": { + "active": { + "type": "boolean" + }, + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "flush_lag_bytes": { + "maximum": 9007199254740991, + "minimum": 0, + "nullable": true, + "type": "integer" + }, + "flush_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "wal_status": { + "enum": [ + "extended", + "lost", + null, + "reserved", + "unknown", + "unreserved" + ], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + } + }, + "required": [ + "active", + "feedback_age_ms", + "flush_lag_bytes", + "flush_lag_ms", + "wal_status", + "write_lag_ms" + ], + "type": "object" + } + }, + "required": [ + "error", + "id", + "name", + "replication_state", + "schema", + "state_observation", + "sync_lag" + ], + "type": "object" + }, + "type": "array" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "progress": { + "description": "Observed states of the selected tables, not completion or percentage of a specific mutation. Last-known states may predate a restart or resync. Null when the selection is unavailable.", + "nullable": true, + "properties": { + "copied_table": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "copying_table": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "error": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "following_wal": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "observation": { + "enum": ["current", "last_known", "unavailable"], + "type": "string" + }, + "queued": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "selected": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "unknown": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "copied_table", + "copying_table", + "error", + "following_wal", + "observation", + "queued", + "selected", + "unknown" + ], + "type": "object" + }, + "status": { + "enum": ["available", "not_provisioned", "unavailable"], + "type": "string" + }, + "unavailable_reason": { + "enum": [ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" + ], + "nullable": true, + "type": "string" + } + }, + "required": ["items", "observed_at", "progress", "status", "unavailable_reason"], + "type": "object" + } + }, + "required": [ + "capabilities", + "compute", + "configured_readiness", + "enabled", + "lifecycle", + "observed_at", + "pipeline", + "project_ref", + "query_connectivity", + "replication", + "status", + "tables" + ], + "type": "object" + }, + "id": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_context"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The consolidated Warehouse status contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1connection", + "value": { + "get": { + "description": "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: `usql -W 'flightsql://postgres@:443?tls=enabled'`.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-connection", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseConnectionResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse feature or project metadata unavailable" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Get Warehouse Flight SQL connection details", + "tags": ["Projects Warehouse"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse", + "method": "connection" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse Flight SQL connection contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseConnectionResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "access_mode": { + "enum": ["read_only"], + "type": "string" + }, + "authentication": { + "description": "How to authenticate. No credentials are returned; the password is never exposed by this API.", + "properties": { + "credential_source": { + "enum": ["source_project_database"], + "type": "string" + }, + "default_username": { + "enum": ["postgres"], + "type": "string" + }, + "membership_guidance": { + "type": "string" + }, + "method": { + "enum": ["database_username_password"], + "type": "string" + }, + "password_guidance": { + "type": "string" + }, + "required_membership": { + "enum": ["supabase_warehouse_reader"], + "type": "string" + } + }, + "required": [ + "credential_source", + "default_username", + "membership_guidance", + "method", + "password_guidance", + "required_membership" + ], + "type": "object" + }, + "endpoint": { + "description": "Arrow Flight SQL URI, grpc+tls://:443. Null unless status is available or pending.", + "nullable": true, + "type": "string" + }, + "host": { + "description": "Public hostname of the Flight SQL endpoint. Null unless status is available or pending.", + "nullable": true, + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when connectivity was last verified.", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "port": { + "description": "Public TLS port of the Flight SQL endpoint. Null unless status is available or pending.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "nullable": true, + "type": "integer" + }, + "project_ref": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "protocol": { + "enum": ["arrow_flight_sql"], + "type": "string" + }, + "query_connectivity": { + "enum": ["not_checked"], + "type": "string" + }, + "region": { + "description": "Assigned Warehouse compute region, which may differ from the source database region. Null when the project has no project-specific route.", + "nullable": true, + "type": "string" + }, + "routing_status": { + "description": "DNS delivery status of the project route. Null when the project uses the shared legacy route.", + "enum": ["error", null, "pending", "ready", "removed"], + "nullable": true, + "type": "string" + }, + "status": { + "description": "Configured availability of the Warehouse endpoint, derived from routing and lifecycle state. It is not a connectivity probe: a ready route does not prove a query will succeed.", + "enum": [ + "available", + "disabled", + "disabling", + "not_configured", + "pending", + "unavailable" + ], + "type": "string" + }, + "tls_required": { + "enum": [true], + "type": "boolean" + }, + "unavailable_reason": { + "description": "Why the endpoint is unavailable. Null unless status is unavailable.", + "enum": [ + "assignment_unavailable", + "cleanup_failed", + null, + "observation_unavailable", + "routing_failed" + ], + "nullable": true, + "type": "string" + } + }, + "required": [ + "access_mode", + "authentication", + "endpoint", + "host", + "observed_at", + "port", + "project_ref", + "protocol", + "query_connectivity", + "region", + "routing_status", + "status", + "tls_required", + "unavailable_reason" + ], + "type": "object" + }, + "id": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_connection"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse Flight SQL connection contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1tables", + "value": { + "get": { + "description": "Lists the source tables selected for Warehouse replication with their replication status and freshness, from the same observations as the Warehouse status. Freshness comes from the replication slot that carries each table: its own sync slot until it follows changes, then the pipeline apply slot; one slot never stands in for the other. lag_ms is that slot's flush lag. Postgres reports no lag time for a caught-up slot without new WAL, so lag_ms can be null while replication_feedback.flush_lag_bytes is 0; neither is ever filled with zero when unknown. observed_at is when the API read the replication state, not when data last synchronized. A stopped, failed or unreadable pipeline reports its tables as stopped or unknown rather than live, and keeps each table's last recorded state. Returns an empty list when Warehouse is not set up, its publication is missing, or it is being disabled or failed to clean up.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-list-warehouse-tables", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseTablesResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse DuckLake destination not found" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse feature, project metadata or table selection unavailable" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "List tables replicated to Warehouse", + "tags": ["Projects Warehouse"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse.tables", + "method": "list" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse tables listing contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTablesResponse_Output", + "value": { + "properties": { + "data": { + "items": { + "properties": { + "attributes": { + "properties": { + "lag_ms": { + "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + "minimum": 0, + "nullable": true, + "type": "number" + }, + "name": { + "description": "Source PostgreSQL table name.", + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "replication_feedback": { + "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", + "nullable": true, + "properties": { + "active": { + "type": "boolean" + }, + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "flush_lag_bytes": { + "maximum": 9007199254740991, + "minimum": 0, + "nullable": true, + "type": "integer" + }, + "flush_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "source": { + "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", + "enum": ["pipeline_apply", "table_sync"], + "type": "string" + }, + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + } + }, + "required": [ + "active", + "feedback_age_ms", + "flush_lag_bytes", + "flush_lag_ms", + "source", + "wal_status", + "write_lag_ms" + ], + "type": "object" + }, + "replication_state": { + "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + "enum": [ + "copied_table", + "copying_table", + "error", + "following_wal", + null, + "queued" + ], + "nullable": true, + "type": "string" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" + }, + "status": { + "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + "enum": ["error", "live", "stopped", "syncing", "unknown"], + "type": "string" + }, + "warehouse_name": { + "description": "Quoted, fully qualified name of the replicated table in the Warehouse.", + "type": "string" + } + }, + "required": [ + "lag_ms", + "name", + "observed_at", + "replication_feedback", + "replication_state", + "schema", + "status", + "warehouse_name" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse tables listing contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1tables~1{table_id}", + "value": { + "get": { + "description": "Returns one source table selected for Warehouse replication by its source OID, from the same observations and with the same status and freshness attributes as the Warehouse tables list. Returns 404 when the table is not selected for replication, including when Warehouse is not set up, its publication is missing, or it is being disabled.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-table", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + }, + { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", + "name": "table_id", + "required": true, + "schema": { + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseTableResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Table not replicated to Warehouse, or Warehouse DuckLake destination not found" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse feature, project metadata or table selection unavailable" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Get a table replicated to Warehouse", + "tags": ["Projects Warehouse"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse.tables", + "method": "get" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse table inspection contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTableResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "lag_ms": { + "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + "minimum": 0, + "nullable": true, + "type": "number" + }, + "name": { + "description": "Source PostgreSQL table name.", + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "replication_feedback": { + "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", + "nullable": true, + "properties": { + "active": { + "type": "boolean" + }, + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "flush_lag_bytes": { + "maximum": 9007199254740991, + "minimum": 0, + "nullable": true, + "type": "integer" + }, + "flush_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "source": { + "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", + "enum": ["pipeline_apply", "table_sync"], + "type": "string" + }, + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + } + }, + "required": [ + "active", + "feedback_age_ms", + "flush_lag_bytes", + "flush_lag_ms", + "source", + "wal_status", + "write_lag_ms" + ], + "type": "object" + }, + "replication_state": { + "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + "enum": [ + "copied_table", + "copying_table", + "error", + "following_wal", + null, + "queued" + ], + "nullable": true, + "type": "string" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" + }, + "status": { + "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + "enum": ["error", "live", "stopped", "syncing", "unknown"], + "type": "string" + }, + "warehouse_name": { + "description": "Quoted, fully qualified name of the replicated table in the Warehouse.", + "type": "string" + } + }, + "required": [ + "lag_ms", + "name", + "observed_at", + "replication_feedback", + "replication_state", + "schema", + "status", + "warehouse_name" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse table inspection contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1tables~1{table_id}~1layout", + "value": { + "get": { + "description": "Returns the sorting and partitioning rules saved for one replicated table, by source OID, beside the layout the DuckLake catalog records for it. The two are reported separately and can differ: the replicator applies saved rules when it starts and then hourly, and a stopped pipeline applies them on its next start. observation_status reports whether the catalog was read; desired rules are returned even when it was not. A catalog layout governs files written after it changes and does not establish that existing files are sorted or partitioned. Returns 404 when the table is not replicated, including when Warehouse is not set up, is being disabled or failed to clean up.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-table-layout", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + }, + { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", + "name": "table_id", + "required": true, + "schema": { + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseTableLayoutResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Table not replicated to Warehouse" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse feature, project metadata or table layout unavailable" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Get the layout of a table replicated to Warehouse", + "tags": ["Projects Warehouse"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse.tables.layout", + "method": "get" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse table layout contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTableLayoutResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "application_status": { + "description": "Backend orchestration state. Runtime acceptance does not establish that the desired layout has been observed in the catalog.", + "type": "string" + }, + "desired": { + "description": "Saved layout rules. The replicator applies them on start and hourly, so they can differ from the observed layout.", + "properties": { + "partition_by": { + "description": "Configured partition keys in order. An empty list explicitly clears partitioning; null leaves it unmanaged.", + "items": { + "properties": { + "column": { + "description": "Source column name.", + "type": "string" + }, + "transform": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": ["identity"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["year"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["month"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["day"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["hour"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "count": { + "description": "Number of hash buckets.", + "exclusiveMinimum": true, + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" + } + }, + "required": ["count", "kind"], + "type": "object" + } + ] + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "nullable": true, + "type": "array" + }, + "sort_by": { + "description": "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", + "oneOf": [ + { + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "columns": { + "items": { + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name", "nulls"], + "type": "object" + }, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + }, + { + "type": "object", + "nullable": true, + "enum": [null] + } + ] + } + }, + "required": ["partition_by", "sort_by"], + "type": "object" + }, + "name": { + "description": "Source PostgreSQL table name.", + "type": "string" + }, + "observation_status": { + "description": "observed when the DuckLake catalog was read, table_missing when the catalog has no table for it yet, unavailable when the catalog could not be read, and not_requested when an update returned without reading the catalog.", + "enum": ["not_requested", "observed", "table_missing", "unavailable"], + "type": "string" + }, + "observed": { + "description": "Layout recorded in the DuckLake catalog, null unless observation_status is observed. Catalog metadata governs files written after it changes and does not establish that existing files are sorted or partitioned.", + "nullable": true, + "properties": { + "observed_at": { + "description": "Time the catalog metadata was read.", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "partition_by": { + "description": "Active partition keys in key order, with transforms as the catalog reports them, for example bucket(16).", + "items": { + "properties": { + "column": { + "type": "string" + }, + "transform": { + "type": "string" + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "type": "array" + }, + "sort_by": { + "description": "Active sort expressions in key order, as the catalog reports them.", + "items": { + "properties": { + "direction": { + "type": "string" + }, + "expression": { + "type": "string" + }, + "nulls": { + "type": "string" + } + }, + "required": ["direction", "expression", "nulls"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["observed_at", "partition_by", "sort_by"], + "type": "object" + }, + "pipeline_id": { + "description": "Warehouse replication pipeline identity.", + "type": "string" + }, + "reset_table": { + "description": "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", + "type": "boolean" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" + } + }, + "required": [ + "application_status", + "desired", + "name", + "observation_status", + "observed", + "pipeline_id", + "reset_table", + "schema" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table_layout"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse table layout contract is not yet in the deployed Management API specification." + }, + { + "op": "test", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1setups~1current/get/x-operation", + "value": { + "group": "warehouse", + "method": "status", + "poll": { + "status": "/data/attributes/status", + "succeeded": ["succeeded"], + "failed": ["failed"], + "error": "/data/attributes/status_error" + } + }, + "$comment": "The setup read is polled by `warehouse enable --wait`; its name must not claim the status read's `warehouse status`, and `inspect` names that consolidated status read." + }, + { + "op": "replace", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1setups~1current/get/x-operation", + "value": { + "group": "warehouse.setups", + "method": "get", + "poll": { + "status": "/data/attributes/status", + "succeeded": ["succeeded"], + "failed": ["failed"], + "error": "/data/attributes/status_error", + "inspect": "v2-get-warehouse-status" + } + } + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1tables~1{table_id}~1layout/patch", + "value": { + "description": "Updates saved sorting and partitioning rules for one source table object identifier (OID). Provide sort_by or partition_by; empty and reset-only patches are rejected. Omitted settings are preserved. Null makes a setting unmanaged. An empty partition list clears partitioning, and the none sort selector clears sorting. The backend validates the source schema and preserves other tables. When the layout changes, an active pipeline is restarted. A stopped pipeline stays stopped. reset_table defaults to false, preserving historical files and replication progress. When the layout changes, --reset-table resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never restarts the pipeline or resets the table. Acceptance and application_status report orchestration. Run warehouse tables layout get to compare the desired and observed rules. Run warehouse tables get to check table replication status. These reads do not establish completion of this specific update. There is no revision, idempotency, resolved preview, or durable operation contract. A failed update can leave partial effects, including a completed reset. Inspect the saved layout, pipeline, and table state before retrying.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-update-warehouse-table-layout", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + }, + { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", + "name": "table_id", + "required": true, + "schema": { + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseTableLayoutUpdateRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseTableLayoutResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Invalid layout or source schema" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse pipeline or replicated table not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse or pipeline mutation conflict, or reset requested without initial sync" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Layout update unavailable or outcome uncertain; inspect the saved layout, pipeline, and table state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Update the layout of a table replicated to Warehouse", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.tables.layout", + "method": "update" + }, + "x-scalar-stability": "experimental" + }, + "$comment": "The Warehouse layout update contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTableLayoutPartitionBy", + "value": { + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", + "items": { + "additionalProperties": false, + "properties": { + "column": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "transform": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["identity"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["year"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["month"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["day"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["hour"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "count": { + "description": "Number of hash buckets.", + "exclusiveMinimum": true, + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" + } + }, + "required": ["count", "kind"], + "type": "object" + } + ] + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "nullable": true, + "type": "array" + }, + "$comment": "The Warehouse layout update contract is not yet in the deployed Management API specification. Shared by both attribute branches of the update request." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTableLayoutSortBy", + "value": { + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "additionalProperties": false, + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + }, + { + "type": "object", + "nullable": true, + "enum": [null] + } + ] + }, + "$comment": "The Warehouse layout update contract is not yet in the deployed Management API specification. Shared by both attribute branches of the update request." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseTableLayoutUpdateRequest", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "anyOf": [ + { + "additionalProperties": false, + "properties": { + "partition_by": { + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{\"column\":\"event_at\",\"transform\":{\"kind\":\"day\"}}]`. Bucket example: `[{\"column\":\"tenant_id\",\"transform\":{\"kind\":\"bucket\",\"count\":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.", + "items": { + "additionalProperties": false, + "properties": { + "column": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "transform": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["identity"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["year"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["month"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["day"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["hour"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "count": { + "description": "Number of hash buckets.", + "exclusiveMinimum": true, + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" + } + }, + "required": ["count", "kind"], + "type": "object" + } + ] + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "nullable": true, + "type": "array" + }, + "reset_table": { + "description": "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", + "type": "boolean" + }, + "sort_by": { + "anyOf": [ + { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "additionalProperties": false, + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + } + ] + }, + { + "enum": [null], + "nullable": true, + "type": "object" + } + ], + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{\"kind\":\"columns\",\"columns\":[{\"name\":\"tenant_id\",\"direction\":\"asc\"},{\"name\":\"event_at\",\"direction\":\"desc\",\"nulls\":\"last\"}]}`. Sort by the primary key with `{\"kind\":\"primary_key\"}` or clear sorting with `{\"kind\":\"none\"}`." + } + }, + "required": ["sort_by"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "partition_by": { + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{\"column\":\"event_at\",\"transform\":{\"kind\":\"day\"}}]`. Bucket example: `[{\"column\":\"tenant_id\",\"transform\":{\"kind\":\"bucket\",\"count\":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.", + "items": { + "additionalProperties": false, + "properties": { + "column": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "transform": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["identity"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["year"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["month"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["day"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["hour"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "count": { + "description": "Number of hash buckets.", + "exclusiveMinimum": true, + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" + } + }, + "required": ["count", "kind"], + "type": "object" + } + ] + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "nullable": true, + "type": "array" + }, + "reset_table": { + "description": "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", + "type": "boolean" + }, + "sort_by": { + "anyOf": [ + { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "additionalProperties": false, + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + } + ] + }, + { + "enum": [null], + "nullable": true, + "type": "object" + } + ], + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{\"kind\":\"columns\",\"columns\":[{\"name\":\"tenant_id\",\"direction\":\"asc\"},{\"name\":\"event_at\",\"direction\":\"desc\",\"nulls\":\"last\"}]}`. Sort by the primary key with `{\"kind\":\"primary_key\"}` or clear sorting with `{\"kind\":\"none\"}`." + } + }, + "required": ["partition_by"], + "type": "object" + } + ] + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table_layout"], + "type": "string" + } + }, + "required": ["attributes", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse layout update contract is not yet in the deployed Management API specification. Its attributes are a union of two branches so a patch with neither sort_by nor partition_by is rejected as the platform does." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseQueryStatsResponse_Output", + "value": { + "properties": { + "data": { + "items": { + "properties": { + "attributes": { + "properties": { + "aggregation": { + "enum": ["mean", "occupied", "p50", "p95", "p99", "rate", "sum"], + "type": "string" + }, + "availability": { + "enum": [ + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable" + ], + "type": "string" + }, + "definition": { + "type": "string" + }, + "effective": { + "properties": { + "end": { + "type": "number" + }, + "rate_window_seconds": { + "type": "number" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "rate_window_seconds", "start", "step"], + "type": "object" + }, + "last_sample_at": { + "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + "nullable": true, + "type": "number" + }, + "metric": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "project_ref": { + "type": "string" + }, + "requested": { + "properties": { + "end": { + "type": "number" + }, + "metric": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "metric", "start"], + "type": "object" + }, + "scrape_interval_seconds": { + "type": "number" + }, + "series": { + "items": { + "properties": { + "coverage": { + "description": "Grid point coverage, not proof that every worker was scraped.", + "properties": { + "expected_points": { + "type": "number" + }, + "returned_points": { + "type": "number" + } + }, + "required": ["expected_points", "returned_points"], + "type": "object" + }, + "labels": { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + "points": { + "items": { + "properties": { + "timestamp": { + "type": "number" + }, + "value": { + "nullable": true, + "type": "number" + } + }, + "required": ["timestamp", "value"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["coverage", "labels", "points"], + "type": "object" + }, + "type": "array" + }, + "unit": { + "enum": ["grants", "per_second", "queries", "seconds"], + "type": "string" + } + }, + "required": [ + "aggregation", + "availability", + "definition", + "effective", + "last_sample_at", + "metric", + "project_ref", + "requested", + "scrape_interval_seconds", + "series", + "unit" + ], + "type": "object" + }, + "id": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_metric"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "Warehouse workload metrics are not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1query-stats", + "value": { + "get": { + "description": "Returns aggregate workload measurements over a bounded time range, using the project\u2019s stored Warehouse placement. Use since or both from and to; the default is the last 30 minutes. Each measurement includes its definition, unit, aggregation, requested and effective ranges, rate_window_seconds, source-sample freshness, availability, and full series with dimension labels. Point timestamps are evaluation times; last_sample_at is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. Do not average interval percentiles into a whole-range percentile. Executor invocations include metadata/schema work and are not counts of user SQL statements. Timeouts are included in errors; cancellation is separate. Missing and unavailable values remain null. No query history, individual-query attribution, raw queries, or backend selectors are exposed. Each request returns up to eight measurements. A failure of one measurement does not discard the other results.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-query-stats", + "parameters": [ + { + "description": "Up to eight distinct workload measurements. Defaults to invocation rate, latency p50/p95/p99, error rate, and timeout rate. Supply a comma-separated list. Allowed measurements: query_rate, query_error_rate, query_timeout_rate, query_canceled_rate, query_duration_mean, query_duration_p50, query_duration_p95, query_duration_p99, duckdb_duration_mean, rpc_rate, rpc_duration_mean, rpc_duration_p95.", + "in": "query", + "name": "attributes", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "Range start as an ISO timestamp, within the last 30 days. Requires to; cannot be combined with since.", + "in": "query", + "name": "from", + "required": false, + "schema": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" + } + }, + { + "description": "Defaults to 1m. The effective step increases to stay within 1441 points per series. Rate and latency windows are at least 5m.", + "in": "query", + "name": "interval", + "required": false, + "schema": { + "enum": ["10m", "1d", "1h", "1m", "30m", "5m"], + "type": "string" + } + }, + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + }, + { + "description": "Look back from server time, for example 30m, 2h, or 1d. Defaults to 30m when from/to are omitted. Maximum 30d. Cannot be combined with from/to.", + "in": "query", + "name": "since", + "required": false, + "schema": { + "pattern": "^[1-9]\\d*(s|m|h|d)$", + "type": "string" + } + }, + { + "description": "Range end as an ISO timestamp, no later than server time. Requires from; cannot be combined with since. The service tolerates up to 60 seconds of request delay or clock skew.", + "in": "query", + "name": "to", + "required": false, + "schema": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseQueryStatsResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Project not found" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable." + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Inspect Warehouse workload query statistics", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse.inspect", + "method": "query-stats" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "Public Warehouse workload metrics generate warehouse inspect query-stats." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseCapacityResponse_Output", + "value": { + "properties": { + "data": { + "items": { + "properties": { + "attributes": { + "properties": { + "aggregation": { + "enum": ["mean", "occupied", "p50", "p95", "p99", "rate", "sum"], + "type": "string" + }, + "availability": { + "enum": [ + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable" + ], + "type": "string" + }, + "definition": { + "type": "string" + }, + "effective": { + "properties": { + "end": { + "type": "number" + }, + "rate_window_seconds": { + "type": "number" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "rate_window_seconds", "start", "step"], + "type": "object" + }, + "last_sample_at": { + "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + "nullable": true, + "type": "number" + }, + "metric": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "query_in_flight", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "project_ref": { + "type": "string" + }, + "requested": { + "properties": { + "end": { + "type": "number" + }, + "metric": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "query_in_flight", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "metric", "start"], + "type": "object" + }, + "scrape_interval_seconds": { + "type": "number" + }, + "series": { + "items": { + "properties": { + "coverage": { + "description": "Grid point coverage, not proof that every worker was scraped.", + "properties": { + "expected_points": { + "type": "number" + }, + "returned_points": { + "type": "number" + } + }, + "required": ["expected_points", "returned_points"], + "type": "object" + }, + "labels": { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + "points": { + "items": { + "properties": { + "timestamp": { + "type": "number" + }, + "value": { + "nullable": true, + "type": "number" + } + }, + "required": ["timestamp", "value"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["coverage", "labels", "points"], + "type": "object" + }, + "type": "array" + }, + "unit": { + "enum": ["grants", "per_second", "queries", "seconds"], + "type": "string" + } + }, + "required": [ + "aggregation", + "availability", + "definition", + "effective", + "last_sample_at", + "metric", + "project_ref", + "requested", + "scrape_interval_seconds", + "series", + "unit" + ], + "type": "object" + }, + "id": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "query_in_flight", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_metric"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse capacity contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1capacity", + "value": { + "get": { + "description": "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project\u2019s stored Warehouse placement. Use `--since` or specify both `--from` and `--to`; the default is the last 30 minutes.\n\nEach measurement includes its definition, unit, aggregation, requested and effective ranges, `rate_window_seconds`, source-sample freshness, availability, coverage, and full series with dimension labels such as `reason`, `kind`, and `result`.\n\nExecutor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or `null`; they do not establish healthy or idle capacity.\n\nPoint timestamps are evaluation times; `last_sample_at` is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range.\n\nEach request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-get-warehouse-capacity", + "parameters": [ + { + "description": "Up to eight distinct measurements. Defaults to `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_p95`, `activation_duration_p95`. Supply a comma-separated list. Allowed measurements: `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_mean`, `assignment_wait_p95`, `activation_rate`, `activation_duration_mean`, `activation_duration_p95`.", + "in": "query", + "name": "attributes", + "required": false, + "schema": { + "type": "string" + } + }, + { + "description": "Range start as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, within the last 30 days. Requires `--to`; cannot be combined with `--since`.", + "in": "query", + "name": "from", + "required": false, + "schema": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" + } + }, + { + "description": "Defaults to `1m`. The effective step increases to stay within 1,441 points per series. Rate and latency windows are at least `5m`.", + "in": "query", + "name": "interval", + "required": false, + "schema": { + "enum": ["10m", "1d", "1h", "1m", "30m", "5m"], + "type": "string" + } + }, + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + }, + { + "description": "Look back from server time, for example `30m`, `2h`, or `1d`. Defaults to `30m` when `--from`/`--to` are omitted. Maximum `30d`. Cannot be combined with `--from`/`--to`.", + "in": "query", + "name": "since", + "required": false, + "schema": { + "pattern": "^[1-9]\\d*(s|m|h|d)$", + "type": "string" + } + }, + { + "description": "Range end as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, no later than server time. Requires `--from`; cannot be combined with `--since`. The service tolerates up to 60 seconds of request delay or clock skew.", + "in": "query", + "name": "to", + "required": false, + "schema": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseCapacityResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Project not found" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable." + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Inspect Warehouse capacity diagnostics", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:read", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_read"]], + "x-oauth-scope": "database:read", + "x-operation": { + "group": "warehouse.inspect", + "method": "capacity" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "Public Warehouse capacity metrics generate warehouse inspect capacity." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseReplicationRequest", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "additionalProperties": false, + "properties": { + "schema": { + "description": "Literal source PostgreSQL schema. Omit table to select its current tables.", + "minLength": 1, + "type": "string" + }, + "table": { + "description": "Literal source table name. Omit to select the schema.", + "minLength": 1, + "type": "string" + } + }, + "required": ["schema"], + "type": "object" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_change"], + "type": "string" + } + }, + "required": ["attributes", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse replication selection request contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseReplicationResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "action": { + "enum": ["add", "remove"], + "type": "string" + }, + "affected_tables": { + "items": { + "properties": { + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + } + }, + "required": ["id", "name", "schema"], + "type": "object" + }, + "type": "array" + }, + "application_status": { + "description": "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion.", + "enum": ["configured", "restart_requested", "unchanged"], + "type": "string" + }, + "changed": { + "type": "boolean" + }, + "includes_future_tables": { + "enum": [false], + "type": "boolean" + }, + "pipeline_id": { + "type": "string" + }, + "pipeline_status_before": { + "type": "string" + }, + "selected_table_count": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "source_data_preserved": { + "enum": [true], + "type": "boolean" + }, + "tables": { + "description": "Resulting configured selection, with best-effort replication observations.", + "items": { + "properties": { + "copy_name": { + "type": "string" + }, + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "replication_state": { + "nullable": true, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + }, + "state": { + "description": "Last observed table state; null when unavailable. Does not establish completion of this request.", + "enum": ["error", "live", null, "syncing"], + "nullable": true, + "type": "string" + } + }, + "required": [ + "copy_name", + "id", + "lag_ms", + "name", + "replication_state", + "schema", + "state" + ], + "type": "object" + }, + "type": "array" + }, + "unchanged_tables": { + "items": { + "properties": { + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + } + }, + "required": ["id", "name", "schema"], + "type": "object" + }, + "type": "array" + }, + "warehouse_data_retained": { + "enum": [true], + "type": "boolean" + }, + "warehouse_enabled": { + "enum": [true], + "type": "boolean" + } + }, + "required": [ + "action", + "affected_tables", + "application_status", + "changed", + "includes_future_tables", + "pipeline_id", + "pipeline_status_before", + "selected_table_count", + "source_data_preserved", + "tables", + "unchanged_tables", + "warehouse_data_retained", + "warehouse_enabled" + ], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_change"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse replication change response contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseResyncRequest", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "additionalProperties": false, + "properties": { + "schema": { + "description": "Literal source PostgreSQL schema of the table.", + "minLength": 1, + "type": "string" + }, + "table": { + "description": "Literal name of the single source table to reset and recopy.", + "minLength": 1, + "type": "string" + } + }, + "required": ["schema", "table"], + "type": "object" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_resync"], + "type": "string" + } + }, + "required": ["attributes", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse replication resync request contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseResyncResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "application_status": { + "description": "ETL reset replication state. Destination rebuild and recopy may still be pending.", + "enum": ["reset"], + "type": "string" + }, + "pipeline_id": { + "description": "Pipeline ID", + "example": "03dg2o5teb2eucxr9ggh3uie6", + "minLength": 1, + "type": "string" + }, + "source_data_preserved": { + "enum": [true], + "type": "boolean" + }, + "source_table": { + "properties": { + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + } + }, + "required": ["id", "name", "schema"], + "type": "object" + }, + "tables": { + "description": "Rolled back tables", + "items": { + "properties": { + "new_state": { + "description": "Table replication state", + "oneOf": [ + { + "properties": { + "name": { + "enum": ["queued"], + "type": "string" + } + }, + "required": ["name"], + "type": "object" + }, + { + "properties": { + "name": { + "enum": ["copying_table"], + "type": "string" + } + }, + "required": ["name"], + "type": "object" + }, + { + "properties": { + "name": { + "enum": ["copied_table"], + "type": "string" + } + }, + "required": ["name"], + "type": "object" + }, + { + "properties": { + "name": { + "enum": ["following_wal"], + "type": "string" + } + }, + "required": ["name"], + "type": "object" + }, + { + "properties": { + "name": { + "enum": ["error"], + "type": "string" + }, + "reason": { + "type": "string" + }, + "retry_policy": { + "oneOf": [ + { + "properties": { + "policy": { + "enum": ["no_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "policy": { + "enum": ["manual_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "next_retry": { + "description": "Next retry time (RFC 3339 timestamp)", + "example": "2025-01-02T03:04:05Z", + "type": "string" + }, + "policy": { + "enum": ["timed_retry"], + "type": "string" + } + }, + "required": ["next_retry", "policy"], + "type": "object" + } + ] + }, + "solution": { + "nullable": true, + "type": "string" + } + }, + "required": ["name", "reason", "retry_policy"], + "type": "object" + } + ] + }, + "table_id": { + "description": "Table id (Postgres OID)", + "example": 16408, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + } + }, + "required": ["new_state", "table_id"], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "application_status", + "pipeline_id", + "source_data_preserved", + "source_table", + "tables" + ], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_resync"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "The Warehouse replication resync response contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1replication~1add", + "value": { + "post": { + "description": "Adds one eligible source table or the currently eligible tables in a schema to an enabled Warehouse. Existing selections and layouts are preserved; already-selected tables are unchanged. Schema selection excludes future tables, except future partitions of selected partition roots. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline remains stopped and requires an explicit start before copying. Initial copy adds source reads; duration is unknown. Unsafe reattachment of retained data is rejected. The response describes configuration and restart acceptance, not completed copy or streaming. Failures may have partial effects; inspect table and pipeline state before retrying.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-add-warehouse-replication", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseReplicationRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseReplicationResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Invalid or ineligible source selection" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse pipeline, publication or selected table not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Add source tables to Warehouse replication", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.replication", + "method": "add" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse replication add contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1replication~1remove", + "value": { + "post": { + "description": "Removes one selected source table or all selected tables in a schema as a batch. Source PostgreSQL rows and existing Warehouse data are retained. The retained copy stops receiving updates. An active pipeline restarts once, interrupting replication for other tables; their in-progress initial copies may restart from scratch. A stopped pipeline stays stopped. Removing an unselected target is unchanged. Removing the last target leaves Warehouse enabled with an empty selection. Publication changes and restart acceptance do not establish observed exclusion by active replication. Failures may have partial effects; inspect the selection and pipeline before retrying.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-remove-warehouse-replication", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseReplicationRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseReplicationResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Invalid or ineligible source selection" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse pipeline, publication or selected table not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Remove source tables from Warehouse replication", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.replication", + "method": "remove" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse replication remove contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1replication~1resync", + "value": { + "post": { + "description": "Resets replication for one selected source table using its currently saved layout. Source rows, saved layouts and completed replication state for unrelated tables are preserved. In-progress initial copies of other tables may restart from scratch. The Warehouse copy is deleted and rebuilt when replication resumes; table reads may be unavailable, freshness can lag, and the source incurs additional reads. Stopping and restarting the pipeline interrupts replication for other tables. Duration is unknown. The pipeline must be started and initial sync enabled for the table before the reset. The immediate response retains ETL reset states; it does not establish recopy completion. Inspect warehouse tables get and warehouse status separately. Do not automatically retry an uncertain response: repeating this request may reset the table again. There is no server-side preview, revision check, idempotency key or operation polling.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-resync-warehouse-replication", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseResyncRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseResyncResponse_Output" + } + } + }, + "description": "" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Invalid or ineligible source selection" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse pipeline, publication or selected table not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Reset and rebuild one Warehouse table", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.replication", + "method": "resync" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "The Warehouse replication resync contract is not yet in the deployed Management API specification." + }, + { + "op": "add", + "path": "/paths/~1v2~1projects~1{ref}~1warehouse~1replication~1restart", + "value": { + "post": { + "description": "Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-restart-warehouse-replication", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseRestartResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Managed Warehouse pipeline not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse lifecycle or runtime state does not permit restart" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Restart outcome uncertain; inspect runtime and table state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Start or restart Warehouse replication", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.replication", + "method": "restart" + }, + "x-scalar-stability": "experimental" + } + }, + "$comment": "Warehouse diagnostics and restart contract pending deployment." + }, + { + "op": "add", + "path": "/components/schemas/V2WarehouseRestartResponse_Output", + "value": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "action": { + "enum": ["restart", "start"], + "type": "string" + }, + "application_status": { + "description": "The runtime request was accepted. This does not establish resumed replication or completed initial copies.", + "enum": ["accepted"], + "type": "string" + }, + "pipeline_id": { + "type": "string" + }, + "pipeline_status_before": { + "type": "string" + } + }, + "required": ["action", "application_status", "pipeline_id", "pipeline_status_before"], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_restart"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "$comment": "Warehouse diagnostics and restart contract pending deployment." } ] diff --git a/packages/api/src/generated/contracts.ts b/packages/api/src/generated/contracts.ts index e17b328108..2ac4f09ea4 100644 --- a/packages/api/src/generated/contracts.ts +++ b/packages/api/src/generated/contracts.ts @@ -11575,9 +11575,6 @@ export const V2AddWarehouseReplicationInput = Schema.Struct({ }), ), data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_change").annotate({ - description: "Resource type.", - }), attributes: Schema.Struct({ schema: Schema.String.annotate({ description: "Literal source PostgreSQL schema. Omit table to select its current tables.", @@ -11590,26 +11587,15 @@ export const V2AddWarehouseReplicationInput = Schema.Struct({ ), ), }), + type: Schema.Literal("warehouse_replication_change").annotate({ + description: "Resource type.", + }), }), }); export const V2AddWarehouseReplicationOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_change").annotate({ - description: "Resource type.", - }), - id: Schema.String, attributes: Schema.Struct({ - pipeline_id: Schema.String, action: Schema.Union([Schema.Literals(["add", "remove"]), OpenString]), - changed: Schema.Boolean, - application_status: Schema.Union([ - Schema.Literals(["unchanged", "restart_requested", "configured"]).annotate({ - description: - "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion.", - }), - OpenString, - ]), - pipeline_status_before: Schema.String, affected_tables: Schema.Array( Schema.Struct({ id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) @@ -11619,16 +11605,40 @@ export const V2AddWarehouseReplicationOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( + name: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - name: Schema.String.check( + schema: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), }), ), - unchanged_tables: Schema.Array( + application_status: Schema.Union([ + Schema.Literals(["configured", "restart_requested", "unchanged"]).annotate({ + description: + "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion.", + }), + OpenString, + ]), + changed: Schema.Boolean, + includes_future_tables: Schema.Literal(false), + pipeline_id: Schema.String, + pipeline_status_before: Schema.String, + selected_table_count: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + source_data_preserved: Schema.Literal(true), + tables: Schema.Array( Schema.Struct({ + copy_name: Schema.String, id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) .check( Schema.isLessThanOrEqualTo(4294967295).annotate({ @@ -11636,15 +11646,33 @@ export const V2AddWarehouseReplicationOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( + lag_ms: Schema.Union([ + Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), + name: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - name: Schema.String.check( + replication_state: Schema.Union([Schema.String, Schema.Null]), + schema: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), + state: Schema.Union([ + Schema.Union([Schema.Literals(["error", "live", "syncing"]), Schema.Null]).annotate({ + description: + "Last observed table state; null when unavailable. Does not establish completion of this request.", + }), + OpenString, + ]), }), - ), - tables: Schema.Array( + ).annotate({ + description: "Resulting configured selection, with best-effort replication observations.", + }), + unchanged_tables: Schema.Array( Schema.Struct({ id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) .check( @@ -11653,48 +11681,20 @@ export const V2AddWarehouseReplicationOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( + name: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - name: Schema.String.check( + schema: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - copy_name: Schema.String, - state: Schema.Union([ - Schema.Union([Schema.Literals(["syncing", "live", "error"]), Schema.Null]).annotate({ - description: - "Last observed table state; null when unavailable. Does not establish completion of this request.", - }), - OpenString, - ]), - replication_state: Schema.Union([Schema.String, Schema.Null]), - lag_ms: Schema.Union([ - Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), }), - ).annotate({ - description: "Resulting configured selection, with best-effort replication observations.", - }), - selected_table_count: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ) - .check( - Schema.isLessThanOrEqualTo(9007199254740991).annotate({ - expected: "a value less than or equal to 9007199254740991", - }), - ), - warehouse_enabled: Schema.Literal(true), - source_data_preserved: Schema.Literal(true), + ), warehouse_data_retained: Schema.Literal(true), - includes_future_tables: Schema.Literal(false), + warehouse_enabled: Schema.Literal(true), + }), + id: Schema.String, + type: Schema.Literal("warehouse_replication_change").annotate({ + description: "Resource type.", }), }), }); @@ -14544,6 +14544,9 @@ export const V2GetProjectConfigOutput = Schema.Struct({ }), }); export const V2GetWarehouseCapacityInput = Schema.Struct({ + attributes: Schema.optionalKey(Schema.String), + from: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), + interval: Schema.optionalKey(Schema.Literals(["10m", "1d", "1h", "1m", "30m", "5m"])), ref: Schema.String.check( Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), ) @@ -14562,150 +14565,100 @@ export const V2GetWarehouseCapacityInput = Schema.Struct({ }), ), ), - from: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), to: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), - attributes: Schema.optionalKey(Schema.String), - interval: Schema.optionalKey(Schema.Literals(["1m", "5m", "10m", "30m", "1h", "1d"])), }); export const V2GetWarehouseCapacityOutput = Schema.Struct({ data: Schema.Array( Schema.Struct({ - type: Schema.Literal("warehouse_metric").annotate({ description: "Resource type." }), - id: Schema.Union([ - Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", - "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95", - ]), - OpenString, - ]), attributes: Schema.Struct({ - project_ref: Schema.String, + aggregation: Schema.Union([ + Schema.Literals(["mean", "occupied", "p50", "p95", "p99", "rate", "sum"]), + OpenString, + ]), + availability: Schema.Union([ + Schema.Literals([ + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable", + ]), + OpenString, + ]), + definition: Schema.String, + effective: Schema.Struct({ + end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + rate_window_seconds: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + step: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + }), + last_sample_at: Schema.Union([ + Schema.Number.annotate({ + description: + "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + }).check(Schema.isFinite().annotate({ expected: "a finite number" })), + Schema.Null, + ]), metric: Schema.Union([ Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", "assignment_wait_mean", "assignment_wait_p95", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95", + "worker_admission_pending", ]), OpenString, ]), - unit: Schema.Union([ - Schema.Literals(["per_second", "seconds", "queries", "grants"]), - OpenString, - ]), - aggregation: Schema.Union([ - Schema.Literals(["rate", "sum", "mean", "p50", "p95", "p99", "occupied"]), - OpenString, - ]), - definition: Schema.String, + project_ref: Schema.String, requested: Schema.Struct({ + end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), metric: Schema.Union([ Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", "assignment_wait_mean", "assignment_wait_p95", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95", + "worker_admission_pending", ]), OpenString, ]), start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), step: Schema.optionalKey( Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), ), }), - effective: Schema.Struct({ - start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - step: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - rate_window_seconds: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - }), scrape_interval_seconds: Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ), - availability: Schema.Union([ - Schema.Literals([ - "ok", - "partial", - "stale", - "no_data", - "insufficient_data", - "not_provisioned", - "disabled", - "unavailable", - ]), - OpenString, - ]), - last_sample_at: Schema.Union([ - Schema.Number.annotate({ - description: - "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", - }).check(Schema.isFinite().annotate({ expected: "a finite number" })), - Schema.Null, - ]), series: Schema.Array( Schema.Struct({ + coverage: Schema.Struct({ + expected_points: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + returned_points: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + }).annotate({ + description: "Grid point coverage, not proof that every worker was scraped.", + }), labels: Schema.Record(Schema.String, Schema.String), points: Schema.Array( Schema.Struct({ @@ -14718,19 +14671,30 @@ export const V2GetWarehouseCapacityOutput = Schema.Struct({ ]), }), ), - coverage: Schema.Struct({ - returned_points: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - expected_points: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - }).annotate({ - description: "Grid point coverage, not proof that every worker was scraped.", - }), }), ), + unit: Schema.Union([ + Schema.Literals(["grants", "per_second", "queries", "seconds"]), + OpenString, + ]), }), + id: Schema.Union([ + Schema.Literals([ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "query_in_flight", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending", + ]), + OpenString, + ]), + type: Schema.Literal("warehouse_metric").annotate({ description: "Resource type." }), }), ), }); @@ -14749,68 +14713,19 @@ export const V2GetWarehouseConnectionInput = Schema.Struct({ }); export const V2GetWarehouseConnectionOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_connection").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ description: "Project ref" }) - .check( - Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), - ) - .check( - Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ - expected: "a string matching the RegExp ^[a-z]+$", - }), - ), attributes: Schema.Struct({ - project_ref: Schema.String.annotate({ description: "Project ref" }) - .check( - Schema.isMinCodePoints(20).annotate({ - expected: "a string with at least 20 code points", - }), - ) - .check( - Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ - expected: "a string matching the RegExp ^[a-z]+$", - }), - ), - observed_at: Schema.String.annotate({ + access_mode: Schema.Literal("read_only"), + authentication: Schema.Struct({ + credential_source: Schema.Literal("source_project_database"), + default_username: Schema.Literal("postgres"), + membership_guidance: Schema.String, + method: Schema.Literal("database_username_password"), + password_guidance: Schema.String, + required_membership: Schema.Literal("supabase_warehouse_reader"), + }).annotate({ description: - "Time the API retrieved this information. This timestamp does not indicate when connectivity was last verified.", - format: "date-time", + "How to authenticate. No credentials are returned; the password is never exposed by this API.", }), - status: Schema.Union([ - Schema.Literals([ - "available", - "pending", - "not_configured", - "disabling", - "disabled", - "unavailable", - ]).annotate({ - description: - "Configured availability of the Warehouse endpoint, derived from routing and lifecycle state. It is not a connectivity probe: a ready route does not prove a query will succeed.", - }), - OpenString, - ]), - unavailable_reason: Schema.Union([ - Schema.Union([ - Schema.Literals([ - "assignment_unavailable", - "routing_failed", - "observation_unavailable", - "cleanup_failed", - ]), - Schema.Null, - ]).annotate({ - description: "Why the endpoint is unavailable. Null unless status is unavailable.", - }), - OpenString, - ]), - protocol: Schema.Literal("arrow_flight_sql"), endpoint: Schema.Union([ Schema.String.annotate({ description: @@ -14825,6 +14740,11 @@ export const V2GetWarehouseConnectionOutput = Schema.Struct({ }), Schema.Null, ]), + observed_at: Schema.String.annotate({ + description: + "Time the API retrieved this information. This timestamp does not indicate when connectivity was last verified.", + format: "date-time", + }), port: Schema.Union([ Schema.Number.annotate({ description: @@ -14843,7 +14763,22 @@ export const V2GetWarehouseConnectionOutput = Schema.Struct({ ), Schema.Null, ]), - tls_required: Schema.Literal(true), + project_ref: Schema.String.annotate({ description: "Project ref" }) + .check( + Schema.isMinCodePoints(20).annotate({ + expected: "a string with at least 20 code points", + }), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + protocol: Schema.Literal("arrow_flight_sql"), + query_connectivity: Schema.Literal("not_checked"), region: Schema.Union([ Schema.String.annotate({ description: @@ -14853,7 +14788,7 @@ export const V2GetWarehouseConnectionOutput = Schema.Struct({ ]), routing_status: Schema.Union([ Schema.Union([ - Schema.Literals(["pending", "ready", "error", "removed"]), + Schema.Literals(["error", "pending", "ready", "removed"]), Schema.Null, ]).annotate({ description: @@ -14861,23 +14796,55 @@ export const V2GetWarehouseConnectionOutput = Schema.Struct({ }), OpenString, ]), - authentication: Schema.Struct({ - method: Schema.Literal("database_username_password"), - credential_source: Schema.Literal("source_project_database"), - default_username: Schema.Literal("postgres"), - password_guidance: Schema.String, - required_membership: Schema.Literal("supabase_warehouse_reader"), - membership_guidance: Schema.String, - }).annotate({ - description: - "How to authenticate. No credentials are returned; the password is never exposed by this API.", - }), - access_mode: Schema.Literal("read_only"), - query_connectivity: Schema.Literal("not_checked"), + status: Schema.Union([ + Schema.Literals([ + "available", + "disabled", + "disabling", + "not_configured", + "pending", + "unavailable", + ]).annotate({ + description: + "Configured availability of the Warehouse endpoint, derived from routing and lifecycle state. It is not a connectivity probe: a ready route does not prove a query will succeed.", + }), + OpenString, + ]), + tls_required: Schema.Literal(true), + unavailable_reason: Schema.Union([ + Schema.Union([ + Schema.Literals([ + "assignment_unavailable", + "cleanup_failed", + "observation_unavailable", + "routing_failed", + ]), + Schema.Null, + ]).annotate({ + description: "Why the endpoint is unavailable. Null unless status is unavailable.", + }), + OpenString, + ]), }), + id: Schema.String.annotate({ description: "Project ref" }) + .check( + Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + type: Schema.Literal("warehouse_connection").annotate({ description: "Resource type." }), }), }); export const V2GetWarehouseQueryStatsInput = Schema.Struct({ + attributes: Schema.optionalKey(Schema.String), + from: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), + interval: Schema.optionalKey(Schema.Literals(["10m", "1d", "1h", "1m", "30m", "5m"])), ref: Schema.String.check( Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), ) @@ -14896,150 +14863,124 @@ export const V2GetWarehouseQueryStatsInput = Schema.Struct({ }), ), ), - from: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), to: Schema.optionalKey(Schema.String.annotate({ format: "date-time" })), - attributes: Schema.optionalKey(Schema.String), - interval: Schema.optionalKey(Schema.Literals(["1m", "5m", "10m", "30m", "1h", "1d"])), }); export const V2GetWarehouseQueryStatsOutput = Schema.Struct({ data: Schema.Array( Schema.Struct({ - type: Schema.Literal("warehouse_metric").annotate({ description: "Resource type." }), - id: Schema.Union([ - Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", - "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95", - ]), - OpenString, - ]), attributes: Schema.Struct({ - project_ref: Schema.String, - metric: Schema.Union([ + aggregation: Schema.Union([ + Schema.Literals(["mean", "occupied", "p50", "p95", "p99", "rate", "sum"]), + OpenString, + ]), + availability: Schema.Union([ Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", - "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95", + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable", ]), OpenString, ]), - unit: Schema.Union([ - Schema.Literals(["per_second", "seconds", "queries", "grants"]), - OpenString, + definition: Schema.String, + effective: Schema.Struct({ + end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + rate_window_seconds: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + step: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), + }), + last_sample_at: Schema.Union([ + Schema.Number.annotate({ + description: + "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + }).check(Schema.isFinite().annotate({ expected: "a finite number" })), + Schema.Null, ]), - aggregation: Schema.Union([ - Schema.Literals(["rate", "sum", "mean", "p50", "p95", "p99", "occupied"]), + metric: Schema.Union([ + Schema.Literals([ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending", + ]), OpenString, ]), - definition: Schema.String, + project_ref: Schema.String, requested: Schema.Struct({ + end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), metric: Schema.Union([ Schema.Literals([ - "query_rate", - "query_error_rate", - "query_timeout_rate", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", "query_canceled_rate", "query_duration_mean", "query_duration_p50", "query_duration_p95", "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", + "query_error_rate", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", + "query_rate", + "query_timeout_rate", "rpc_duration_mean", "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending", ]), OpenString, ]), start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), step: Schema.optionalKey( Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), ), }), - effective: Schema.Struct({ - start: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - end: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - step: Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })), - rate_window_seconds: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - }), scrape_interval_seconds: Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ), - availability: Schema.Union([ - Schema.Literals([ - "ok", - "partial", - "stale", - "no_data", - "insufficient_data", - "not_provisioned", - "disabled", - "unavailable", - ]), - OpenString, - ]), - last_sample_at: Schema.Union([ - Schema.Number.annotate({ - description: - "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", - }).check(Schema.isFinite().annotate({ expected: "a finite number" })), - Schema.Null, - ]), series: Schema.Array( Schema.Struct({ + coverage: Schema.Struct({ + expected_points: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + returned_points: Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ), + }).annotate({ + description: "Grid point coverage, not proof that every worker was scraped.", + }), labels: Schema.Record(Schema.String, Schema.String), points: Schema.Array( Schema.Struct({ @@ -15052,19 +14993,42 @@ export const V2GetWarehouseQueryStatsOutput = Schema.Struct({ ]), }), ), - coverage: Schema.Struct({ - returned_points: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - expected_points: Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ), - }).annotate({ - description: "Grid point coverage, not proof that every worker was scraped.", - }), }), ), + unit: Schema.Union([ + Schema.Literals(["grants", "per_second", "queries", "seconds"]), + OpenString, + ]), }), + id: Schema.Union([ + Schema.Literals([ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending", + ]), + OpenString, + ]), + type: Schema.Literal("warehouse_metric").annotate({ description: "Resource type." }), }), ), }); @@ -15284,88 +15248,28 @@ export const V2GetWarehouseStatusInput = Schema.Struct({ }); export const V2GetWarehouseStatusOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_context").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ description: "Project ref" }) - .check( - Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), - ) - .check( - Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ - expected: "a string matching the RegExp ^[a-z]+$", - }), - ), attributes: Schema.Struct({ - project_ref: Schema.String.annotate({ description: "Project ref" }) - .check( - Schema.isMinCodePoints(20).annotate({ - expected: "a string with at least 20 code points", - }), - ) - .check( - Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ - expected: "a string matching the RegExp ^[a-z]+$", - }), - ), - observed_at: Schema.String.annotate({ format: "date-time" }), - enabled: Schema.Union([ - Schema.Boolean.annotate({ - description: - "Whether Warehouse is enabled, independently of selected table count. Null means provisioning could not be determined.", - }), - Schema.Null, - ]), - configured_readiness: Schema.Union([ - Schema.Literals(["ready", "not_ready", "unavailable"]).annotate({ + capabilities: Schema.Struct({ + context: Schema.Boolean, + query_explain: Schema.Boolean.annotate({ description: - "Readiness inferred from configuration and replication observations; no query is executed.", + "Whether the Management API supports a query-explain operation. SQL EXPLAIN through the Warehouse connection is independent of this flag.", }), - OpenString, - ]), - query_connectivity: Schema.Literal("not_checked"), - status: Schema.Union([ - Schema.Literals([ - "not_provisioned", - "disabled", - "disabling", - "starting", - "ready", - "stopped", - "stopping", - "degraded", - "unavailable", - ]).annotate({ + replication_add: Schema.Boolean, + replication_remove: Schema.Boolean, + table_layout_read: Schema.Boolean, + table_layout_update: Schema.Boolean, + table_resync: Schema.Boolean, + workload_metrics: Schema.Boolean.annotate({ description: - "Warehouse setup and replication status. Ready means the Warehouse connection is configured and tables are replicating ongoing changes. It does not guarantee that a query will succeed.", - }), - OpenString, - ]), - lifecycle: Schema.Union([ - Schema.Struct({ - status: Schema.Union([ - Schema.Literals(["disabling", "disabled", "deletion_failed"]), - OpenString, - ]), - updated_at: Schema.String.annotate({ format: "date-time" }), - delete_data: Schema.Boolean, + "Query statistics and capacity inspection are supported by the Management API. Metric availability is reported separately.", }), - Schema.Null, - ]), + replication_restart: Schema.Boolean, + }).annotate({ + description: + "Complete operations supported by this API, not caller authorization. Each operation still requires its feature, entitlement and project permission checks.", + }), compute: Schema.Struct({ - status: Schema.Union([ - Schema.Literals(["available", "unavailable", "not_provisioned"]), - OpenString, - ]), - region: Schema.Union([Schema.String, Schema.Null]), - routing_status: Schema.Union([ - Schema.Union([Schema.Literals(["pending", "ready", "error", "removed"]), Schema.Null]), - OpenString, - ]), observed_at: Schema.Union([ Schema.String.annotate({ description: @@ -15374,14 +15278,23 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ }), Schema.Null, ]), - unavailable_reason: Schema.Union([ - Schema.Union([ - Schema.Literals([ + region: Schema.Union([Schema.String, Schema.Null]), + routing_status: Schema.Union([ + Schema.Union([Schema.Literals(["error", "pending", "ready", "removed"]), Schema.Null]), + OpenString, + ]), + status: Schema.Union([ + Schema.Literals(["available", "not_provisioned", "unavailable"]), + OpenString, + ]), + unavailable_reason: Schema.Union([ + Schema.Union([ + Schema.Literals([ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + "observation_unavailable", ]), Schema.Null, ]), @@ -15391,23 +15304,37 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ description: "Configured Warehouse compute and region, which may differ from the source database region. Live availability and capacity are not reported.", }), + configured_readiness: Schema.Union([ + Schema.Literals(["not_ready", "ready", "unavailable"]).annotate({ + description: + "Readiness inferred from configuration and replication observations; no query is executed.", + }), + OpenString, + ]), + enabled: Schema.Union([ + Schema.Boolean.annotate({ + description: + "Whether Warehouse is enabled, independently of selected table count. Null means provisioning could not be determined.", + }), + Schema.Null, + ]), + lifecycle: Schema.Union([ + Schema.Struct({ + delete_data: Schema.Boolean, + status: Schema.Union([ + Schema.Literals(["deletion_failed", "disabled", "disabling"]), + OpenString, + ]), + updated_at: Schema.String.annotate({ format: "date-time" }), + }), + Schema.Null, + ]), + observed_at: Schema.String.annotate({ format: "date-time" }), pipeline: Schema.Union([ Schema.Struct({ id: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - status: Schema.Union([ - Schema.Literals([ - "stopped", - "starting", - "started", - "stopping", - "unknown", - "failed", - "unavailable", - ]), - OpenString, - ]), observed_at: Schema.Union([ Schema.String.annotate({ description: @@ -15416,62 +15343,89 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ }), Schema.Null, ]), + status: Schema.Union([ + Schema.Literals([ + "failed", + "started", + "starting", + "stopped", + "stopping", + "unavailable", + "unknown", + ]), + OpenString, + ]), unavailable_reason: Schema.Union([ Schema.Union([ Schema.Literals([ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + "observation_unavailable", ]), Schema.Null, ]), OpenString, ]), + diagnostic: Schema.Union([ + Schema.Struct({ + code: Schema.Union([ + Schema.Literals([ + "configuration_error", + "crash_loop", + "image_unavailable", + "out_of_memory", + "process_exited", + "runtime_failed", + "startup_failed", + ]), + OpenString, + ]), + exit_code: Schema.Union([ + Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(-9007199254740991).annotate({ + expected: "a value greater than or equal to -9007199254740991", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + Schema.Null, + ]), + message: Schema.String, + }).annotate({ + description: + "Safe classification of the current runtime failure. Does not include worker logs or establish its underlying cause.", + }), + Schema.Null, + ]), }), Schema.Null, ]), - replication: Schema.Struct({ - status: Schema.Union([ - Schema.Literals([ - "available", - "unavailable", - "not_provisioned", - "not_started", - "stopped", - ]), - OpenString, - ]), - observed_at: Schema.Union([ - Schema.String.annotate({ - description: - "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", - format: "date-time", + project_ref: Schema.String.annotate({ description: "Project ref" }) + .check( + Schema.isMinCodePoints(20).annotate({ + expected: "a string with at least 20 code points", }), - Schema.Null, - ]), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + query_connectivity: Schema.Literal("not_checked"), + replication: Schema.Struct({ apply_lag: Schema.Union([ Schema.Struct({ active: Schema.Boolean, - wal_status: Schema.Union([ - Schema.Union([ - Schema.Literals(["reserved", "extended", "unreserved", "lost", "unknown"]), - Schema.Null, - ]), - OpenString, - ]), - write_lag_ms: Schema.Union([ - Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), - flush_lag_ms: Schema.Union([ + feedback_age_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -15495,7 +15449,24 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ ), Schema.Null, ]), - feedback_age_ms: Schema.Union([ + flush_lag_ms: Schema.Union([ + Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), + wal_status: Schema.Union([ + Schema.Union([ + Schema.Literals(["extended", "lost", "reserved", "unknown", "unreserved"]), + Schema.Null, + ]), + OpenString, + ]), + write_lag_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -15511,25 +15482,6 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ }), Schema.Null, ]), - unavailable_reason: Schema.Union([ - Schema.Union([ - Schema.Literals([ - "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", - "cleanup_failed", - ]), - Schema.Null, - ]), - OpenString, - ]), - }), - tables: Schema.Struct({ - status: Schema.Union([ - Schema.Literals(["available", "unavailable", "not_provisioned"]), - OpenString, - ]), observed_at: Schema.Union([ Schema.String.annotate({ description: @@ -15538,19 +15490,48 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ }), Schema.Null, ]), + status: Schema.Union([ + Schema.Literals([ + "available", + "not_provisioned", + "not_started", + "stopped", + "unavailable", + ]), + OpenString, + ]), unavailable_reason: Schema.Union([ Schema.Union([ Schema.Literals([ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + "observation_unavailable", ]), Schema.Null, ]), OpenString, ]), + }), + status: Schema.Union([ + Schema.Literals([ + "degraded", + "disabled", + "disabling", + "not_provisioned", + "ready", + "starting", + "stopped", + "stopping", + "unavailable", + ]).annotate({ + description: + "Warehouse setup and replication status. Ready means the Warehouse connection is configured and tables are replicating ongoing changes. It does not guarantee that a query will succeed.", + }), + OpenString, + ]), + tables: Schema.Struct({ items: Schema.Array( Schema.Struct({ id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) @@ -15560,42 +15541,25 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String, name: Schema.String, replication_state: Schema.Union([ Schema.Union([ Schema.Literals([ - "queued", - "copying_table", "copied_table", - "following_wal", + "copying_table", "error", + "following_wal", + "queued", ]), Schema.Null, ]), OpenString, ]), + schema: Schema.String, sync_lag: Schema.Union([ Schema.Struct({ active: Schema.Boolean, - wal_status: Schema.Union([ - Schema.Union([ - Schema.Literals(["reserved", "extended", "unreserved", "lost", "unknown"]), - Schema.Null, - ]), - OpenString, - ]), - write_lag_ms: Schema.Union([ - Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), - flush_lag_ms: Schema.Union([ + feedback_age_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -15619,7 +15583,7 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ ), Schema.Null, ]), - feedback_age_ms: Schema.Union([ + flush_lag_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -15629,29 +15593,182 @@ export const V2GetWarehouseStatusOutput = Schema.Struct({ ), Schema.Null, ]), - }).annotate({ - description: - "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", - }), - Schema.Null, - ]), - }), - ), - }), - capabilities: Schema.Struct({ - context: Schema.Boolean, - workload_metrics: Schema.Boolean, - query_explain: Schema.Boolean, - table_layout_read: Schema.Boolean, - table_layout_update: Schema.Boolean, - replication_add: Schema.Boolean, - replication_remove: Schema.Boolean, - table_resync: Schema.Boolean, - }).annotate({ - description: - "Complete operations supported by this API, not caller authorization. Each operation still requires its feature, entitlement and project permission checks.", + wal_status: Schema.Union([ + Schema.Union([ + Schema.Literals(["extended", "lost", "reserved", "unknown", "unreserved"]), + Schema.Null, + ]), + OpenString, + ]), + write_lag_ms: Schema.Union([ + Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), + }).annotate({ + description: + "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", + }), + Schema.Null, + ]), + error: Schema.Union([ + Schema.Struct({ + reason: Schema.String, + retry_policy: Schema.Union( + [ + Schema.Struct({ policy: Schema.Literal("no_retry") }), + Schema.Struct({ policy: Schema.Literal("manual_retry") }), + Schema.Struct({ + next_retry: Schema.String, + policy: Schema.Literal("timed_retry"), + }), + ], + { mode: "oneOf" }, + ), + solution: Schema.Union([Schema.String, Schema.Null]), + }), + Schema.Null, + ]), + state_observation: Schema.Union([ + Schema.Literals(["current", "last_known", "unavailable"]), + OpenString, + ]), + }), + ), + observed_at: Schema.Union([ + Schema.String.annotate({ + description: + "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + format: "date-time", + }), + Schema.Null, + ]), + status: Schema.Union([ + Schema.Literals(["available", "not_provisioned", "unavailable"]), + OpenString, + ]), + unavailable_reason: Schema.Union([ + Schema.Union([ + Schema.Literals([ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + "observation_unavailable", + ]), + Schema.Null, + ]), + OpenString, + ]), + progress: Schema.Union([ + Schema.Struct({ + copied_table: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + copying_table: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + error: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + following_wal: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + observation: Schema.Union([ + Schema.Literals(["current", "last_known", "unavailable"]), + OpenString, + ]), + queued: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + selected: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + unknown: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + }).annotate({ + description: + "Observed states of the selected tables, not completion or percentage of a specific mutation. Last-known states may predate a restart or resync. Null when the selection is unavailable.", + }), + Schema.Null, + ]), }), }), + id: Schema.String.annotate({ description: "Project ref" }) + .check( + Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + type: Schema.Literal("warehouse_context").annotate({ description: "Resource type." }), }), }); export const V2GetWarehouseTableInput = Schema.Struct({ @@ -15676,41 +15793,21 @@ export const V2GetWarehouseTableInput = Schema.Struct({ }); export const V2GetWarehouseTableOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_table").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ - description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - }) - .check( - Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ - expected: "a string matching the RegExp ^[1-9]\\d*$", - }), - ), attributes: Schema.Struct({ - schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), - name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), - warehouse_name: Schema.String.annotate({ - description: "Quoted, fully qualified name of the replicated table in the Warehouse.", - }), - status: Schema.Union([ - Schema.Literals(["syncing", "live", "error", "stopped", "unknown"]).annotate({ - description: - "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", - }), - OpenString, - ]), - replication_state: Schema.Union([ - Schema.Union([ - Schema.Literals(["queued", "copying_table", "copied_table", "following_wal", "error"]), - Schema.Null, - ]).annotate({ + lag_ms: Schema.Union([ + Schema.Number.annotate({ description: - "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", - }), - OpenString, + "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + }) + .check(Schema.isFinite().annotate({ expected: "a finite number" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, ]), + name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), observed_at: Schema.Union([ Schema.String.annotate({ description: @@ -15722,22 +15819,7 @@ export const V2GetWarehouseTableOutput = Schema.Struct({ replication_feedback: Schema.Union([ Schema.Struct({ active: Schema.Boolean, - wal_status: Schema.Union([ - Schema.Union([ - Schema.Literals(["reserved", "extended", "unreserved", "lost", "unknown"]), - Schema.Null, - ]), - OpenString, - ]), - write_lag_ms: Schema.Union([ - Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), - flush_lag_ms: Schema.Union([ + feedback_age_ms: Schema.Union([ Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( Schema.isGreaterThanOrEqualTo(0).annotate({ expected: "a value greater than or equal to 0", @@ -15759,7 +15841,7 @@ export const V2GetWarehouseTableOutput = Schema.Struct({ ), Schema.Null, ]), - feedback_age_ms: Schema.Union([ + flush_lag_ms: Schema.Union([ Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( Schema.isGreaterThanOrEqualTo(0).annotate({ expected: "a value greater than or equal to 0", @@ -15768,32 +15850,67 @@ export const V2GetWarehouseTableOutput = Schema.Struct({ Schema.Null, ]), source: Schema.Union([ - Schema.Literals(["table_sync", "pipeline_apply"]).annotate({ + Schema.Literals(["pipeline_apply", "table_sync"]).annotate({ description: "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", }), OpenString, ]), + wal_status: Schema.Union([ + Schema.Union([ + Schema.Literals(["extended", "lost", "reserved", "unknown", "unreserved"]), + Schema.Null, + ]), + OpenString, + ]), + write_lag_ms: Schema.Union([ + Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), }).annotate({ description: "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", }), Schema.Null, ]), - lag_ms: Schema.Union([ - Schema.Number.annotate({ + replication_state: Schema.Union([ + Schema.Union([ + Schema.Literals(["copied_table", "copying_table", "error", "following_wal", "queued"]), + Schema.Null, + ]).annotate({ description: - "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", - }) - .check(Schema.isFinite().annotate({ expected: "a finite number" })) - .check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, + "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + }), + OpenString, + ]), + schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), + status: Schema.Union([ + Schema.Literals(["error", "live", "stopped", "syncing", "unknown"]).annotate({ + description: + "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + }), + OpenString, ]), + warehouse_name: Schema.String.annotate({ + description: "Quoted, fully qualified name of the replicated table in the Warehouse.", + }), }), + id: Schema.String.annotate({ + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }) + .check( + Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ + expected: "a string matching the RegExp ^[1-9]\\d*$", + }), + ), + type: Schema.Literal("warehouse_table").annotate({ description: "Resource type." }), }), }); export const V2GetWarehouseTableLayoutInput = Schema.Struct({ @@ -15815,64 +15932,15 @@ export const V2GetWarehouseTableLayoutInput = Schema.Struct({ expected: "a string matching the RegExp ^[1-9]\\d*$", }), ), -}); -export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ - data: Schema.Struct({ - type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ - description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - }) - .check( - Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ - expected: "a string matching the RegExp ^[1-9]\\d*$", - }), - ), +}); +export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ + data: Schema.Struct({ attributes: Schema.Struct({ - pipeline_id: Schema.String.annotate({ - description: "Warehouse replication pipeline identity.", - }), - schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), - name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), application_status: Schema.String.annotate({ description: "Backend orchestration state. Runtime acceptance does not establish that the desired layout has been observed in the catalog.", }), - reset_table: Schema.Boolean.annotate({ - description: - "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", - }), desired: Schema.Struct({ - sort_by: Schema.Union([ - Schema.Union( - [ - Schema.Struct({ kind: Schema.Literal("none") }), - Schema.Struct({ kind: Schema.Literal("primary_key") }), - Schema.Struct({ - kind: Schema.Literal("columns"), - columns: Schema.Array( - Schema.Struct({ - name: Schema.String.annotate({ description: "Source column name." }), - direction: Schema.Union([Schema.Literals(["asc", "desc"]), OpenString]), - nulls: Schema.Union([ - Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ - description: "Null placement. Null uses DuckLake's default placement.", - }), - OpenString, - ]), - }), - ), - }), - ], - { mode: "oneOf" }, - ), - Schema.Null, - ]).annotate({ - description: - "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", - }), partition_by: Schema.Union([ Schema.Array( Schema.Struct({ @@ -15885,7 +15953,6 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ Schema.Struct({ kind: Schema.Literal("day") }), Schema.Struct({ kind: Schema.Literal("hour") }), Schema.Struct({ - kind: Schema.Literal("bucket"), count: Schema.Number.annotate({ description: "Number of hash buckets." }) .check(Schema.isInt().annotate({ expected: "an integer" })) .check( @@ -15896,6 +15963,7 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ .check( Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" }), ), + kind: Schema.Literal("bucket"), }), ], { mode: "oneOf" }, @@ -15907,12 +15975,39 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ }), Schema.Null, ]), + sort_by: Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("none") }), + Schema.Struct({ kind: Schema.Literal("primary_key") }), + Schema.Struct({ + columns: Schema.Array( + Schema.Struct({ + direction: Schema.Union([Schema.Literals(["asc", "desc"]), OpenString]), + name: Schema.String.annotate({ description: "Source column name." }), + nulls: Schema.Union([ + Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ + description: "Null placement. Null uses DuckLake's default placement.", + }), + OpenString, + ]), + }), + ), + kind: Schema.Literal("columns"), + }), + Schema.Null, + ], + { mode: "oneOf" }, + ).annotate({ + description: + "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", + }), }).annotate({ description: "Saved layout rules. The replicator applies them on start and hourly, so they can differ from the observed layout.", }), + name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), observation_status: Schema.Union([ - Schema.Literals(["observed", "table_missing", "unavailable", "not_requested"]).annotate({ + Schema.Literals(["not_requested", "observed", "table_missing", "unavailable"]).annotate({ description: "observed when the DuckLake catalog was read, table_missing when the catalog has no table for it yet, unavailable when the catalog could not be read, and not_requested when an update returned without reading the catalog.", }), @@ -15920,14 +16015,9 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ ]), observed: Schema.Union([ Schema.Struct({ - sort_by: Schema.Array( - Schema.Struct({ - expression: Schema.String, - direction: Schema.String, - nulls: Schema.String, - }), - ).annotate({ - description: "Active sort expressions in key order, as the catalog reports them.", + observed_at: Schema.String.annotate({ + description: "Time the catalog metadata was read.", + format: "date-time", }), partition_by: Schema.Array( Schema.Struct({ column: Schema.String, transform: Schema.String }), @@ -15935,9 +16025,14 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ description: "Active partition keys in key order, with transforms as the catalog reports them, for example bucket(16).", }), - observed_at: Schema.String.annotate({ - description: "Time the catalog metadata was read.", - format: "date-time", + sort_by: Schema.Array( + Schema.Struct({ + direction: Schema.String, + expression: Schema.String, + nulls: Schema.String, + }), + ).annotate({ + description: "Active sort expressions in key order, as the catalog reports them.", }), }).annotate({ description: @@ -15945,7 +16040,27 @@ export const V2GetWarehouseTableLayoutOutput = Schema.Struct({ }), Schema.Null, ]), + pipeline_id: Schema.String.annotate({ + description: "Warehouse replication pipeline identity.", + }), + reset_table: Schema.Boolean.annotate({ + description: + "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", + }), + schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), }), + id: Schema.String.annotate({ + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }) + .check( + Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ + expected: "a string matching the RegExp ^[1-9]\\d*$", + }), + ), + type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), }), }); export const V2GetWarehouseTeardownInput = Schema.Struct({ @@ -17015,41 +17130,21 @@ export const V2ListWarehouseTablesInput = Schema.Struct({ export const V2ListWarehouseTablesOutput = Schema.Struct({ data: Schema.Array( Schema.Struct({ - type: Schema.Literal("warehouse_table").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ - description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - }) - .check( - Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ - expected: "a string matching the RegExp ^[1-9]\\d*$", - }), - ), attributes: Schema.Struct({ - schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), - name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), - warehouse_name: Schema.String.annotate({ - description: "Quoted, fully qualified name of the replicated table in the Warehouse.", - }), - status: Schema.Union([ - Schema.Literals(["syncing", "live", "error", "stopped", "unknown"]).annotate({ - description: - "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", - }), - OpenString, - ]), - replication_state: Schema.Union([ - Schema.Union([ - Schema.Literals(["queued", "copying_table", "copied_table", "following_wal", "error"]), - Schema.Null, - ]).annotate({ + lag_ms: Schema.Union([ + Schema.Number.annotate({ description: - "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", - }), - OpenString, + "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + }) + .check(Schema.isFinite().annotate({ expected: "a finite number" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, ]), + name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), observed_at: Schema.Union([ Schema.String.annotate({ description: @@ -17061,24 +17156,7 @@ export const V2ListWarehouseTablesOutput = Schema.Struct({ replication_feedback: Schema.Union([ Schema.Struct({ active: Schema.Boolean, - wal_status: Schema.Union([ - Schema.Union([ - Schema.Literals(["reserved", "extended", "unreserved", "lost", "unknown"]), - Schema.Null, - ]), - OpenString, - ]), - write_lag_ms: Schema.Union([ - Schema.Number.check( - Schema.isFinite().annotate({ expected: "a finite number" }), - ).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), - flush_lag_ms: Schema.Union([ + feedback_age_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -17102,7 +17180,7 @@ export const V2ListWarehouseTablesOutput = Schema.Struct({ ), Schema.Null, ]), - feedback_age_ms: Schema.Union([ + flush_lag_ms: Schema.Union([ Schema.Number.check( Schema.isFinite().annotate({ expected: "a finite number" }), ).check( @@ -17113,32 +17191,69 @@ export const V2ListWarehouseTablesOutput = Schema.Struct({ Schema.Null, ]), source: Schema.Union([ - Schema.Literals(["table_sync", "pipeline_apply"]).annotate({ + Schema.Literals(["pipeline_apply", "table_sync"]).annotate({ description: "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", }), OpenString, ]), + wal_status: Schema.Union([ + Schema.Union([ + Schema.Literals(["extended", "lost", "reserved", "unknown", "unreserved"]), + Schema.Null, + ]), + OpenString, + ]), + write_lag_ms: Schema.Union([ + Schema.Number.check( + Schema.isFinite().annotate({ expected: "a finite number" }), + ).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), }).annotate({ description: "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", }), Schema.Null, ]), - lag_ms: Schema.Union([ - Schema.Number.annotate({ + replication_state: Schema.Union([ + Schema.Union([ + Schema.Literals(["copied_table", "copying_table", "error", "following_wal", "queued"]), + Schema.Null, + ]).annotate({ description: - "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", - }) - .check(Schema.isFinite().annotate({ expected: "a finite number" })) - .check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, + "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + }), + OpenString, + ]), + schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), + status: Schema.Union([ + Schema.Literals(["error", "live", "stopped", "syncing", "unknown"]).annotate({ + description: + "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + }), + OpenString, ]), + warehouse_name: Schema.String.annotate({ + description: "Quoted, fully qualified name of the replicated table in the Warehouse.", + }), }), + id: Schema.String.annotate({ + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }) + .check( + Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ + expected: "a string matching the RegExp ^[1-9]\\d*$", + }), + ), + type: Schema.Literal("warehouse_table").annotate({ description: "Resource type." }), }), ), }); @@ -20107,9 +20222,6 @@ export const V2RemoveWarehouseReplicationInput = Schema.Struct({ }), ), data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_change").annotate({ - description: "Resource type.", - }), attributes: Schema.Struct({ schema: Schema.String.annotate({ description: "Literal source PostgreSQL schema. Omit table to select its current tables.", @@ -20122,28 +20234,58 @@ export const V2RemoveWarehouseReplicationInput = Schema.Struct({ ), ), }), + type: Schema.Literal("warehouse_replication_change").annotate({ + description: "Resource type.", + }), }), }); export const V2RemoveWarehouseReplicationOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_change").annotate({ - description: "Resource type.", - }), - id: Schema.String, attributes: Schema.Struct({ - pipeline_id: Schema.String, action: Schema.Union([Schema.Literals(["add", "remove"]), OpenString]), - changed: Schema.Boolean, + affected_tables: Schema.Array( + Schema.Struct({ + id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isLessThanOrEqualTo(4294967295).annotate({ + expected: "a value less than or equal to 4294967295", + }), + ) + .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), + name: Schema.String.check( + Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), + ), + schema: Schema.String.check( + Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), + ), + }), + ), application_status: Schema.Union([ - Schema.Literals(["unchanged", "restart_requested", "configured"]).annotate({ + Schema.Literals(["configured", "restart_requested", "unchanged"]).annotate({ description: "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion.", }), OpenString, ]), + changed: Schema.Boolean, + includes_future_tables: Schema.Literal(false), + pipeline_id: Schema.String, pipeline_status_before: Schema.String, - affected_tables: Schema.Array( + selected_table_count: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(9007199254740991).annotate({ + expected: "a value less than or equal to 9007199254740991", + }), + ), + source_data_preserved: Schema.Literal(true), + tables: Schema.Array( Schema.Struct({ + copy_name: Schema.String, id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) .check( Schema.isLessThanOrEqualTo(4294967295).annotate({ @@ -20151,14 +20293,32 @@ export const V2RemoveWarehouseReplicationOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( + lag_ms: Schema.Union([ + Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ), + Schema.Null, + ]), + name: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - name: Schema.String.check( + replication_state: Schema.Union([Schema.String, Schema.Null]), + schema: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), + state: Schema.Union([ + Schema.Union([Schema.Literals(["error", "live", "syncing"]), Schema.Null]).annotate({ + description: + "Last observed table state; null when unavailable. Does not establish completion of this request.", + }), + OpenString, + ]), }), - ), + ).annotate({ + description: "Resulting configured selection, with best-effort replication observations.", + }), unchanged_tables: Schema.Array( Schema.Struct({ id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) @@ -20168,69 +20328,24 @@ export const V2RemoveWarehouseReplicationOutput = Schema.Struct({ }), ) .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( - Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), - ), name: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - }), - ), - tables: Schema.Array( - Schema.Struct({ - id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isLessThanOrEqualTo(4294967295).annotate({ - expected: "a value less than or equal to 4294967295", - }), - ) - .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), schema: Schema.String.check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), - name: Schema.String.check( - Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), - ), - copy_name: Schema.String, - state: Schema.Union([ - Schema.Union([Schema.Literals(["syncing", "live", "error"]), Schema.Null]).annotate({ - description: - "Last observed table state; null when unavailable. Does not establish completion of this request.", - }), - OpenString, - ]), - replication_state: Schema.Union([Schema.String, Schema.Null]), - lag_ms: Schema.Union([ - Schema.Number.check(Schema.isFinite().annotate({ expected: "a finite number" })).check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ), - Schema.Null, - ]), }), - ).annotate({ - description: "Resulting configured selection, with best-effort replication observations.", - }), - selected_table_count: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ) - .check( - Schema.isLessThanOrEqualTo(9007199254740991).annotate({ - expected: "a value less than or equal to 9007199254740991", - }), - ), - warehouse_enabled: Schema.Literal(true), - source_data_preserved: Schema.Literal(true), + ), warehouse_data_retained: Schema.Literal(true), - includes_future_tables: Schema.Literal(false), + warehouse_enabled: Schema.Literal(true), + }), + id: Schema.String, + type: Schema.Literal("warehouse_replication_change").annotate({ + description: "Resource type.", }), }), }); -export const V2ResyncWarehouseReplicationInput = Schema.Struct({ +export const V2RestartWarehouseReplicationInput = Schema.Struct({ ref: Schema.String.check( Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), ) @@ -20242,44 +20357,78 @@ export const V2ResyncWarehouseReplicationInput = Schema.Struct({ expected: "a string matching the RegExp ^[a-z]+$", }), ), +}); +export const V2RestartWarehouseReplicationOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_resync").annotate({ + attributes: Schema.Struct({ + action: Schema.Union([Schema.Literals(["restart", "start"]), OpenString]), + application_status: Schema.Literal("accepted").annotate({ + description: + "The runtime request was accepted. This does not establish resumed replication or completed initial copies.", + }), + pipeline_id: Schema.String, + pipeline_status_before: Schema.String, + }), + id: Schema.String, + type: Schema.Literal("warehouse_replication_restart").annotate({ description: "Resource type.", }), + }), +}); +export const V2ResyncWarehouseReplicationInput = Schema.Struct({ + ref: Schema.String.check( + Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + data: Schema.Struct({ attributes: Schema.Struct({ schema: Schema.String.annotate({ - description: "Literal source PostgreSQL schema. Omit table to select its current tables.", + description: "Literal source PostgreSQL schema of the table.", }).check(Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" })), table: Schema.String.annotate({ description: "Literal name of the single source table to reset and recopy.", }).check(Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" })), }), + type: Schema.Literal("warehouse_replication_resync").annotate({ + description: "Resource type.", + }), }), }); export const V2ResyncWarehouseReplicationOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_replication_resync").annotate({ - description: "Resource type.", - }), - id: Schema.String, attributes: Schema.Struct({ + application_status: Schema.Literal("reset").annotate({ + description: + "ETL reset replication state. Destination rebuild and recopy may still be pending.", + }), pipeline_id: Schema.String.annotate({ description: "Pipeline ID" }).check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), ), + source_data_preserved: Schema.Literal(true), + source_table: Schema.Struct({ + id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isLessThanOrEqualTo(4294967295).annotate({ + expected: "a value less than or equal to 4294967295", + }), + ) + .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), + name: Schema.String.check( + Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), + ), + schema: Schema.String.check( + Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), + ), + }), tables: Schema.Array( Schema.Struct({ - table_id: Schema.Number.annotate({ description: "Table id (Postgres OID)" }) - .check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isGreaterThanOrEqualTo(0).annotate({ - expected: "a value greater than or equal to 0", - }), - ) - .check( - Schema.isLessThanOrEqualTo(4294967295).annotate({ - expected: "a value less than or equal to 4294967295", - }), - ), new_state: Schema.Union( [ Schema.Struct({ name: Schema.Literal("queued") }), @@ -20289,46 +20438,42 @@ export const V2ResyncWarehouseReplicationOutput = Schema.Struct({ Schema.Struct({ name: Schema.Literal("error"), reason: Schema.String, - solution: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), retry_policy: Schema.Union( [ Schema.Struct({ policy: Schema.Literal("no_retry") }), Schema.Struct({ policy: Schema.Literal("manual_retry") }), Schema.Struct({ - policy: Schema.Literal("timed_retry"), next_retry: Schema.String.annotate({ description: "Next retry time (RFC 3339 timestamp)", }), + policy: Schema.Literal("timed_retry"), }), ], { mode: "oneOf" }, ), + solution: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), }), ], { mode: "oneOf" }, ).annotate({ description: "Table replication state" }), + table_id: Schema.Number.annotate({ description: "Table id (Postgres OID)" }) + .check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isGreaterThanOrEqualTo(0).annotate({ + expected: "a value greater than or equal to 0", + }), + ) + .check( + Schema.isLessThanOrEqualTo(4294967295).annotate({ + expected: "a value less than or equal to 4294967295", + }), + ), }), ).annotate({ description: "Rolled back tables" }), - source_table: Schema.Struct({ - id: Schema.Number.check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isLessThanOrEqualTo(4294967295).annotate({ - expected: "a value less than or equal to 4294967295", - }), - ) - .check(Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" })), - schema: Schema.String.check( - Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), - ), - name: Schema.String.check( - Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), - ), - }), - source_data_preserved: Schema.Literal(true), - application_status: Schema.Literal("reset").annotate({ - description: - "ETL reset replication state. Destination rebuild and recopy may still be pending.", - }), + }), + id: Schema.String, + type: Schema.Literal("warehouse_replication_resync").annotate({ + description: "Resource type.", }), }), }); @@ -21143,75 +21288,33 @@ export const V2UpdateNotebookOutput = Schema.Struct({ ], { mode: "oneOf" }, ), - ), - }), - }), - }), -}); -export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ - ref: Schema.String.check( - Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), - ) - .check( - Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ - expected: "a string matching the RegExp ^[a-z]+$", - }), - ), - table_id: Schema.String.check( - Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), - ).check( - Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ - expected: "a string matching the RegExp ^[1-9]\\d*$", - }), - ), - data: Schema.Struct({ - type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), - attributes: Schema.Union([ - Schema.Struct({ - reset_table: Schema.optionalKey( - Schema.Boolean.annotate({ - description: - "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", - }), - ), - sort_by: Schema.Union([ - Schema.Union( - [ - Schema.Struct({ kind: Schema.Literal("none") }), - Schema.Struct({ kind: Schema.Literal("primary_key") }), - Schema.Struct({ - kind: Schema.Literal("columns"), - columns: Schema.Array( - Schema.Struct({ - name: Schema.String.annotate({ description: "Source column name." }).check( - Schema.isMinLength(1).annotate({ - expected: "a value with a length of at least 1", - }), - ), - direction: Schema.Literals(["asc", "desc"]), - nulls: Schema.optionalKey( - Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ - description: "Null placement. Null uses DuckLake's default placement.", - }), - ), - }), - ).check( - Schema.isMinLength(1).annotate({ - expected: "a value with a length of at least 1", - }), - ), - }), - ], - { mode: "oneOf" }, - ), - Schema.Null, - ]).annotate({ - description: - "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", - }), + ), + }), + }), + }), +}); +export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ + ref: Schema.String.check( + Schema.isMinCodePoints(20).annotate({ expected: "a string with at least 20 code points" }), + ) + .check( + Schema.isMaxCodePoints(20).annotate({ expected: "a string with at most 20 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[a-z]+$", "u")).annotate({ + expected: "a string matching the RegExp ^[a-z]+$", + }), + ), + table_id: Schema.String.check( + Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), + ).check( + Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ + expected: "a string matching the RegExp ^[1-9]\\d*$", + }), + ), + data: Schema.Struct({ + attributes: Schema.Union([ + Schema.Struct({ partition_by: Schema.optionalKey( Schema.Union([ Schema.Array( @@ -21229,7 +21332,6 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ Schema.Struct({ kind: Schema.Literal("day") }), Schema.Struct({ kind: Schema.Literal("hour") }), Schema.Struct({ - kind: Schema.Literal("bucket"), count: Schema.Number.annotate({ description: "Number of hash buckets." }) .check(Schema.isInt().annotate({ expected: "an integer" })) .check( @@ -21240,6 +21342,7 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ .check( Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" }), ), + kind: Schema.Literal("bucket"), }), ], { mode: "oneOf" }, @@ -21247,13 +21350,90 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ }), ).annotate({ description: - "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", + 'Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{"column":"event_at","transform":{"kind":"day"}}]`. Bucket example: `[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.', }), Schema.Null, ]), ), + reset_table: Schema.optionalKey( + Schema.Boolean.annotate({ + description: + "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", + }), + ), + sort_by: Schema.Union([ + Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("none") }), + Schema.Struct({ kind: Schema.Literal("primary_key") }), + Schema.Struct({ + columns: Schema.Array( + Schema.Struct({ + direction: Schema.Literals(["asc", "desc"]), + name: Schema.String.annotate({ description: "Source column name." }).check( + Schema.isMinLength(1).annotate({ + expected: "a value with a length of at least 1", + }), + ), + nulls: Schema.optionalKey( + Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ + description: "Null placement. Null uses DuckLake's default placement.", + }), + ), + }), + ).check( + Schema.isMinLength(1).annotate({ + expected: "a value with a length of at least 1", + }), + ), + kind: Schema.Literal("columns"), + }), + ], + { mode: "oneOf" }, + ), + Schema.Null, + ]).annotate({ + description: + 'Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}`. Sort by the primary key with `{"kind":"primary_key"}` or clear sorting with `{"kind":"none"}`.', + }), }), Schema.Struct({ + partition_by: Schema.Union([ + Schema.Array( + Schema.Struct({ + column: Schema.String.annotate({ description: "Source column name." }).check( + Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), + ), + transform: Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("identity") }), + Schema.Struct({ kind: Schema.Literal("year") }), + Schema.Struct({ kind: Schema.Literal("month") }), + Schema.Struct({ kind: Schema.Literal("day") }), + Schema.Struct({ kind: Schema.Literal("hour") }), + Schema.Struct({ + count: Schema.Number.annotate({ description: "Number of hash buckets." }) + .check(Schema.isInt().annotate({ expected: "an integer" })) + .check( + Schema.isLessThanOrEqualTo(2147483647).annotate({ + expected: "a value less than or equal to 2147483647", + }), + ) + .check( + Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" }), + ), + kind: Schema.Literal("bucket"), + }), + ], + { mode: "oneOf" }, + ), + }), + ).annotate({ + description: + 'Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{"column":"event_at","transform":{"kind":"day"}}]`. Bucket example: `[{"column":"tenant_id","transform":{"kind":"bucket","count":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.', + }), + Schema.Null, + ]), reset_table: Schema.optionalKey( Schema.Boolean.annotate({ description: @@ -21267,15 +21447,14 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ Schema.Struct({ kind: Schema.Literal("none") }), Schema.Struct({ kind: Schema.Literal("primary_key") }), Schema.Struct({ - kind: Schema.Literal("columns"), columns: Schema.Array( Schema.Struct({ + direction: Schema.Literals(["asc", "desc"]), name: Schema.String.annotate({ description: "Source column name." }).check( Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1", }), ), - direction: Schema.Literals(["asc", "desc"]), nulls: Schema.optionalKey( Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ description: "Null placement. Null uses DuckLake's default placement.", @@ -21287,6 +21466,7 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ expected: "a value with a length of at least 1", }), ), + kind: Schema.Literal("columns"), }), ], { mode: "oneOf" }, @@ -21294,106 +21474,22 @@ export const V2UpdateWarehouseTableLayoutInput = Schema.Struct({ Schema.Null, ]).annotate({ description: - "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", + 'Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{"kind":"columns","columns":[{"name":"tenant_id","direction":"asc"},{"name":"event_at","direction":"desc","nulls":"last"}]}`. Sort by the primary key with `{"kind":"primary_key"}` or clear sorting with `{"kind":"none"}`.', }), ), - partition_by: Schema.Union([ - Schema.Array( - Schema.Struct({ - column: Schema.String.annotate({ description: "Source column name." }).check( - Schema.isMinLength(1).annotate({ expected: "a value with a length of at least 1" }), - ), - transform: Schema.Union( - [ - Schema.Struct({ kind: Schema.Literal("identity") }), - Schema.Struct({ kind: Schema.Literal("year") }), - Schema.Struct({ kind: Schema.Literal("month") }), - Schema.Struct({ kind: Schema.Literal("day") }), - Schema.Struct({ kind: Schema.Literal("hour") }), - Schema.Struct({ - kind: Schema.Literal("bucket"), - count: Schema.Number.annotate({ description: "Number of hash buckets." }) - .check(Schema.isInt().annotate({ expected: "an integer" })) - .check( - Schema.isLessThanOrEqualTo(2147483647).annotate({ - expected: "a value less than or equal to 2147483647", - }), - ) - .check( - Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" }), - ), - }), - ], - { mode: "oneOf" }, - ), - }), - ).annotate({ - description: - "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", - }), - Schema.Null, - ]), }), ]), + type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), }), }); export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ data: Schema.Struct({ - type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), - id: Schema.String.annotate({ - description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - }) - .check( - Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), - ) - .check( - Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ - expected: "a string matching the RegExp ^[1-9]\\d*$", - }), - ), attributes: Schema.Struct({ - pipeline_id: Schema.String.annotate({ - description: "Warehouse replication pipeline identity.", - }), - schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), - name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), application_status: Schema.String.annotate({ description: "Backend orchestration state. Runtime acceptance does not establish that the desired layout has been observed in the catalog.", }), - reset_table: Schema.Boolean.annotate({ - description: - "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", - }), desired: Schema.Struct({ - sort_by: Schema.Union([ - Schema.Union( - [ - Schema.Struct({ kind: Schema.Literal("none") }), - Schema.Struct({ kind: Schema.Literal("primary_key") }), - Schema.Struct({ - kind: Schema.Literal("columns"), - columns: Schema.Array( - Schema.Struct({ - name: Schema.String.annotate({ description: "Source column name." }), - direction: Schema.Union([Schema.Literals(["asc", "desc"]), OpenString]), - nulls: Schema.Union([ - Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ - description: "Null placement. Null uses DuckLake's default placement.", - }), - OpenString, - ]), - }), - ), - }), - ], - { mode: "oneOf" }, - ), - Schema.Null, - ]).annotate({ - description: - "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", - }), partition_by: Schema.Union([ Schema.Array( Schema.Struct({ @@ -21406,7 +21502,6 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ Schema.Struct({ kind: Schema.Literal("day") }), Schema.Struct({ kind: Schema.Literal("hour") }), Schema.Struct({ - kind: Schema.Literal("bucket"), count: Schema.Number.annotate({ description: "Number of hash buckets." }) .check(Schema.isInt().annotate({ expected: "an integer" })) .check( @@ -21417,6 +21512,7 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ .check( Schema.isGreaterThan(0).annotate({ expected: "a value greater than 0" }), ), + kind: Schema.Literal("bucket"), }), ], { mode: "oneOf" }, @@ -21428,12 +21524,39 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ }), Schema.Null, ]), + sort_by: Schema.Union( + [ + Schema.Struct({ kind: Schema.Literal("none") }), + Schema.Struct({ kind: Schema.Literal("primary_key") }), + Schema.Struct({ + columns: Schema.Array( + Schema.Struct({ + direction: Schema.Union([Schema.Literals(["asc", "desc"]), OpenString]), + name: Schema.String.annotate({ description: "Source column name." }), + nulls: Schema.Union([ + Schema.Union([Schema.Literals(["first", "last"]), Schema.Null]).annotate({ + description: "Null placement. Null uses DuckLake's default placement.", + }), + OpenString, + ]), + }), + ), + kind: Schema.Literal("columns"), + }), + Schema.Null, + ], + { mode: "oneOf" }, + ).annotate({ + description: + "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", + }), }).annotate({ description: "Saved layout rules. The replicator applies them on start and hourly, so they can differ from the observed layout.", }), + name: Schema.String.annotate({ description: "Source PostgreSQL table name." }), observation_status: Schema.Union([ - Schema.Literals(["observed", "table_missing", "unavailable", "not_requested"]).annotate({ + Schema.Literals(["not_requested", "observed", "table_missing", "unavailable"]).annotate({ description: "observed when the DuckLake catalog was read, table_missing when the catalog has no table for it yet, unavailable when the catalog could not be read, and not_requested when an update returned without reading the catalog.", }), @@ -21441,14 +21564,9 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ ]), observed: Schema.Union([ Schema.Struct({ - sort_by: Schema.Array( - Schema.Struct({ - expression: Schema.String, - direction: Schema.String, - nulls: Schema.String, - }), - ).annotate({ - description: "Active sort expressions in key order, as the catalog reports them.", + observed_at: Schema.String.annotate({ + description: "Time the catalog metadata was read.", + format: "date-time", }), partition_by: Schema.Array( Schema.Struct({ column: Schema.String, transform: Schema.String }), @@ -21456,9 +21574,14 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ description: "Active partition keys in key order, with transforms as the catalog reports them, for example bucket(16).", }), - observed_at: Schema.String.annotate({ - description: "Time the catalog metadata was read.", - format: "date-time", + sort_by: Schema.Array( + Schema.Struct({ + direction: Schema.String, + expression: Schema.String, + nulls: Schema.String, + }), + ).annotate({ + description: "Active sort expressions in key order, as the catalog reports them.", }), }).annotate({ description: @@ -21466,7 +21589,27 @@ export const V2UpdateWarehouseTableLayoutOutput = Schema.Struct({ }), Schema.Null, ]), + pipeline_id: Schema.String.annotate({ + description: "Warehouse replication pipeline identity.", + }), + reset_table: Schema.Boolean.annotate({ + description: + "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", + }), + schema: Schema.String.annotate({ description: "Source PostgreSQL schema of the table." }), }), + id: Schema.String.annotate({ + description: "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + }) + .check( + Schema.isMaxCodePoints(10).annotate({ expected: "a string with at most 10 code points" }), + ) + .check( + Schema.isPattern(new RegExp("^[1-9]\\d*$", "u")).annotate({ + expected: "a string matching the RegExp ^[1-9]\\d*$", + }), + ), + type: Schema.Literal("warehouse_table_layout").annotate({ description: "Resource type." }), }), }); export const V1ApplyAMigrationOutput = Schema.Void; @@ -21763,6 +21906,7 @@ export const openApiOperationIdMap = { "v2-projects-ref-webhooks-endpoints-post": "v2ProjectsRefWebhooksEndpointsPost", "v2-remove-organization-members": "v2RemoveOrganizationMembers", "v2-remove-warehouse-replication": "v2RemoveWarehouseReplication", + "v2-restart-warehouse-replication": "v2RestartWarehouseReplication", "v2-resync-warehouse-replication": "v2ResyncWarehouseReplication", "v2-run-project-advisors": "v2RunProjectAdvisors", "v2-transfer-a-project": "v2TransferAProject", @@ -24962,11 +25106,11 @@ export const operationDefinitions = { v2GetWarehouseCapacity: { id: "v2GetWarehouseCapacity", description: - "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use since or both from and to; the default is the last 30 minutes. Each measurement includes its definition, unit, aggregation, requested and effective ranges, rate_window_seconds, source-sample freshness, availability, coverage, and full series with dimension labels such as reason, kind, and result. Executor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or null; they do not establish healthy or idle capacity. Point timestamps are evaluation times; last_sample_at is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. Each request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.\n\nThis endpoint is currently in its **Alpha** stage.", + "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use `--since` or specify both `--from` and `--to`; the default is the last 30 minutes.\n\nEach measurement includes its definition, unit, aggregation, requested and effective ranges, `rate_window_seconds`, source-sample freshness, availability, coverage, and full series with dimension labels such as `reason`, `kind`, and `result`.\n\nExecutor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or `null`; they do not establish healthy or idle capacity.\n\nPoint timestamps are evaluation times; `last_sample_at` is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range.\n\nEach request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.\n\nThis endpoint is currently in its **Alpha** stage.", method: "GET", path: "/v2/projects/{ref}/warehouse/capacity", pathParams: ["ref"], - queryParams: ["since", "from", "to", "attributes", "interval"], + queryParams: ["attributes", "from", "interval", "since", "to"], headerParams: [], requestBody: { kind: "none" }, response: { kind: "json" }, @@ -24976,7 +25120,7 @@ export const operationDefinitions = { v2GetWarehouseConnection: { id: "v2GetWarehouseConnection", description: - "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: usql -W 'flightsql://postgres@:443?tls=enabled'.\n\nThis endpoint is currently in its **Alpha** stage.", + "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: `usql -W 'flightsql://postgres@:443?tls=enabled'`.\n\nThis endpoint is currently in its **Alpha** stage.", method: "GET", path: "/v2/projects/{ref}/warehouse/connection", pathParams: ["ref"], @@ -24994,7 +25138,7 @@ export const operationDefinitions = { method: "GET", path: "/v2/projects/{ref}/warehouse/query-stats", pathParams: ["ref"], - queryParams: ["since", "from", "to", "attributes", "interval"], + queryParams: ["attributes", "from", "interval", "since", "to"], headerParams: [], requestBody: { kind: "none" }, response: { kind: "json" }, @@ -25018,7 +25162,7 @@ export const operationDefinitions = { v2GetWarehouseStatus: { id: "v2GetWarehouseStatus", description: - "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions.\n\nThis endpoint is currently in its **Alpha** stage.", + "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection.\n\nThis endpoint is currently in its **Alpha** stage.", method: "GET", path: "/v2/projects/{ref}/warehouse/status", pathParams: ["ref"], @@ -25520,6 +25664,20 @@ export const operationDefinitions = { inputSchema: V2RemoveWarehouseReplicationInput, outputSchema: V2RemoveWarehouseReplicationOutput, }, + v2RestartWarehouseReplication: { + id: "v2RestartWarehouseReplication", + description: + "Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response.\n\nThis endpoint is currently in its **Alpha** stage.", + method: "POST", + path: "/v2/projects/{ref}/warehouse/replication/restart", + pathParams: ["ref"], + queryParams: [], + headerParams: [], + requestBody: { kind: "none" }, + response: { kind: "json" }, + inputSchema: V2RestartWarehouseReplicationInput, + outputSchema: V2RestartWarehouseReplicationOutput, + }, v2ResyncWarehouseReplication: { id: "v2ResyncWarehouseReplication", description: diff --git a/packages/api/src/generated/effect-client.ts b/packages/api/src/generated/effect-client.ts index 07abc05da8..c774514db3 100644 --- a/packages/api/src/generated/effect-client.ts +++ b/packages/api/src/generated/effect-client.ts @@ -3812,6 +3812,22 @@ export const versionedEffectOperations = { options, ); }), + restartWarehouseReplication: ( + input: typeof operationDefinitions.v2RestartWarehouseReplication.inputSchema.Type, + options?: SupabaseApiRequestOptions, + ): Effect.Effect< + typeof operationDefinitions.v2RestartWarehouseReplication.outputSchema.Type, + SupabaseApiError, + SupabaseApiClient + > => + Effect.gen(function* () { + const client = yield* SupabaseApiClient; + return yield* client.execute<"v2RestartWarehouseReplication">( + operationDefinitions.v2RestartWarehouseReplication, + input, + options, + ); + }), resyncWarehouseReplication: ( input: typeof operationDefinitions.v2ResyncWarehouseReplication.inputSchema.Type, options?: SupabaseApiRequestOptions, diff --git a/packages/api/src/generated/openapi.json b/packages/api/src/generated/openapi.json index bb0356939d..c5e3af9156 100644 --- a/packages/api/src/generated/openapi.json +++ b/packages/api/src/generated/openapi.json @@ -12012,119 +12012,119 @@ "operationId": "v2-add-warehouse-replication", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "requestBody": { - "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseReplicationRequest" } } - } + }, + "required": true }, "responses": { "202": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseReplicationResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "Invalid or ineligible source selection", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Invalid or ineligible source selection" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Warehouse pipeline, publication or selected table not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse pipeline, publication or selected table not found" }, "409": { - "description": "Warehouse lifecycle, initial sync or retained data conflict", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" } }, "security": [ @@ -12134,7 +12134,7 @@ ], "summary": "Add source tables to Warehouse replication", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:write", @@ -12150,7 +12150,7 @@ } ], "x-endpoint-owners": ["pipelines"], - "x-fga-permissions": [["project_admin_write", "database_write"]], + "x-fga-permissions": [["database_write", "project_admin_write"]], "x-oauth-scope": "database:write", "x-operation": { "group": "warehouse.replication", @@ -12165,119 +12165,119 @@ "operationId": "v2-remove-warehouse-replication", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "requestBody": { - "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseReplicationRequest" } } - } + }, + "required": true }, "responses": { "202": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseReplicationResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "Invalid or ineligible source selection", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Invalid or ineligible source selection" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Warehouse pipeline, publication or selected table not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse pipeline, publication or selected table not found" }, "409": { - "description": "Warehouse lifecycle, initial sync or retained data conflict", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" } }, "security": [ @@ -12287,7 +12287,7 @@ ], "summary": "Remove source tables from Warehouse replication", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:write", @@ -12303,7 +12303,7 @@ } ], "x-endpoint-owners": ["pipelines"], - "x-fga-permissions": [["project_admin_write", "database_write"]], + "x-fga-permissions": [["database_write", "project_admin_write"]], "x-oauth-scope": "database:write", "x-operation": { "group": "warehouse.replication", @@ -12318,119 +12318,119 @@ "operationId": "v2-resync-warehouse-replication", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "requestBody": { - "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseResyncRequest" } } - } + }, + "required": true }, "responses": { "202": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseResyncResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "Invalid or ineligible source selection", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Invalid or ineligible source selection" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Warehouse pipeline, publication or selected table not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse pipeline, publication or selected table not found" }, "409": { - "description": "Warehouse lifecycle, initial sync or retained data conflict", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse lifecycle, initial sync or retained data conflict" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Backend unavailable or outcome uncertain; inspect table and pipeline state before retrying" } }, "security": [ @@ -12440,7 +12440,7 @@ ], "summary": "Reset and rebuild one Warehouse table", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:write", @@ -12456,7 +12456,7 @@ } ], "x-endpoint-owners": ["pipelines"], - "x-fga-permissions": [["project_admin_write", "database_write"]], + "x-fga-permissions": [["database_write", "project_admin_write"]], "x-oauth-scope": "database:write", "x-operation": { "group": "warehouse.replication", @@ -12467,154 +12467,154 @@ }, "/v2/projects/{ref}/warehouse/capacity": { "get": { - "description": "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use since or both from and to; the default is the last 30 minutes. Each measurement includes its definition, unit, aggregation, requested and effective ranges, rate_window_seconds, source-sample freshness, availability, coverage, and full series with dimension labels such as reason, kind, and result. Executor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or null; they do not establish healthy or idle capacity. Point timestamps are evaluation times; last_sample_at is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range. Each request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.\n\nThis endpoint is currently in its **Alpha** stage.", + "description": "Returns capacity, admission, assignment-wait, and activation measurements over a bounded time range, using the project’s stored Warehouse placement. Use `--since` or specify both `--from` and `--to`; the default is the last 30 minutes.\n\nEach measurement includes its definition, unit, aggregation, requested and effective ranges, `rate_window_seconds`, source-sample freshness, availability, coverage, and full series with dimension labels such as `reason`, `kind`, and `result`.\n\nExecutor invocations in flight are distinct from worker admission grants. Occupied admission includes active plus pending grants. The configured admission limit does not imply an open gate or spare capacity. Missing, stale, and insufficient observations remain unavailable or `null`; they do not establish healthy or idle capacity.\n\nPoint timestamps are evaluation times; `last_sample_at` is the original source-sample time. Rates and latency quantiles describe the effective rate window at each point, not the entire requested range.\n\nEach request returns up to eight measurements, and a failure of one measurement does not discard the other results. No raw queries or backend selectors are accepted.\n\nThis endpoint is currently in its **Alpha** stage.", "operationId": "v2-get-warehouse-capacity", "parameters": [ { - "name": "ref", - "required": true, - "in": "path", - "description": "Project ref", + "description": "Up to eight distinct measurements. Defaults to `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_p95`, `activation_duration_p95`. Supply a comma-separated list. Allowed measurements: `query_in_flight`, `worker_admission_limit`, `worker_admission_active`, `worker_admission_pending`, `worker_admission_occupied`, `admission_rejection_rate`, `assignment_wait_mean`, `assignment_wait_p95`, `activation_rate`, `activation_duration_mean`, `activation_duration_p95`.", + "in": "query", + "name": "attributes", + "required": false, "schema": { - "minLength": 20, - "maxLength": 20, - "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } }, { - "name": "since", - "required": false, + "description": "Range start as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, within the last 30 days. Requires `--to`; cannot be combined with `--since`.", "in": "query", - "description": "Look back from server time, for example 30m, 2h, or 1d. Defaults to 30m when from/to are omitted. Maximum 30d. Cannot be combined with from/to.", + "name": "from", + "required": false, "schema": { - "pattern": "^[1-9]\\d*(s|m|h|d)$", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", "type": "string" } }, { - "name": "from", - "required": false, + "description": "Defaults to `1m`. The effective step increases to stay within 1,441 points per series. Rate and latency windows are at least `5m`.", "in": "query", - "description": "Range start as an ISO timestamp, within the last 30 days. Requires to; cannot be combined with since.", + "name": "interval", + "required": false, "schema": { - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "enum": ["10m", "1d", "1h", "1m", "30m", "5m"], "type": "string" } }, { - "name": "to", - "required": false, - "in": "query", - "description": "Range end as an ISO timestamp, no later than server time. Requires from; cannot be combined with since. The service tolerates up to 60 seconds of request delay or clock skew.", + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, "schema": { - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", "type": "string" } }, { - "name": "attributes", - "required": false, + "description": "Look back from server time, for example `30m`, `2h`, or `1d`. Defaults to `30m` when `--from`/`--to` are omitted. Maximum `30d`. Cannot be combined with `--from`/`--to`.", "in": "query", - "description": "Up to eight distinct measurements. Defaults to query_in_flight, worker_admission_limit, worker_admission_active, worker_admission_pending, worker_admission_occupied, admission_rejection_rate, assignment_wait_p95, activation_duration_p95. Supply a comma-separated list. Allowed measurements: query_in_flight, worker_admission_limit, worker_admission_active, worker_admission_pending, worker_admission_occupied, admission_rejection_rate, assignment_wait_mean, assignment_wait_p95, activation_rate, activation_duration_mean, activation_duration_p95.", + "name": "since", + "required": false, "schema": { + "pattern": "^[1-9]\\d*(s|m|h|d)$", "type": "string" } }, { - "name": "interval", - "required": false, + "description": "Range end as an ISO 8601 timestamp with seconds and a time zone, for example `2026-11-18T09:30:00Z`, no later than server time. Requires `--from`; cannot be combined with `--since`. The service tolerates up to 60 seconds of request delay or clock skew.", "in": "query", - "description": "Defaults to 1m. The effective step increases to stay within 1441 points per series. Rate and latency windows are at least 5m.", + "name": "to", + "required": false, "schema": { - "type": "string", - "enum": ["1m", "5m", "10m", "30m", "1h", "1d"] + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseCapacityResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Project not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Project not found" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable." } }, "security": [ @@ -12624,7 +12624,7 @@ ], "summary": "Inspect Warehouse capacity diagnostics", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:read", @@ -12655,150 +12655,150 @@ "operationId": "v2-get-warehouse-query-stats", "parameters": [ { - "name": "ref", - "required": true, - "in": "path", - "description": "Project ref", + "description": "Up to eight distinct workload measurements. Defaults to invocation rate, latency p50/p95/p99, error rate, and timeout rate. Supply a comma-separated list. Allowed measurements: query_rate, query_error_rate, query_timeout_rate, query_canceled_rate, query_duration_mean, query_duration_p50, query_duration_p95, query_duration_p99, duckdb_duration_mean, rpc_rate, rpc_duration_mean, rpc_duration_p95.", + "in": "query", + "name": "attributes", + "required": false, "schema": { - "minLength": 20, - "maxLength": 20, - "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } }, { - "name": "since", - "required": false, + "description": "Range start as an ISO timestamp, within the last 30 days. Requires to; cannot be combined with since.", "in": "query", - "description": "Look back from server time, for example 30m, 2h, or 1d. Defaults to 30m when from/to are omitted. Maximum 30d. Cannot be combined with from/to.", + "name": "from", + "required": false, "schema": { - "pattern": "^[1-9]\\d*(s|m|h|d)$", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", "type": "string" } }, { - "name": "from", - "required": false, + "description": "Defaults to 1m. The effective step increases to stay within 1441 points per series. Rate and latency windows are at least 5m.", "in": "query", - "description": "Range start as an ISO timestamp, within the last 30 days. Requires to; cannot be combined with since.", + "name": "interval", + "required": false, "schema": { - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "enum": ["10m", "1d", "1h", "1m", "30m", "5m"], "type": "string" } }, { - "name": "to", - "required": false, - "in": "query", - "description": "Range end as an ISO timestamp, no later than server time. Requires from; cannot be combined with since. The service tolerates up to 60 seconds of request delay or clock skew.", + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, "schema": { - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", "type": "string" } }, { - "name": "attributes", - "required": false, + "description": "Look back from server time, for example 30m, 2h, or 1d. Defaults to 30m when from/to are omitted. Maximum 30d. Cannot be combined with from/to.", "in": "query", - "description": "Up to eight distinct measurements. Defaults to query_rate, query_duration_p50, query_duration_p95, query_duration_p99, query_error_rate, query_timeout_rate. Supply a comma-separated list. Allowed measurements: query_rate, query_error_rate, query_timeout_rate, query_canceled_rate, query_duration_mean, query_duration_p50, query_duration_p95, query_duration_p99, duckdb_duration_mean, rpc_rate, rpc_duration_mean, rpc_duration_p95.", + "name": "since", + "required": false, "schema": { + "pattern": "^[1-9]\\d*(s|m|h|d)$", "type": "string" } }, { - "name": "interval", - "required": false, + "description": "Range end as an ISO timestamp, no later than server time. Requires from; cannot be combined with since. The service tolerates up to 60 seconds of request delay or clock skew.", "in": "query", - "description": "Defaults to 1m. The effective step increases to stay within 1441 points per series. Rate and latency windows are at least 5m.", + "name": "to", + "required": false, "schema": { - "type": "string", - "enum": ["1m", "5m", "10m", "30m", "1h", "1d"] + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$", + "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseQueryStatsResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "validation_failed: Invalid measurement selection, range, interval, or query parameter" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Project not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Project not found" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "warehouse_metrics_unavailable: Metrics query capacity is temporarily unavailable; retry after a short delay. warehouse_setup_unavailable: Warehouse feature or project metadata unavailable." } }, "security": [ @@ -12808,7 +12808,7 @@ ], "summary": "Inspect Warehouse workload query statistics", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:read", @@ -13542,73 +13542,73 @@ }, "/v2/projects/{ref}/warehouse/status": { "get": { - "description": "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions.\n\nThis endpoint is currently in its **Alpha** stage.", + "description": "Returns provisioning, configured compute, replication, cleanup lifecycle and supported capabilities, including when individual dependencies are unavailable. Enabled Warehouse state is independent of the selected table count. Readiness is inferred from configuration and replication; query connectivity is not checked. Does not inspect the FDW. Observation timestamps are retrieval times, separate from table sync lag, pipeline apply lag and feedback age. Read access remains available without a replication entitlement; mutation endpoints enforce their own entitlements and permissions. Runtime diagnostics classify current failures. Table errors and progress are explicitly current, last-known or unavailable; they do not establish completion of a particular restart or resync. Capabilities describe Management API operations: workload_metrics includes query-stats and capacity; query_explain does not describe SQL EXPLAIN through the Warehouse connection.\n\nThis endpoint is currently in its **Alpha** stage.", "operationId": "v2-get-warehouse-status", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseContextResponse_Output" } } - } + }, + "description": "" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Warehouse feature or project metadata unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse feature or project metadata unavailable" } }, "security": [ @@ -13640,73 +13640,73 @@ }, "/v2/projects/{ref}/warehouse/connection": { "get": { - "description": "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: usql -W 'flightsql://postgres@:443?tls=enabled'.\n\nThis endpoint is currently in its **Alpha** stage.", + "description": "Returns the public Arrow Flight SQL endpoint resolved from the project's Warehouse routing, with TLS required on port 443. Status is configured availability and query connectivity is not checked, so DNS readiness does not prove a query will succeed. Login uses a role in the source project database with that role's existing password (postgres uses the project database password), including when the catalog and storage are in another project. The role needs supabase_warehouse_reader membership, which is separate from Management API authorization. No passwords, tokens, catalog credentials or private endpoints are returned, and endpoint, host and port are null unless status is available or pending. Example client: `usql -W 'flightsql://postgres@:443?tls=enabled'`.\n\nThis endpoint is currently in its **Alpha** stage.", "operationId": "v2-get-warehouse-connection", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseConnectionResponse_Output" } } - } + }, + "description": "" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Warehouse feature or project metadata unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse feature or project metadata unavailable" } }, "security": [ @@ -13742,79 +13742,79 @@ "operationId": "v2-list-warehouse-tables", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseTablesResponse_Output" } } - } + }, + "description": "" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Warehouse DuckLake destination not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse DuckLake destination not found" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Warehouse feature, project metadata or table selection unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse feature, project metadata or table selection unavailable" } }, "security": [ @@ -13850,91 +13850,91 @@ "operationId": "v2-get-warehouse-table", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } }, { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", "name": "table_id", "required": true, - "in": "path", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", "schema": { + "example": "16385", "maxLength": 10, "pattern": "^[1-9]\\d*$", - "example": "16385", "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseTableResponse_Output" } } - } + }, + "description": "" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Table not replicated to Warehouse, or Warehouse DuckLake destination not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Table not replicated to Warehouse, or Warehouse DuckLake destination not found" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Warehouse feature, project metadata or table selection unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse feature, project metadata or table selection unavailable" } }, "security": [ @@ -13970,91 +13970,91 @@ "operationId": "v2-get-warehouse-table-layout", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } }, { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", "name": "table_id", "required": true, - "in": "path", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", "schema": { + "example": "16385", "maxLength": 10, "pattern": "^[1-9]\\d*$", - "example": "16385", "type": "string" } } ], "responses": { "200": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseTableLayoutResponse_Output" } } - } + }, + "description": "" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Table not replicated to Warehouse", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Table not replicated to Warehouse" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Warehouse feature, project metadata or table layout unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse feature, project metadata or table layout unavailable" } }, "security": [ @@ -14088,131 +14088,131 @@ "operationId": "v2-update-warehouse-table-layout", "parameters": [ { + "description": "Project ref", + "in": "path", "name": "ref", "required": true, - "in": "path", - "description": "Project ref", "schema": { - "minLength": 20, + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "example": "abcdefghijklmnopqrst", "type": "string" } }, { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "in": "path", "name": "table_id", "required": true, - "in": "path", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", "schema": { + "example": "16385", "maxLength": 10, "pattern": "^[1-9]\\d*$", - "example": "16385", "type": "string" } } ], "requestBody": { - "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseTableLayoutUpdateRequest" } } - } + }, + "required": true }, "responses": { "202": { - "description": "", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/V2WarehouseTableLayoutResponse_Output" } } - } + }, + "description": "" }, "400": { - "description": "Invalid layout or source schema", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Invalid layout or source schema" }, "401": { - "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Unauthorized" }, "402": { - "description": "This feature requires the Pro, Team, or Enterprise organization plan.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." }, "403": { - "description": "Forbidden action", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Forbidden action" }, "404": { - "description": "Warehouse pipeline or replicated table not found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse pipeline or replicated table not found" }, "409": { - "description": "Warehouse or pipeline mutation conflict, or reset requested without initial sync", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Warehouse or pipeline mutation conflict, or reset requested without initial sync" }, "429": { - "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Rate limit exceeded" }, "503": { - "description": "Layout update unavailable or outcome uncertain; inspect the saved layout, pipeline, and table state before retrying", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponseBody" } } - } + }, + "description": "Layout update unavailable or outcome uncertain; inspect the saved layout, pipeline, and table state before retrying" } }, "security": [ @@ -14222,7 +14222,7 @@ ], "summary": "Update the layout of a table replicated to Warehouse", "tags": ["Projects Warehouse"], - "x-allowed-plans": ["Pro", "Team", "Enterprise"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], "x-badges": [ { "name": "OAuth scope: database:write", @@ -14238,7 +14238,7 @@ } ], "x-endpoint-owners": ["pipelines"], - "x-fga-permissions": [["project_admin_write", "database_write"]], + "x-fga-permissions": [["database_write", "project_admin_write"]], "x-oauth-scope": "database:write", "x-operation": { "group": "warehouse.tables.layout", @@ -34448,6 +34448,139 @@ "summary": "Retry delivery", "description": "Retry delivering the same event again.\n\nAutomatic retries are not applicable to manual retries - if the delivery fails, there won't be any automatic retries attempted.\n\nThis endpoint is heavy rate-limited to allow for 10 request within 60 seconds." } + }, + "/v2/projects/{ref}/warehouse/replication/restart": { + "post": { + "description": "Starts a stopped managed pipeline or restarts a starting, started or failed pipeline, preserving the selected tables and saved layouts. Restart interrupts replication; in-progress initial copies may restart from scratch. If lost-slot recreation is configured, startup can rebuild destination tables. The response confirms acceptance only. Inspect warehouse status for runtime diagnostics and observed table progress; these observations do not identify completion of this request. Inspect state before retrying an uncertain response.\n\nThis endpoint is currently in its **Alpha** stage.", + "operationId": "v2-restart-warehouse-replication", + "parameters": [ + { + "description": "Project ref", + "in": "path", + "name": "ref", + "required": true, + "schema": { + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + } + } + ], + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2WarehouseRestartResponse_Output" + } + } + }, + "description": "" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Unauthorized" + }, + "402": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "This feature requires the Pro, Team, or Enterprise organization plan." + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Forbidden action" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Managed Warehouse pipeline not found" + }, + "409": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Warehouse lifecycle or runtime state does not permit restart" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Rate limit exceeded" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponseBody" + } + } + }, + "description": "Restart outcome uncertain; inspect runtime and table state before retrying" + } + }, + "security": [ + { + "bearer": [] + } + ], + "summary": "Start or restart Warehouse replication", + "tags": ["Projects Warehouse"], + "x-allowed-plans": ["Enterprise", "Pro", "Team"], + "x-badges": [ + { + "name": "OAuth scope: database:write", + "position": "after" + }, + { + "name": "Only available on Pro, Team, Enterprise", + "position": "before" + }, + { + "name": "Alpha", + "position": "before" + } + ], + "x-endpoint-owners": ["pipelines"], + "x-fga-permissions": [["database_write", "project_admin_write"]], + "x-oauth-scope": "database:write", + "x-operation": { + "group": "warehouse.replication", + "method": "restart" + }, + "x-scalar-stability": "experimental" + } } }, "components": { @@ -44409,213 +44542,213 @@ "required": ["projects", "pagination"] }, "V2WarehouseReplicationRequest": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_replication_change"] - }, "attributes": { - "type": "object", + "additionalProperties": false, "properties": { "schema": { - "type": "string", + "description": "Literal source PostgreSQL schema. Omit table to select its current tables.", "minLength": 1, - "description": "Literal source PostgreSQL schema. Omit table to select its current tables." + "type": "string" }, "table": { "description": "Literal source table name. Omit to select the schema.", - "type": "string", - "minLength": 1 + "minLength": 1, + "type": "string" } }, "required": ["schema"], - "additionalProperties": false + "type": "object" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_change"], + "type": "string" } }, - "required": ["type", "attributes"] + "required": ["attributes", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseReplicationResponse_Output": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_replication_change"] - }, - "id": { - "type": "string" - }, "attributes": { - "type": "object", "properties": { - "pipeline_id": { - "type": "string" - }, "action": { - "type": "string", - "enum": ["add", "remove"] - }, - "changed": { - "type": "boolean" - }, - "application_status": { - "type": "string", - "enum": ["unchanged", "restart_requested", "configured"], - "description": "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion." - }, - "pipeline_status_before": { + "enum": ["add", "remove"], "type": "string" }, "affected_tables": { - "type": "array", "items": { - "type": "object", "properties": { "id": { - "type": "integer", "exclusiveMinimum": true, "maximum": 4294967295, - "minimum": 0 - }, - "schema": { - "type": "string", - "minLength": 1 + "minimum": 0, + "type": "integer" }, "name": { - "type": "string", - "minLength": 1 - } - }, - "required": ["id", "schema", "name"] - } - }, - "unchanged_tables": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "exclusiveMinimum": true, - "maximum": 4294967295, - "minimum": 0 + "minLength": 1, + "type": "string" }, "schema": { - "type": "string", - "minLength": 1 - }, - "name": { - "type": "string", - "minLength": 1 + "minLength": 1, + "type": "string" } }, - "required": ["id", "schema", "name"] - } + "required": ["id", "name", "schema"], + "type": "object" + }, + "type": "array" + }, + "application_status": { + "description": "Immediate orchestration result. Restart acceptance does not establish runtime application or copy completion.", + "enum": ["configured", "restart_requested", "unchanged"], + "type": "string" + }, + "changed": { + "type": "boolean" + }, + "includes_future_tables": { + "enum": [false], + "type": "boolean" + }, + "pipeline_id": { + "type": "string" + }, + "pipeline_status_before": { + "type": "string" + }, + "selected_table_count": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "source_data_preserved": { + "enum": [true], + "type": "boolean" }, "tables": { - "type": "array", + "description": "Resulting configured selection, with best-effort replication observations.", "items": { - "type": "object", "properties": { + "copy_name": { + "type": "string" + }, "id": { - "type": "integer", "exclusiveMinimum": true, "maximum": 4294967295, - "minimum": 0 + "minimum": 0, + "type": "integer" }, - "schema": { - "type": "string", - "minLength": 1 + "lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" }, "name": { - "type": "string", - "minLength": 1 + "minLength": 1, + "type": "string" }, - "copy_name": { + "replication_state": { + "nullable": true, + "type": "string" + }, + "schema": { + "minLength": 1, "type": "string" }, "state": { - "type": "string", - "enum": ["syncing", "live", "error", null], "description": "Last observed table state; null when unavailable. Does not establish completion of this request.", - "nullable": true - }, - "replication_state": { - "type": "string", - "nullable": true - }, - "lag_ms": { - "type": "number", - "minimum": 0, - "nullable": true + "enum": ["error", "live", null, "syncing"], + "nullable": true, + "type": "string" } }, "required": [ + "copy_name", "id", - "schema", + "lag_ms", "name", - "copy_name", - "state", "replication_state", - "lag_ms" - ] + "schema", + "state" + ], + "type": "object" }, - "description": "Resulting configured selection, with best-effort replication observations." - }, - "selected_table_count": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "warehouse_enabled": { - "type": "boolean", - "enum": [true] + "type": "array" }, - "source_data_preserved": { - "type": "boolean", - "enum": [true] + "unchanged_tables": { + "items": { + "properties": { + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + } + }, + "required": ["id", "name", "schema"], + "type": "object" + }, + "type": "array" }, "warehouse_data_retained": { - "type": "boolean", - "enum": [true] + "enum": [true], + "type": "boolean" }, - "includes_future_tables": { - "type": "boolean", - "enum": [false] + "warehouse_enabled": { + "enum": [true], + "type": "boolean" } }, "required": [ - "pipeline_id", "action", - "changed", + "affected_tables", "application_status", + "changed", + "includes_future_tables", + "pipeline_id", "pipeline_status_before", - "affected_tables", - "unchanged_tables", - "tables", "selected_table_count", - "warehouse_enabled", "source_data_preserved", + "tables", + "unchanged_tables", "warehouse_data_retained", - "includes_future_tables" - ] + "warehouse_enabled" + ], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_change"], + "type": "string" } }, - "required": ["type", "id", "attributes"] + "required": ["attributes", "id", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "APIErrorObject": { "type": "object", @@ -44783,691 +44916,655 @@ "required": ["error"] }, "V2WarehouseResyncRequest": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_replication_resync"] - }, "attributes": { - "type": "object", + "additionalProperties": false, "properties": { "schema": { - "type": "string", + "description": "Literal source PostgreSQL schema of the table.", "minLength": 1, - "description": "Literal source PostgreSQL schema. Omit table to select its current tables." + "type": "string" }, "table": { - "type": "string", + "description": "Literal name of the single source table to reset and recopy.", "minLength": 1, - "description": "Literal name of the single source table to reset and recopy." + "type": "string" } }, "required": ["schema", "table"], - "additionalProperties": false + "type": "object" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_resync"], + "type": "string" } }, - "required": ["type", "attributes"] + "required": ["attributes", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseResyncResponse_Output": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_replication_resync"] - }, - "id": { - "type": "string" - }, "attributes": { - "type": "object", "properties": { + "application_status": { + "description": "ETL reset replication state. Destination rebuild and recopy may still be pending.", + "enum": ["reset"], + "type": "string" + }, "pipeline_id": { - "type": "string", - "minLength": 1, "description": "Pipeline ID", - "example": "03dg2o5teb2eucxr9ggh3uie6" + "example": "03dg2o5teb2eucxr9ggh3uie6", + "minLength": 1, + "type": "string" + }, + "source_data_preserved": { + "enum": [true], + "type": "boolean" + }, + "source_table": { + "properties": { + "id": { + "exclusiveMinimum": true, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" + }, + "name": { + "minLength": 1, + "type": "string" + }, + "schema": { + "minLength": 1, + "type": "string" + } + }, + "required": ["id", "name", "schema"], + "type": "object" }, "tables": { - "type": "array", + "description": "Rolled back tables", "items": { - "type": "object", "properties": { - "table_id": { - "type": "integer", - "minimum": 0, - "maximum": 4294967295, - "description": "Table id (Postgres OID)", - "example": 16408 - }, "new_state": { + "description": "Table replication state", "oneOf": [ { - "type": "object", "properties": { "name": { - "type": "string", - "enum": ["queued"] + "enum": ["queued"], + "type": "string" } }, - "required": ["name"] + "required": ["name"], + "type": "object" }, { - "type": "object", "properties": { "name": { - "type": "string", - "enum": ["copying_table"] + "enum": ["copying_table"], + "type": "string" } }, - "required": ["name"] + "required": ["name"], + "type": "object" }, { - "type": "object", "properties": { "name": { - "type": "string", - "enum": ["copied_table"] + "enum": ["copied_table"], + "type": "string" } }, - "required": ["name"] + "required": ["name"], + "type": "object" }, { - "type": "object", "properties": { "name": { - "type": "string", - "enum": ["following_wal"] + "enum": ["following_wal"], + "type": "string" } }, - "required": ["name"] + "required": ["name"], + "type": "object" }, { - "type": "object", "properties": { "name": { - "type": "string", - "enum": ["error"] + "enum": ["error"], + "type": "string" }, "reason": { "type": "string" }, - "solution": { - "type": "string", - "nullable": true - }, "retry_policy": { "oneOf": [ { - "type": "object", "properties": { "policy": { - "type": "string", - "enum": ["no_retry"] + "enum": ["no_retry"], + "type": "string" } }, - "required": ["policy"] + "required": ["policy"], + "type": "object" }, { - "type": "object", "properties": { "policy": { - "type": "string", - "enum": ["manual_retry"] + "enum": ["manual_retry"], + "type": "string" } }, - "required": ["policy"] + "required": ["policy"], + "type": "object" }, { - "type": "object", "properties": { - "policy": { - "type": "string", - "enum": ["timed_retry"] - }, "next_retry": { - "type": "string", "description": "Next retry time (RFC 3339 timestamp)", - "example": "2025-01-02T03:04:05Z" + "example": "2025-01-02T03:04:05Z", + "type": "string" + }, + "policy": { + "enum": ["timed_retry"], + "type": "string" } }, - "required": ["policy", "next_retry"] + "required": ["next_retry", "policy"], + "type": "object" } ] + }, + "solution": { + "nullable": true, + "type": "string" } }, - "required": ["name", "reason", "retry_policy"] + "required": ["name", "reason", "retry_policy"], + "type": "object" } - ], - "description": "Table replication state" + ] + }, + "table_id": { + "description": "Table id (Postgres OID)", + "example": 16408, + "maximum": 4294967295, + "minimum": 0, + "type": "integer" } }, - "required": ["table_id", "new_state"] - }, - "description": "Rolled back tables" - }, - "source_table": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "exclusiveMinimum": true, - "maximum": 4294967295, - "minimum": 0 - }, - "schema": { - "type": "string", - "minLength": 1 - }, - "name": { - "type": "string", - "minLength": 1 - } + "required": ["new_state", "table_id"], + "type": "object" }, - "required": ["id", "schema", "name"] - }, - "source_data_preserved": { - "type": "boolean", - "enum": [true] - }, - "application_status": { - "type": "string", - "description": "ETL reset replication state. Destination rebuild and recopy may still be pending.", - "enum": ["reset"] + "type": "array" } }, "required": [ + "application_status", "pipeline_id", - "tables", - "source_table", "source_data_preserved", - "application_status" - ] + "source_table", + "tables" + ], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_resync"], + "type": "string" } }, - "required": ["type", "id", "attributes"] + "required": ["attributes", "id", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseCapacityResponse_Output": { - "type": "object", "properties": { "data": { - "type": "array", "items": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_metric"] - }, - "id": { - "type": "string", - "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", - "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, "attributes": { - "type": "object", "properties": { - "project_ref": { + "aggregation": { + "enum": ["mean", "occupied", "p50", "p95", "p99", "rate", "sum"], + "type": "string" + }, + "availability": { + "enum": [ + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable" + ], + "type": "string" + }, + "definition": { "type": "string" }, + "effective": { + "properties": { + "end": { + "type": "number" + }, + "rate_window_seconds": { + "type": "number" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "rate_window_seconds", "start", "step"], + "type": "object" + }, + "last_sample_at": { + "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + "nullable": true, + "type": "number" + }, "metric": { - "type": "string", "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", "assignment_wait_mean", "assignment_wait_p95", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, - "unit": { - "type": "string", - "enum": ["per_second", "seconds", "queries", "grants"] - }, - "aggregation": { - "type": "string", - "enum": ["rate", "sum", "mean", "p50", "p95", "p99", "occupied"] + "worker_admission_pending" + ], + "type": "string" }, - "definition": { + "project_ref": { "type": "string" }, "requested": { - "type": "object", "properties": { + "end": { + "type": "number" + }, "metric": { - "type": "string", "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", "assignment_wait_mean", "assignment_wait_p95", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, - "start": { - "type": "number" - }, - "end": { - "type": "number" + "worker_admission_pending" + ], + "type": "string" }, - "step": { - "type": "number" - } - }, - "required": ["metric", "start", "end"] - }, - "effective": { - "type": "object", - "properties": { "start": { "type": "number" }, - "end": { - "type": "number" - }, "step": { "type": "number" - }, - "rate_window_seconds": { - "type": "number" } }, - "required": ["start", "end", "step", "rate_window_seconds"] + "required": ["end", "metric", "start"], + "type": "object" }, "scrape_interval_seconds": { "type": "number" }, - "availability": { - "type": "string", - "enum": [ - "ok", - "partial", - "stale", - "no_data", - "insufficient_data", - "not_provisioned", - "disabled", - "unavailable" - ] - }, - "last_sample_at": { - "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", - "type": "number", - "nullable": true - }, "series": { - "type": "array", "items": { - "type": "object", "properties": { + "coverage": { + "description": "Grid point coverage, not proof that every worker was scraped.", + "properties": { + "expected_points": { + "type": "number" + }, + "returned_points": { + "type": "number" + } + }, + "required": ["expected_points", "returned_points"], + "type": "object" + }, "labels": { - "type": "object", "additionalProperties": { "type": "string" - } + }, + "type": "object" }, "points": { - "type": "array", "items": { - "type": "object", "properties": { "timestamp": { "type": "number" }, "value": { - "type": "number", - "nullable": true + "nullable": true, + "type": "number" } }, - "required": ["timestamp", "value"] - } - }, - "coverage": { - "type": "object", - "properties": { - "returned_points": { - "type": "number" - }, - "expected_points": { - "type": "number" - } + "required": ["timestamp", "value"], + "type": "object" }, - "required": ["returned_points", "expected_points"], - "description": "Grid point coverage, not proof that every worker was scraped." + "type": "array" } }, - "required": ["labels", "points", "coverage"] - } + "required": ["coverage", "labels", "points"], + "type": "object" + }, + "type": "array" + }, + "unit": { + "enum": ["grants", "per_second", "queries", "seconds"], + "type": "string" } }, "required": [ - "project_ref", - "metric", - "unit", "aggregation", + "availability", "definition", - "requested", "effective", - "scrape_interval_seconds", - "availability", "last_sample_at", - "series" - ] + "metric", + "project_ref", + "requested", + "scrape_interval_seconds", + "series", + "unit" + ], + "type": "object" + }, + "id": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "query_in_flight", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_metric"], + "type": "string" } }, - "required": ["type", "id", "attributes"] - } + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseQueryStatsResponse_Output": { - "type": "object", "properties": { "data": { - "type": "array", "items": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_metric"] - }, - "id": { - "type": "string", - "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", - "query_canceled_rate", - "query_duration_mean", - "query_duration_p50", - "query_duration_p95", - "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", - "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", - "worker_admission_active", - "worker_admission_pending", - "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, "attributes": { - "type": "object", "properties": { - "project_ref": { + "aggregation": { + "enum": ["mean", "occupied", "p50", "p95", "p99", "rate", "sum"], + "type": "string" + }, + "availability": { + "enum": [ + "disabled", + "insufficient_data", + "no_data", + "not_provisioned", + "ok", + "partial", + "stale", + "unavailable" + ], + "type": "string" + }, + "definition": { "type": "string" }, + "effective": { + "properties": { + "end": { + "type": "number" + }, + "rate_window_seconds": { + "type": "number" + }, + "start": { + "type": "number" + }, + "step": { + "type": "number" + } + }, + "required": ["end", "rate_window_seconds", "start", "step"], + "type": "object" + }, + "last_sample_at": { + "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", + "nullable": true, + "type": "number" + }, "metric": { - "type": "string", "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", "query_canceled_rate", "query_duration_mean", "query_duration_p50", "query_duration_p95", "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", + "query_error_rate", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, - "unit": { - "type": "string", - "enum": ["per_second", "seconds", "queries", "grants"] - }, - "aggregation": { - "type": "string", - "enum": ["rate", "sum", "mean", "p50", "p95", "p99", "occupied"] + "worker_admission_pending" + ], + "type": "string" }, - "definition": { + "project_ref": { "type": "string" }, "requested": { - "type": "object", "properties": { + "end": { + "type": "number" + }, "metric": { - "type": "string", "enum": [ - "query_rate", - "query_error_rate", - "query_timeout_rate", + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", "query_canceled_rate", "query_duration_mean", "query_duration_p50", "query_duration_p95", "query_duration_p99", - "duckdb_duration_mean", - "assignment_wait_mean", - "assignment_wait_p95", + "query_error_rate", "query_in_flight", - "admission_rejection_rate", - "worker_admission_limit", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", "worker_admission_active", - "worker_admission_pending", + "worker_admission_limit", "worker_admission_occupied", - "activation_rate", - "activation_duration_mean", - "activation_duration_p95", - "rpc_rate", - "rpc_duration_mean", - "rpc_duration_p95" - ] - }, - "start": { - "type": "number" - }, - "end": { - "type": "number" + "worker_admission_pending" + ], + "type": "string" }, - "step": { - "type": "number" - } - }, - "required": ["metric", "start", "end"] - }, - "effective": { - "type": "object", - "properties": { "start": { "type": "number" }, - "end": { - "type": "number" - }, "step": { "type": "number" - }, - "rate_window_seconds": { - "type": "number" } }, - "required": ["start", "end", "step", "rate_window_seconds"] + "required": ["end", "metric", "start"], + "type": "object" }, "scrape_interval_seconds": { "type": "number" }, - "availability": { - "type": "string", - "enum": [ - "ok", - "partial", - "stale", - "no_data", - "insufficient_data", - "not_provisioned", - "disabled", - "unavailable" - ] - }, - "last_sample_at": { - "description": "Latest observed source sample timestamp in Unix seconds; not the query evaluation timestamp.", - "type": "number", - "nullable": true - }, "series": { - "type": "array", "items": { - "type": "object", "properties": { + "coverage": { + "description": "Grid point coverage, not proof that every worker was scraped.", + "properties": { + "expected_points": { + "type": "number" + }, + "returned_points": { + "type": "number" + } + }, + "required": ["expected_points", "returned_points"], + "type": "object" + }, "labels": { - "type": "object", "additionalProperties": { "type": "string" - } + }, + "type": "object" }, "points": { - "type": "array", "items": { - "type": "object", "properties": { "timestamp": { "type": "number" }, "value": { - "type": "number", - "nullable": true + "nullable": true, + "type": "number" } }, - "required": ["timestamp", "value"] - } - }, - "coverage": { - "type": "object", - "properties": { - "returned_points": { - "type": "number" - }, - "expected_points": { - "type": "number" - } + "required": ["timestamp", "value"], + "type": "object" }, - "required": ["returned_points", "expected_points"], - "description": "Grid point coverage, not proof that every worker was scraped." + "type": "array" } }, - "required": ["labels", "points", "coverage"] - } + "required": ["coverage", "labels", "points"], + "type": "object" + }, + "type": "array" + }, + "unit": { + "enum": ["grants", "per_second", "queries", "seconds"], + "type": "string" } }, "required": [ - "project_ref", - "metric", - "unit", "aggregation", + "availability", "definition", - "requested", "effective", - "scrape_interval_seconds", - "availability", "last_sample_at", - "series" - ] + "metric", + "project_ref", + "requested", + "scrape_interval_seconds", + "series", + "unit" + ], + "type": "object" + }, + "id": { + "enum": [ + "activation_duration_mean", + "activation_duration_p95", + "activation_rate", + "admission_rejection_rate", + "assignment_wait_mean", + "assignment_wait_p95", + "duckdb_duration_mean", + "query_canceled_rate", + "query_duration_mean", + "query_duration_p50", + "query_duration_p95", + "query_duration_p99", + "query_error_rate", + "query_in_flight", + "query_rate", + "query_timeout_rate", + "rpc_duration_mean", + "rpc_duration_p95", + "rpc_rate", + "worker_admission_active", + "worker_admission_limit", + "worker_admission_occupied", + "worker_admission_pending" + ], + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_metric"], + "type": "string" } }, - "required": ["type", "id", "attributes"] - } + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseTeardownResponse_Output": { "type": "object", @@ -46130,1509 +46227,1665 @@ "required": ["data"] }, "V2WarehouseContextResponse_Output": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_context"] - }, - "id": { - "type": "string", - "minLength": 20, - "maxLength": 20, - "pattern": "^[a-z]+$", - "description": "Project ref", - "example": "abcdefghijklmnopqrst" - }, "attributes": { - "type": "object", "properties": { - "project_ref": { - "type": "string", - "minLength": 20, - "maxLength": 20, - "pattern": "^[a-z]+$", - "description": "Project ref", - "example": "abcdefghijklmnopqrst" - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" - }, - "enabled": { - "description": "Whether Warehouse is enabled, independently of selected table count. Null means provisioning could not be determined.", - "type": "boolean", - "nullable": true - }, - "configured_readiness": { - "type": "string", - "enum": ["ready", "not_ready", "unavailable"], - "description": "Readiness inferred from configuration and replication observations; no query is executed." - }, - "query_connectivity": { - "type": "string", - "enum": ["not_checked"] - }, - "status": { - "type": "string", - "enum": [ - "not_provisioned", - "disabled", - "disabling", - "starting", - "ready", - "stopped", - "stopping", - "degraded", - "unavailable" - ], - "description": "Warehouse setup and replication status. Ready means the Warehouse connection is configured and tables are replicating ongoing changes. It does not guarantee that a query will succeed." - }, - "lifecycle": { - "type": "object", + "capabilities": { + "description": "Complete operations supported by this API, not caller authorization. Each operation still requires its feature, entitlement and project permission checks.", "properties": { - "status": { - "type": "string", - "enum": ["disabling", "disabled", "deletion_failed"] + "context": { + "type": "boolean" }, - "updated_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$" + "query_explain": { + "type": "boolean", + "description": "Whether the Management API supports a query-explain operation. SQL EXPLAIN through the Warehouse connection is independent of this flag." }, - "delete_data": { + "replication_add": { + "type": "boolean" + }, + "replication_remove": { + "type": "boolean" + }, + "table_layout_read": { + "type": "boolean" + }, + "table_layout_update": { + "type": "boolean" + }, + "table_resync": { + "type": "boolean" + }, + "workload_metrics": { + "type": "boolean", + "description": "Query statistics and capacity inspection are supported by the Management API. Metric availability is reported separately." + }, + "replication_restart": { "type": "boolean" } }, - "required": ["status", "updated_at", "delete_data"], - "nullable": true + "required": [ + "context", + "query_explain", + "replication_add", + "replication_remove", + "replication_restart", + "table_layout_read", + "table_layout_update", + "table_resync", + "workload_metrics" + ], + "type": "object" }, "compute": { - "type": "object", + "description": "Configured Warehouse compute and region, which may differ from the source database region. Live availability and capacity are not reported.", "properties": { - "status": { - "type": "string", - "enum": ["available", "unavailable", "not_provisioned"] + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" }, "region": { - "type": "string", - "nullable": true + "nullable": true, + "type": "string" }, "routing_status": { - "type": "string", - "enum": ["pending", "ready", "error", "removed", null], - "nullable": true + "enum": ["error", null, "pending", "ready", "removed"], + "nullable": true, + "type": "string" }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", - "nullable": true + "status": { + "enum": ["available", "not_provisioned", "unavailable"], + "type": "string" }, "unavailable_reason": { - "type": "string", "enum": [ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", - null + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" ], - "nullable": true + "nullable": true, + "type": "string" } }, "required": [ - "status", + "observed_at", "region", "routing_status", - "observed_at", + "status", "unavailable_reason" ], - "description": "Configured Warehouse compute and region, which may differ from the source database region. Live availability and capacity are not reported." + "type": "object" + }, + "configured_readiness": { + "description": "Readiness inferred from configuration and replication observations; no query is executed.", + "enum": ["not_ready", "ready", "unavailable"], + "type": "string" + }, + "enabled": { + "description": "Whether Warehouse is enabled, independently of selected table count. Null means provisioning could not be determined.", + "nullable": true, + "type": "boolean" + }, + "lifecycle": { + "nullable": true, + "properties": { + "delete_data": { + "type": "boolean" + }, + "status": { + "enum": ["deletion_failed", "disabled", "disabling"], + "type": "string" + }, + "updated_at": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + } + }, + "required": ["delete_data", "status", "updated_at"], + "type": "object" + }, + "observed_at": { + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" }, "pipeline": { - "type": "object", + "nullable": true, "properties": { "id": { - "type": "string", - "minLength": 1 + "minLength": 1, + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" }, "status": { - "type": "string", "enum": [ - "stopped", - "starting", + "failed", "started", + "starting", + "stopped", "stopping", - "unknown", - "failed", - "unavailable" - ] - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", - "nullable": true + "unavailable", + "unknown" + ], + "type": "string" }, "unavailable_reason": { - "type": "string", "enum": [ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", - null + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" ], - "nullable": true + "nullable": true, + "type": "string" + }, + "diagnostic": { + "description": "Safe classification of the current runtime failure. Does not include worker logs or establish its underlying cause.", + "nullable": true, + "properties": { + "code": { + "enum": [ + "configuration_error", + "crash_loop", + "image_unavailable", + "out_of_memory", + "process_exited", + "runtime_failed", + "startup_failed" + ], + "type": "string" + }, + "exit_code": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "nullable": true, + "type": "integer" + }, + "message": { + "type": "string" + } + }, + "required": ["code", "exit_code", "message"], + "type": "object" } }, - "required": ["id", "status", "observed_at", "unavailable_reason"], - "nullable": true + "required": ["diagnostic", "id", "observed_at", "status", "unavailable_reason"], + "type": "object" + }, + "project_ref": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "query_connectivity": { + "enum": ["not_checked"], + "type": "string" }, "replication": { - "type": "object", "properties": { - "status": { - "type": "string", - "enum": [ - "available", - "unavailable", - "not_provisioned", - "not_started", - "stopped" - ] - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", - "nullable": true - }, "apply_lag": { - "type": "object", + "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", + "nullable": true, "properties": { "active": { "type": "boolean" }, - "wal_status": { - "type": "string", - "enum": ["reserved", "extended", "unreserved", "lost", "unknown", null], - "nullable": true + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" }, - "write_lag_ms": { - "type": "number", + "flush_lag_bytes": { + "maximum": 9007199254740991, "minimum": 0, - "nullable": true + "nullable": true, + "type": "integer" }, "flush_lag_ms": { - "type": "number", "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" }, - "flush_lag_bytes": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "nullable": true + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" }, - "feedback_age_ms": { - "type": "number", + "write_lag_ms": { "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" } }, "required": [ "active", - "wal_status", - "write_lag_ms", - "flush_lag_ms", + "feedback_age_ms", "flush_lag_bytes", - "feedback_age_ms" + "flush_lag_ms", + "wal_status", + "write_lag_ms" ], - "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", - "nullable": true + "type": "object" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "status": { + "enum": [ + "available", + "not_provisioned", + "not_started", + "stopped", + "unavailable" + ], + "type": "string" }, "unavailable_reason": { - "type": "string", "enum": [ "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", "cleanup_failed", - null + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" ], - "nullable": true + "nullable": true, + "type": "string" } }, - "required": ["status", "observed_at", "apply_lag", "unavailable_reason"] + "required": ["apply_lag", "observed_at", "status", "unavailable_reason"], + "type": "object" + }, + "status": { + "description": "Warehouse setup and replication status. Ready means the Warehouse connection is configured and tables are replicating ongoing changes. It does not guarantee that a query will succeed.", + "enum": [ + "degraded", + "disabled", + "disabling", + "not_provisioned", + "ready", + "starting", + "stopped", + "stopping", + "unavailable" + ], + "type": "string" }, "tables": { - "type": "object", "properties": { - "status": { - "type": "string", - "enum": ["available", "unavailable", "not_provisioned"] - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", - "nullable": true - }, - "unavailable_reason": { - "type": "string", - "enum": [ - "assignment_unavailable", - "observation_unavailable", - "identity_mismatch", - "cleanup_in_progress", - "cleanup_failed", - null - ], - "nullable": true - }, "items": { - "type": "array", "items": { - "type": "object", "properties": { "id": { - "type": "integer", "exclusiveMinimum": true, "maximum": 9007199254740991, - "minimum": 0 - }, - "schema": { - "type": "string" + "minimum": 0, + "type": "integer" }, "name": { "type": "string" }, "replication_state": { - "type": "string", "enum": [ - "queued", - "copying_table", "copied_table", - "following_wal", + "copying_table", "error", - null + "following_wal", + null, + "queued" ], - "nullable": true + "nullable": true, + "type": "string" + }, + "schema": { + "type": "string" }, "sync_lag": { - "type": "object", + "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", + "nullable": true, "properties": { "active": { "type": "boolean" }, + "feedback_age_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, + "flush_lag_bytes": { + "maximum": 9007199254740991, + "minimum": 0, + "nullable": true, + "type": "integer" + }, + "flush_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" + }, "wal_status": { - "type": "string", "enum": [ - "reserved", "extended", - "unreserved", "lost", + null, + "reserved", "unknown", - null + "unreserved" ], - "nullable": true + "nullable": true, + "type": "string" }, "write_lag_ms": { - "type": "number", - "minimum": 0, - "nullable": true - }, - "flush_lag_ms": { - "type": "number", - "minimum": 0, - "nullable": true - }, - "flush_lag_bytes": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "nullable": true - }, - "feedback_age_ms": { - "type": "number", "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" } }, "required": [ "active", - "wal_status", - "write_lag_ms", - "flush_lag_ms", + "feedback_age_ms", "flush_lag_bytes", - "feedback_age_ms" + "flush_lag_ms", + "wal_status", + "write_lag_ms" ], - "description": "Postgres replication feedback. Null means Postgres reported no value; lag times also become null shortly after a caught-up slot sees no new WAL, while flush_lag_bytes, the WAL not yet confirmed flushed, reads 0. Feedback age measures time since the last response and does not establish how current query results are.", - "nullable": true + "type": "object" + }, + "error": { + "nullable": true, + "properties": { + "reason": { + "type": "string" + }, + "retry_policy": { + "oneOf": [ + { + "properties": { + "policy": { + "enum": ["no_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "policy": { + "enum": ["manual_retry"], + "type": "string" + } + }, + "required": ["policy"], + "type": "object" + }, + { + "properties": { + "next_retry": { + "type": "string" + }, + "policy": { + "enum": ["timed_retry"], + "type": "string" + } + }, + "required": ["next_retry", "policy"], + "type": "object" + } + ] + }, + "solution": { + "nullable": true, + "type": "string" + } + }, + "required": ["reason", "retry_policy", "solution"], + "type": "object" + }, + "state_observation": { + "enum": ["current", "last_known", "unavailable"], + "type": "string" } }, - "required": ["id", "schema", "name", "replication_state", "sync_lag"] - } - } - }, - "required": ["status", "observed_at", "unavailable_reason", "items"] - }, - "capabilities": { - "type": "object", - "properties": { - "context": { - "type": "boolean" - }, - "workload_metrics": { - "type": "boolean" - }, - "query_explain": { - "type": "boolean" - }, - "table_layout_read": { - "type": "boolean" + "required": [ + "error", + "id", + "name", + "replication_state", + "schema", + "state_observation", + "sync_lag" + ], + "type": "object" + }, + "type": "array" }, - "table_layout_update": { - "type": "boolean" + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when data was measured or last synchronized.", + "format": "date-time", + "nullable": true, + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" }, - "replication_add": { - "type": "boolean" + "status": { + "enum": ["available", "not_provisioned", "unavailable"], + "type": "string" }, - "replication_remove": { - "type": "boolean" + "unavailable_reason": { + "enum": [ + "assignment_unavailable", + "cleanup_failed", + "cleanup_in_progress", + "identity_mismatch", + null, + "observation_unavailable" + ], + "nullable": true, + "type": "string" }, - "table_resync": { - "type": "boolean" + "progress": { + "description": "Observed states of the selected tables, not completion or percentage of a specific mutation. Last-known states may predate a restart or resync. Null when the selection is unavailable.", + "nullable": true, + "properties": { + "copied_table": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "copying_table": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "error": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "following_wal": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "observation": { + "enum": ["current", "last_known", "unavailable"], + "type": "string" + }, + "queued": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "selected": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + }, + "unknown": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "copied_table", + "copying_table", + "error", + "following_wal", + "observation", + "queued", + "selected", + "unknown" + ], + "type": "object" } }, "required": [ - "context", - "workload_metrics", - "query_explain", - "table_layout_read", - "table_layout_update", - "replication_add", - "replication_remove", - "table_resync" + "items", + "observed_at", + "progress", + "status", + "unavailable_reason" ], - "description": "Complete operations supported by this API, not caller authorization. Each operation still requires its feature, entitlement and project permission checks." + "type": "object" } }, "required": [ - "project_ref", - "observed_at", - "enabled", + "capabilities", + "compute", "configured_readiness", - "query_connectivity", - "status", + "enabled", "lifecycle", - "compute", + "observed_at", "pipeline", + "project_ref", + "query_connectivity", "replication", - "tables", - "capabilities" - ] - } - }, - "required": ["type", "id", "attributes"] - } - }, - "required": ["data"] - }, - "V2WarehouseConnectionResponse_Output": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_connection"] + "status", + "tables" + ], + "type": "object" }, "id": { - "type": "string", - "minLength": 20, + "description": "Project ref", + "example": "abcdefghijklmnopqrst", "maxLength": 20, + "minLength": 20, "pattern": "^[a-z]+$", - "description": "Project ref", - "example": "abcdefghijklmnopqrst" + "type": "string" }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_context"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" + }, + "V2WarehouseConnectionResponse_Output": { + "properties": { + "data": { + "properties": { "attributes": { - "type": "object", "properties": { - "project_ref": { - "type": "string", - "minLength": 20, - "maxLength": 20, - "pattern": "^[a-z]+$", - "description": "Project ref", - "example": "abcdefghijklmnopqrst" - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved this information. This timestamp does not indicate when connectivity was last verified." - }, - "status": { - "type": "string", - "enum": [ - "available", - "pending", - "not_configured", - "disabling", - "disabled", - "unavailable" - ], - "description": "Configured availability of the Warehouse endpoint, derived from routing and lifecycle state. It is not a connectivity probe: a ready route does not prove a query will succeed." - }, - "unavailable_reason": { - "type": "string", - "enum": [ - "assignment_unavailable", - "routing_failed", - "observation_unavailable", - "cleanup_failed", - null - ], - "description": "Why the endpoint is unavailable. Null unless status is unavailable.", - "nullable": true - }, - "protocol": { - "type": "string", - "enum": ["arrow_flight_sql"] - }, - "endpoint": { - "description": "Arrow Flight SQL URI, grpc+tls://:443. Null unless status is available or pending.", - "type": "string", - "nullable": true - }, - "host": { - "description": "Public hostname of the Flight SQL endpoint. Null unless status is available or pending.", - "type": "string", - "nullable": true - }, - "port": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991, - "description": "Public TLS port of the Flight SQL endpoint. Null unless status is available or pending.", - "nullable": true - }, - "tls_required": { - "type": "boolean", - "enum": [true] - }, - "region": { - "description": "Assigned Warehouse compute region, which may differ from the source database region. Null when the project has no project-specific route.", - "type": "string", - "nullable": true - }, - "routing_status": { - "type": "string", - "enum": ["pending", "ready", "error", "removed", null], - "description": "DNS delivery status of the project route. Null when the project uses the shared legacy route.", - "nullable": true + "access_mode": { + "enum": ["read_only"], + "type": "string" }, "authentication": { - "type": "object", + "description": "How to authenticate. No credentials are returned; the password is never exposed by this API.", "properties": { - "method": { - "type": "string", - "enum": ["database_username_password"] - }, "credential_source": { - "type": "string", - "enum": ["source_project_database"] + "enum": ["source_project_database"], + "type": "string" }, "default_username": { - "type": "string", - "enum": ["postgres"] + "enum": ["postgres"], + "type": "string" + }, + "membership_guidance": { + "type": "string" + }, + "method": { + "enum": ["database_username_password"], + "type": "string" }, "password_guidance": { "type": "string" }, "required_membership": { - "type": "string", - "enum": ["supabase_warehouse_reader"] - }, - "membership_guidance": { + "enum": ["supabase_warehouse_reader"], "type": "string" } }, "required": [ - "method", "credential_source", "default_username", + "membership_guidance", + "method", "password_guidance", - "required_membership", - "membership_guidance" + "required_membership" ], - "description": "How to authenticate. No credentials are returned; the password is never exposed by this API." + "type": "object" }, - "access_mode": { - "type": "string", - "enum": ["read_only"] + "endpoint": { + "description": "Arrow Flight SQL URI, grpc+tls://:443. Null unless status is available or pending.", + "nullable": true, + "type": "string" + }, + "host": { + "description": "Public hostname of the Flight SQL endpoint. Null unless status is available or pending.", + "nullable": true, + "type": "string" + }, + "observed_at": { + "description": "Time the API retrieved this information. This timestamp does not indicate when connectivity was last verified.", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "port": { + "description": "Public TLS port of the Flight SQL endpoint. Null unless status is available or pending.", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "nullable": true, + "type": "integer" + }, + "project_ref": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "protocol": { + "enum": ["arrow_flight_sql"], + "type": "string" }, "query_connectivity": { - "type": "string", - "enum": ["not_checked"] + "enum": ["not_checked"], + "type": "string" + }, + "region": { + "description": "Assigned Warehouse compute region, which may differ from the source database region. Null when the project has no project-specific route.", + "nullable": true, + "type": "string" + }, + "routing_status": { + "description": "DNS delivery status of the project route. Null when the project uses the shared legacy route.", + "enum": ["error", null, "pending", "ready", "removed"], + "nullable": true, + "type": "string" + }, + "status": { + "description": "Configured availability of the Warehouse endpoint, derived from routing and lifecycle state. It is not a connectivity probe: a ready route does not prove a query will succeed.", + "enum": [ + "available", + "disabled", + "disabling", + "not_configured", + "pending", + "unavailable" + ], + "type": "string" + }, + "tls_required": { + "enum": [true], + "type": "boolean" + }, + "unavailable_reason": { + "description": "Why the endpoint is unavailable. Null unless status is unavailable.", + "enum": [ + "assignment_unavailable", + "cleanup_failed", + null, + "observation_unavailable", + "routing_failed" + ], + "nullable": true, + "type": "string" } }, "required": [ - "project_ref", - "observed_at", - "status", - "unavailable_reason", - "protocol", + "access_mode", + "authentication", "endpoint", "host", + "observed_at", "port", - "tls_required", + "project_ref", + "protocol", + "query_connectivity", "region", "routing_status", - "authentication", - "access_mode", - "query_connectivity" - ] + "status", + "tls_required", + "unavailable_reason" + ], + "type": "object" + }, + "id": { + "description": "Project ref", + "example": "abcdefghijklmnopqrst", + "maxLength": 20, + "minLength": 20, + "pattern": "^[a-z]+$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_connection"], + "type": "string" } }, - "required": ["type", "id", "attributes"] + "required": ["attributes", "id", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseTablesResponse_Output": { - "type": "object", "properties": { "data": { - "type": "array", "items": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_table"] - }, - "id": { - "type": "string", - "maxLength": 10, - "pattern": "^[1-9]\\d*$", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - "example": "16385" - }, "attributes": { - "type": "object", "properties": { - "schema": { - "type": "string", - "description": "Source PostgreSQL schema of the table." + "lag_ms": { + "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + "minimum": 0, + "nullable": true, + "type": "number" }, "name": { - "type": "string", - "description": "Source PostgreSQL table name." - }, - "warehouse_name": { - "type": "string", - "description": "Quoted, fully qualified name of the replicated table in the Warehouse." - }, - "status": { - "type": "string", - "enum": ["syncing", "live", "error", "stopped", "unknown"], - "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts." - }, - "replication_state": { - "type": "string", - "enum": [ - "queued", - "copying_table", - "copied_table", - "following_wal", - "error", - null - ], - "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", - "nullable": true + "description": "Source PostgreSQL table name.", + "type": "string" }, "observed_at": { - "type": "string", + "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", "format": "date-time", + "nullable": true, "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", - "nullable": true + "type": "string" }, "replication_feedback": { - "type": "object", + "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", + "nullable": true, "properties": { "active": { "type": "boolean" }, - "wal_status": { - "type": "string", - "enum": ["reserved", "extended", "unreserved", "lost", "unknown", null], - "nullable": true - }, - "write_lag_ms": { - "type": "number", - "minimum": 0, - "nullable": true - }, - "flush_lag_ms": { - "type": "number", + "feedback_age_ms": { "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" }, "flush_lag_bytes": { - "type": "integer", - "minimum": 0, "maximum": 9007199254740991, - "nullable": true + "minimum": 0, + "nullable": true, + "type": "integer" }, - "feedback_age_ms": { - "type": "number", + "flush_lag_ms": { "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" }, "source": { - "type": "string", - "enum": ["table_sync", "pipeline_apply"], - "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does." + "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", + "enum": ["pipeline_apply", "table_sync"], + "type": "string" + }, + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" } }, "required": [ "active", - "wal_status", - "write_lag_ms", - "flush_lag_ms", - "flush_lag_bytes", "feedback_age_ms", - "source" + "flush_lag_bytes", + "flush_lag_ms", + "source", + "wal_status", + "write_lag_ms" ], - "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", - "nullable": true + "type": "object" }, - "lag_ms": { - "type": "number", - "minimum": 0, - "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", - "nullable": true + "replication_state": { + "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + "enum": [ + "copied_table", + "copying_table", + "error", + "following_wal", + null, + "queued" + ], + "nullable": true, + "type": "string" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" + }, + "status": { + "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + "enum": ["error", "live", "stopped", "syncing", "unknown"], + "type": "string" + }, + "warehouse_name": { + "description": "Quoted, fully qualified name of the replicated table in the Warehouse.", + "type": "string" } }, "required": [ - "schema", + "lag_ms", "name", - "warehouse_name", - "status", - "replication_state", "observed_at", "replication_feedback", - "lag_ms" - ] + "replication_state", + "schema", + "status", + "warehouse_name" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table"], + "type": "string" } }, - "required": ["type", "id", "attributes"] - } + "required": ["attributes", "id", "type"], + "type": "object" + }, + "type": "array" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseTableResponse_Output": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_table"] - }, - "id": { - "type": "string", - "maxLength": 10, - "pattern": "^[1-9]\\d*$", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - "example": "16385" - }, "attributes": { - "type": "object", "properties": { - "schema": { - "type": "string", - "description": "Source PostgreSQL schema of the table." + "lag_ms": { + "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", + "minimum": 0, + "nullable": true, + "type": "number" }, "name": { - "type": "string", - "description": "Source PostgreSQL table name." - }, - "warehouse_name": { - "type": "string", - "description": "Quoted, fully qualified name of the replicated table in the Warehouse." - }, - "status": { - "type": "string", - "enum": ["syncing", "live", "error", "stopped", "unknown"], - "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts." - }, - "replication_state": { - "type": "string", - "enum": [ - "queued", - "copying_table", - "copied_table", - "following_wal", - "error", - null - ], - "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", - "nullable": true + "description": "Source PostgreSQL table name.", + "type": "string" }, "observed_at": { - "type": "string", + "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", "format": "date-time", + "nullable": true, "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the API retrieved the replication state of the table. It does not indicate when data was last synchronized.", - "nullable": true + "type": "string" }, "replication_feedback": { - "type": "object", + "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", + "nullable": true, "properties": { "active": { "type": "boolean" }, - "wal_status": { - "type": "string", - "enum": ["reserved", "extended", "unreserved", "lost", "unknown", null], - "nullable": true - }, - "write_lag_ms": { - "type": "number", - "minimum": 0, - "nullable": true - }, - "flush_lag_ms": { - "type": "number", + "feedback_age_ms": { "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" }, "flush_lag_bytes": { - "type": "integer", - "minimum": 0, "maximum": 9007199254740991, - "nullable": true + "minimum": 0, + "nullable": true, + "type": "integer" }, - "feedback_age_ms": { - "type": "number", + "flush_lag_ms": { "minimum": 0, - "nullable": true + "nullable": true, + "type": "number" }, "source": { - "type": "string", - "enum": ["table_sync", "pipeline_apply"], - "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does." + "description": "Replication slot that reported the feedback: the table's own sync slot until it follows changes, or the pipeline apply slot once it does.", + "enum": ["pipeline_apply", "table_sync"], + "type": "string" + }, + "wal_status": { + "enum": ["extended", "lost", null, "reserved", "unknown", "unreserved"], + "nullable": true, + "type": "string" + }, + "write_lag_ms": { + "minimum": 0, + "nullable": true, + "type": "number" } }, "required": [ "active", - "wal_status", - "write_lag_ms", - "flush_lag_ms", - "flush_lag_bytes", "feedback_age_ms", - "source" + "flush_lag_bytes", + "flush_lag_ms", + "source", + "wal_status", + "write_lag_ms" ], - "description": "Postgres feedback from the replication slot named in source. Null when no feedback is available, including while the pipeline is stopped. Feedback age measures time since the slot last responded and does not establish how current query results are.", - "nullable": true + "type": "object" }, - "lag_ms": { - "type": "number", - "minimum": 0, - "description": "Flush lag in milliseconds that Postgres reports for the slot in replication_feedback. Null when there is no feedback or Postgres reports no recent measurement, which includes a caught-up slot without new WAL; replication_feedback.flush_lag_bytes reads 0 in that case.", - "nullable": true + "replication_state": { + "description": "Last replication state the pipeline recorded for the table, also while the pipeline is stopped. Null when none was observed.", + "enum": [ + "copied_table", + "copying_table", + "error", + "following_wal", + null, + "queued" + ], + "nullable": true, + "type": "string" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" + }, + "status": { + "description": "Replication status. error means the table failed to replicate; stopped means the pipeline is stopped, stopping or failed, so the table receives no changes; live means the table follows changes; syncing means it is queued, copying or catching up; unknown means the pipeline status or the table state was not observed, for example before replication starts.", + "enum": ["error", "live", "stopped", "syncing", "unknown"], + "type": "string" + }, + "warehouse_name": { + "description": "Quoted, fully qualified name of the replicated table in the Warehouse.", + "type": "string" } }, "required": [ - "schema", + "lag_ms", "name", - "warehouse_name", - "status", - "replication_state", "observed_at", "replication_feedback", - "lag_ms" - ] + "replication_state", + "schema", + "status", + "warehouse_name" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table"], + "type": "string" } }, - "required": ["type", "id", "attributes"] + "required": ["attributes", "id", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseTableLayoutResponse_Output": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_table_layout"] - }, - "id": { - "type": "string", - "maxLength": 10, - "pattern": "^[1-9]\\d*$", - "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", - "example": "16385" - }, "attributes": { - "type": "object", "properties": { - "pipeline_id": { - "type": "string", - "description": "Warehouse replication pipeline identity." - }, - "schema": { - "type": "string", - "description": "Source PostgreSQL schema of the table." - }, - "name": { - "type": "string", - "description": "Source PostgreSQL table name." - }, "application_status": { - "type": "string", - "description": "Backend orchestration state. Runtime acceptance does not establish that the desired layout has been observed in the catalog." - }, - "reset_table": { - "type": "boolean", - "description": "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy." + "description": "Backend orchestration state. Runtime acceptance does not establish that the desired layout has been observed in the catalog.", + "type": "string" }, - "desired": { - "type": "object", - "properties": { - "sort_by": { - "anyOf": [ - { - "oneOf": [ - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["none"] - } - }, - "required": ["kind"] - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["primary_key"] - } - }, - "required": ["kind"] - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["columns"] - }, - "columns": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Source column name." - }, - "direction": { - "type": "string", - "enum": ["asc", "desc"] - }, - "nulls": { - "type": "string", - "enum": ["first", "last", null], - "description": "Null placement. Null uses DuckLake's default placement.", - "nullable": true - } - }, - "required": ["name", "direction", "nulls"] - } - } - }, - "required": ["kind", "columns"] - } - ] - }, - { - "type": "object", - "nullable": true, - "enum": [null] - } - ], - "description": "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged." - }, + "desired": { + "description": "Saved layout rules. The replicator applies them on start and hourly, so they can differ from the observed layout.", + "properties": { "partition_by": { - "type": "array", + "description": "Configured partition keys in order. An empty list explicitly clears partitioning; null leaves it unmanaged.", "items": { - "type": "object", "properties": { "column": { - "type": "string", - "description": "Source column name." + "description": "Source column name.", + "type": "string" }, "transform": { "oneOf": [ { - "type": "object", "properties": { "kind": { - "type": "string", - "enum": ["identity"] + "enum": ["identity"], + "type": "string" } }, - "required": ["kind"] + "required": ["kind"], + "type": "object" }, { - "type": "object", "properties": { "kind": { - "type": "string", - "enum": ["year"] + "enum": ["year"], + "type": "string" } }, - "required": ["kind"] + "required": ["kind"], + "type": "object" }, { - "type": "object", "properties": { "kind": { - "type": "string", - "enum": ["month"] + "enum": ["month"], + "type": "string" } }, - "required": ["kind"] + "required": ["kind"], + "type": "object" }, { - "type": "object", "properties": { "kind": { - "type": "string", - "enum": ["day"] + "enum": ["day"], + "type": "string" } }, - "required": ["kind"] + "required": ["kind"], + "type": "object" }, { - "type": "object", "properties": { "kind": { - "type": "string", - "enum": ["hour"] + "enum": ["hour"], + "type": "string" } }, - "required": ["kind"] + "required": ["kind"], + "type": "object" }, { - "type": "object", "properties": { - "kind": { - "type": "string", - "enum": ["bucket"] - }, "count": { - "type": "integer", + "description": "Number of hash buckets.", "exclusiveMinimum": true, "maximum": 2147483647, - "description": "Number of hash buckets.", - "minimum": 0 + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" } }, - "required": ["kind", "count"] + "required": ["count", "kind"], + "type": "object" } ] } }, - "required": ["column", "transform"] + "required": ["column", "transform"], + "type": "object" }, - "description": "Configured partition keys in order. An empty list explicitly clears partitioning; null leaves it unmanaged.", - "nullable": true + "nullable": true, + "type": "array" + }, + "sort_by": { + "description": "Configured sort order. none explicitly clears sorting, primary_key sorts by the source primary-key columns in key order, and columns lists them. Null leaves sorting unmanaged.", + "oneOf": [ + { + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "properties": { + "columns": { + "items": { + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name", "nulls"], + "type": "object" + }, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + }, + { + "type": "object", + "nullable": true, + "enum": [null] + } + ] } }, - "required": ["sort_by", "partition_by"], - "description": "Saved layout rules. The replicator applies them on start and hourly, so they can differ from the observed layout." + "required": ["partition_by", "sort_by"], + "type": "object" + }, + "name": { + "description": "Source PostgreSQL table name.", + "type": "string" }, "observation_status": { - "type": "string", - "enum": ["observed", "table_missing", "unavailable", "not_requested"], - "description": "observed when the DuckLake catalog was read, table_missing when the catalog has no table for it yet, unavailable when the catalog could not be read, and not_requested when an update returned without reading the catalog." + "description": "observed when the DuckLake catalog was read, table_missing when the catalog has no table for it yet, unavailable when the catalog could not be read, and not_requested when an update returned without reading the catalog.", + "enum": ["not_requested", "observed", "table_missing", "unavailable"], + "type": "string" }, "observed": { - "type": "object", + "description": "Layout recorded in the DuckLake catalog, null unless observation_status is observed. Catalog metadata governs files written after it changes and does not establish that existing files are sorted or partitioned.", + "nullable": true, "properties": { - "sort_by": { - "type": "array", + "observed_at": { + "description": "Time the catalog metadata was read.", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", + "type": "string" + }, + "partition_by": { + "description": "Active partition keys in key order, with transforms as the catalog reports them, for example bucket(16).", "items": { - "type": "object", "properties": { - "expression": { - "type": "string" - }, - "direction": { + "column": { "type": "string" }, - "nulls": { + "transform": { "type": "string" } }, - "required": ["expression", "direction", "nulls"] + "required": ["column", "transform"], + "type": "object" }, - "description": "Active sort expressions in key order, as the catalog reports them." + "type": "array" }, - "partition_by": { - "type": "array", + "sort_by": { + "description": "Active sort expressions in key order, as the catalog reports them.", "items": { - "type": "object", "properties": { - "column": { + "direction": { "type": "string" }, - "transform": { + "expression": { + "type": "string" + }, + "nulls": { "type": "string" } }, - "required": ["column", "transform"] + "required": ["direction", "expression", "nulls"], + "type": "object" }, - "description": "Active partition keys in key order, with transforms as the catalog reports them, for example bucket(16)." - }, - "observed_at": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$", - "description": "Time the catalog metadata was read." + "type": "array" } }, - "required": ["sort_by", "partition_by", "observed_at"], - "description": "Layout recorded in the DuckLake catalog, null unless observation_status is observed. Catalog metadata governs files written after it changes and does not establish that existing files are sorted or partitioned.", - "nullable": true + "required": ["observed_at", "partition_by", "sort_by"], + "type": "object" + }, + "pipeline_id": { + "description": "Warehouse replication pipeline identity.", + "type": "string" + }, + "reset_table": { + "description": "Whether this update reset source replication state. False for unchanged layouts and reads; reads do not retain reset history. True does not establish completion of recopy.", + "type": "boolean" + }, + "schema": { + "description": "Source PostgreSQL schema of the table.", + "type": "string" } }, "required": [ - "pipeline_id", - "schema", - "name", "application_status", - "reset_table", "desired", + "name", "observation_status", - "observed" - ] + "observed", + "pipeline_id", + "reset_table", + "schema" + ], + "type": "object" + }, + "id": { + "description": "Source PostgreSQL table OID, as returned by the Warehouse tables list.", + "example": "16385", + "maxLength": 10, + "pattern": "^[1-9]\\d*$", + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table_layout"], + "type": "string" } }, - "required": ["type", "id", "attributes"] + "required": ["attributes", "id", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "V2WarehouseTableLayoutUpdateRequest": { - "type": "object", "properties": { "data": { - "type": "object", "properties": { - "type": { - "type": "string", - "description": "Resource type.", - "enum": ["warehouse_table_layout"] - }, "attributes": { "anyOf": [ { - "type": "object", + "additionalProperties": false, "properties": { - "reset_table": { - "description": "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", - "type": "boolean" - }, - "sort_by": { - "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", - "anyOf": [ - { - "oneOf": [ - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["none"] - } - }, - "required": ["kind"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["primary_key"] - } - }, - "required": ["kind"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": ["columns"] - }, - "columns": { - "minItems": 1, - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "description": "Source column name." - }, - "direction": { - "type": "string", - "enum": ["asc", "desc"] - }, - "nulls": { - "type": "string", - "enum": ["first", "last", null], - "description": "Null placement. Null uses DuckLake's default placement.", - "nullable": true - } - }, - "required": ["name", "direction"], - "additionalProperties": false - } - } - }, - "required": ["kind", "columns"], - "additionalProperties": false - } - ] - }, - { - "type": "object", - "nullable": true, - "enum": [null] - } - ] - }, "partition_by": { - "type": "array", + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{\"column\":\"event_at\",\"transform\":{\"kind\":\"day\"}}]`. Bucket example: `[{\"column\":\"tenant_id\",\"transform\":{\"kind\":\"bucket\",\"count\":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.", "items": { - "type": "object", + "additionalProperties": false, "properties": { "column": { - "type": "string", + "description": "Source column name.", "minLength": 1, - "description": "Source column name." + "type": "string" }, "transform": { "oneOf": [ { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["identity"] + "enum": ["identity"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["year"] + "enum": ["year"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["month"] + "enum": ["month"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["day"] + "enum": ["day"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["hour"] + "enum": ["hour"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { - "kind": { - "type": "string", - "enum": ["bucket"] - }, "count": { - "type": "integer", + "description": "Number of hash buckets.", "exclusiveMinimum": true, "maximum": 2147483647, - "description": "Number of hash buckets.", - "minimum": 0 + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" } }, - "required": ["kind", "count"], - "additionalProperties": false + "required": ["count", "kind"], + "type": "object" } ] } }, "required": ["column", "transform"], - "additionalProperties": false + "type": "object" }, - "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", - "nullable": true - } - }, - "required": ["sort_by"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { + "nullable": true, + "type": "array" + }, "reset_table": { "description": "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", "type": "boolean" }, "sort_by": { - "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", "anyOf": [ { "oneOf": [ { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["none"] + "enum": ["none"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["primary_key"] + "enum": ["primary_key"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { - "kind": { - "type": "string", - "enum": ["columns"] - }, "columns": { - "minItems": 1, - "type": "array", "items": { - "type": "object", + "additionalProperties": false, "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, "name": { - "type": "string", + "description": "Source column name.", "minLength": 1, - "description": "Source column name." - }, - "direction": { - "type": "string", - "enum": ["asc", "desc"] + "type": "string" }, "nulls": { - "type": "string", - "enum": ["first", "last", null], "description": "Null placement. Null uses DuckLake's default placement.", - "nullable": true + "enum": ["first", "last", null], + "nullable": true, + "type": "string" } }, - "required": ["name", "direction"], - "additionalProperties": false - } + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" } }, - "required": ["kind", "columns"], - "additionalProperties": false + "required": ["columns", "kind"], + "type": "object" } ] }, { - "type": "object", + "enum": [null], "nullable": true, - "enum": [null] + "type": "object" } - ] - }, + ], + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{\"kind\":\"columns\",\"columns\":[{\"name\":\"tenant_id\",\"direction\":\"asc\"},{\"name\":\"event_at\",\"direction\":\"desc\",\"nulls\":\"last\"}]}`. Sort by the primary key with `{\"kind\":\"primary_key\"}` or clear sorting with `{\"kind\":\"none\"}`." + } + }, + "required": ["sort_by"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { "partition_by": { - "type": "array", + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys. Day example: `[{\"column\":\"event_at\",\"transform\":{\"kind\":\"day\"}}]`. Bucket example: `[{\"column\":\"tenant_id\",\"transform\":{\"kind\":\"bucket\",\"count\":8}}]`. Use `[]` to clear or `null` to stop managing partitioning.", "items": { - "type": "object", + "additionalProperties": false, "properties": { "column": { - "type": "string", + "description": "Source column name.", "minLength": 1, - "description": "Source column name." + "type": "string" }, "transform": { "oneOf": [ { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["identity"] + "enum": ["identity"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["year"] + "enum": ["year"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["month"] + "enum": ["month"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["day"] + "enum": ["day"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { "kind": { - "type": "string", - "enum": ["hour"] + "enum": ["hour"], + "type": "string" } }, "required": ["kind"], - "additionalProperties": false + "type": "object" }, { - "type": "object", + "additionalProperties": false, "properties": { - "kind": { - "type": "string", - "enum": ["bucket"] - }, "count": { - "type": "integer", + "description": "Number of hash buckets.", "exclusiveMinimum": true, "maximum": 2147483647, - "description": "Number of hash buckets.", - "minimum": 0 + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" } }, - "required": ["kind", "count"], - "additionalProperties": false + "required": ["count", "kind"], + "type": "object" } ] } }, "required": ["column", "transform"], - "additionalProperties": false + "type": "object" }, - "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", - "nullable": true + "nullable": true, + "type": "array" + }, + "reset_table": { + "description": "Defaults to false, preserving historical files and replication progress. When the layout changes, true resets the table and copies it again. This requires initial sync to be enabled. Reads are disrupted during the copy. An unchanged layout never resets the table.", + "type": "boolean" + }, + "sort_by": { + "anyOf": [ + { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "additionalProperties": false, + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + } + ] + }, + { + "enum": [null], + "nullable": true, + "type": "object" + } + ], + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector. Example: `{\"kind\":\"columns\",\"columns\":[{\"name\":\"tenant_id\",\"direction\":\"asc\"},{\"name\":\"event_at\",\"direction\":\"desc\",\"nulls\":\"last\"}]}`. Sort by the primary key with `{\"kind\":\"primary_key\"}` or clear sorting with `{\"kind\":\"none\"}`." } }, "required": ["partition_by"], - "additionalProperties": false + "type": "object" } ] + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_table_layout"], + "type": "string" } }, - "required": ["type", "attributes"] + "required": ["attributes", "type"], + "type": "object" } }, - "required": ["data"] + "required": ["data"], + "type": "object" }, "ListLogDrainsResponse_Output": { "type": "object", @@ -52254,6 +52507,215 @@ } }, "required": ["data"] + }, + "V2WarehouseTableLayoutPartitionBy": { + "description": "Omit to preserve the saved partitioning. Null makes partitioning unmanaged. An empty list explicitly clears partitioning. Otherwise, supply all ordered partition keys.", + "items": { + "additionalProperties": false, + "properties": { + "column": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "transform": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["identity"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["year"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["month"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["day"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["hour"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "count": { + "description": "Number of hash buckets.", + "exclusiveMinimum": true, + "maximum": 2147483647, + "minimum": 0, + "type": "integer" + }, + "kind": { + "enum": ["bucket"], + "type": "string" + } + }, + "required": ["count", "kind"], + "type": "object" + } + ] + } + }, + "required": ["column", "transform"], + "type": "object" + }, + "nullable": true, + "type": "array" + }, + "V2WarehouseTableLayoutSortBy": { + "description": "Omit to preserve the saved sorting. Null makes sorting unmanaged. The none selector explicitly clears sorting. Otherwise, supply the complete sort selector.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["none"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "kind": { + "enum": ["primary_key"], + "type": "string" + } + }, + "required": ["kind"], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "additionalProperties": false, + "properties": { + "direction": { + "enum": ["asc", "desc"], + "type": "string" + }, + "name": { + "description": "Source column name.", + "minLength": 1, + "type": "string" + }, + "nulls": { + "description": "Null placement. Null uses DuckLake's default placement.", + "enum": ["first", "last", null], + "nullable": true, + "type": "string" + } + }, + "required": ["direction", "name"], + "type": "object" + }, + "minItems": 1, + "type": "array" + }, + "kind": { + "enum": ["columns"], + "type": "string" + } + }, + "required": ["columns", "kind"], + "type": "object" + }, + { + "type": "object", + "nullable": true, + "enum": [null] + } + ] + }, + "V2WarehouseRestartResponse_Output": { + "properties": { + "data": { + "properties": { + "attributes": { + "properties": { + "action": { + "enum": ["restart", "start"], + "type": "string" + }, + "application_status": { + "description": "The runtime request was accepted. This does not establish resumed replication or completed initial copies.", + "enum": ["accepted"], + "type": "string" + }, + "pipeline_id": { + "type": "string" + }, + "pipeline_status_before": { + "type": "string" + } + }, + "required": [ + "action", + "application_status", + "pipeline_id", + "pipeline_status_before" + ], + "type": "object" + }, + "id": { + "type": "string" + }, + "type": { + "description": "Resource type.", + "enum": ["warehouse_replication_restart"], + "type": "string" + } + }, + "required": ["attributes", "id", "type"], + "type": "object" + } + }, + "required": ["data"], + "type": "object" } } } diff --git a/packages/api/src/generated/permissions.ts b/packages/api/src/generated/permissions.ts index 7247a56d76..0619fa3cd8 100644 --- a/packages/api/src/generated/permissions.ts +++ b/packages/api/src/generated/permissions.ts @@ -338,15 +338,15 @@ export const operationPermissions: Readonly oauthScope: "projects:read", }, "v2-add-warehouse-replication": { - fga: [["project_admin_write", "database_write"]], + fga: [["database_write", "project_admin_write"]], oauthScope: "database:write", }, "v2-remove-warehouse-replication": { - fga: [["project_admin_write", "database_write"]], + fga: [["database_write", "project_admin_write"]], oauthScope: "database:write", }, "v2-resync-warehouse-replication": { - fga: [["project_admin_write", "database_write"]], + fga: [["database_write", "project_admin_write"]], oauthScope: "database:write", }, "v2-get-warehouse-capacity": { fga: [["database_read"]], oauthScope: "database:read" }, @@ -371,7 +371,7 @@ export const operationPermissions: Readonly "v2-get-warehouse-table": { fga: [["database_read"]], oauthScope: "database:read" }, "v2-get-warehouse-table-layout": { fga: [["database_read"]], oauthScope: "database:read" }, "v2-update-warehouse-table-layout": { - fga: [["project_admin_write", "database_write"]], + fga: [["database_write", "project_admin_write"]], oauthScope: "database:write", }, "v2-list-log-drains": { fga: [["analytics_config_read"]], oauthScope: "analytics_config:read" }, @@ -480,4 +480,8 @@ export const operationPermissions: Readonly "v2-organizations-slug-webhooks-endpoints-id-test-post": { fga: [] }, "v2-organizations-slug-webhooks-deliveries-id-get": { fga: [] }, "v2-organizations-slug-webhooks-deliveries-id-retry-post": { fga: [] }, + "v2-restart-warehouse-replication": { + fga: [["database_write", "project_admin_write"]], + oauthScope: "database:write", + }, }; diff --git a/packages/config/src/experimental.ts b/packages/config/src/experimental.ts index 28cddd19a8..d41dcdf99c 100644 --- a/packages/config/src/experimental.ts +++ b/packages/config/src/experimental.ts @@ -38,6 +38,12 @@ export const experimental = Schema.Struct({ tags, }), ), + warehouse: Schema.optionalKey( + Schema.Boolean.annotate({ + description: "Enable the experimental warehouse command family.", + tags, + }), + ), stack: Schema.optionalKey( Schema.Boolean.annotate({ description: diff --git a/packages/config/src/project-config/hosted-sections.ts b/packages/config/src/project-config/hosted-sections.ts index 24a5acd3df..de27043cdd 100644 --- a/packages/config/src/project-config/hosted-sections.ts +++ b/packages/config/src/project-config/hosted-sections.ts @@ -52,6 +52,7 @@ export const DOCUMENT_ONLY_LOCAL_PATHS = [ ["realtime", "max_header_length"], ["experimental", "stack"], ["experimental", "compute"], + ["experimental", "warehouse"], ["experimental", "orioledb_version"], ["experimental", "s3_host"], ["experimental", "s3_region"], diff --git a/packages/config/src/project-config/project-config.unit.test.ts b/packages/config/src/project-config/project-config.unit.test.ts index c3254484a0..c834ef5f09 100644 --- a/packages/config/src/project-config/project-config.unit.test.ts +++ b/packages/config/src/project-config/project-config.unit.test.ts @@ -645,6 +645,7 @@ describe("fromConfigDocument — CLI-only field exclusion (CLI-2316)", () => { realtime: { enabled: false, ip_version: "IPv6", max_header_length: 1 }, experimental: { compute: true, + warehouse: true, stack: true, orioledb_version: "", s3_host: "host", diff --git a/turbo.json b/turbo.json index 57070cfac9..551afd903d 100644 --- a/turbo.json +++ b/turbo.json @@ -26,6 +26,9 @@ "fmt:fix": { "cache": false }, + "api-commands:check": { + "cache": false + }, "knip:check": { "cache": false }, @@ -82,6 +85,18 @@ ], "outputs": ["schemas/**"] }, + "supabase#api-commands:generate": { + "cache": true, + "inputs": [ + "$TURBO_DEFAULT$", + "!src/commands/api/generated*", + "$TURBO_ROOT$/mise.lock", + "$TURBO_ROOT$/.oxfmtrc.json", + "$TURBO_ROOT$/packages/api/src/generated/openapi.json", + "$TURBO_ROOT$/packages/api/src/generated/contracts.ts" + ], + "outputs": ["src/commands/api/generated.ts", "src/commands/api/generated.md"] + }, "supabase#test:live": { "cache": false, "dependsOn": ["supabase#build"],