import { parseExactJson, exactInteger, compareExactNumbers } from './exact-json.ts'; import clockForm from '../world-clock.cjs'; // THE REAL-SYSTEM ADAPTERS, DERIVED (docs/contributing/architecture.md, "The real-system adapters"): a pack's perform, // refresh and ingest made by the kernel from its manifest and its generated surface, so no pack writes adapter code. // They run over the kernel executor (`RemoteExecute`), which applies the sealed credential; the credential never // reaches here, only its keyed fingerprint (`PerformContext.credential`, for the idempotency key). import type { TwinAction } from './actions.ts'; import { aliasesFrom, parentEntries, readParentTreeMap, readTree, wholeLog } from './log.ts'; import { fillTemplate, gitNameOf, gitRepositoryOf, storedType, type DerivedManifest, type IngestDecl, type ResourceDecl, type ScopedRefresh, type VendorManifest } from './derived-core.ts'; import type { DerivedOperation, DerivedSurface } from './derived.ts'; import { verifyEvent, type EventScheme } from './events.ts'; import { hashFieldValue } from './hash.ts'; import { readResourceBlob, writeResourceBlob } from './resource-blob.ts'; import { RefusedWriteError, settlingEntries, type PerformAction, type PerformContext, type PushOutcome } from './head.ts'; import { ZERO_SHA, fetchPack, isAncestor, lsRemote, sendPack, type SmartHttpTransport } from './git/index.ts'; import { observeResources, type Completed, type ObservedResource } from './observe.ts'; import type { RemoteExecute, RemoteExecuteResponse } from './remote-execute.ts'; import { readRoot, type StateSystemAdapters } from './state-system.ts'; type Unit = { manifest: DerivedManifest; surface: DerivedSurface; lane?: string }; type Row = Record; /** A JSON path's value: `a.b`, `a[0].b`, `$body.a` (the leading `$body.` read as the root). */ function at(value: unknown, path: string): unknown { if (value && typeof value === 'object' && Object.hasOwn(value, path)) return (value as Row)[path]; let cur = value; for (const part of path.replace(/^\$body\.?/, '').split(/\.|\[(\d+)\]/).filter((p) => p !== undefined && p !== '')) { if (cur === null || typeof cur !== 'object') return undefined; cur = (cur as Row)[part]; } return cur; } const object = (v: unknown): Row | undefined => (v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Row) : undefined); const parse = (r: RemoteExecuteResponse): unknown => { if (r.body && r.body.trimStart().startsWith('<')) return fromXml(r.body); try { return r.body ? parseExactJson(r.body) : undefined; } catch { return r.body; } }; /** Link header relations and extension parameters, with commas and escapes inside quoted values preserved. */ function linkRelations(value: string): Array<{ url: string; params: Record }> { const links: Array<{ url: string; params: Record }> = []; let rest = value.trim(); while (rest) { const target = /^<([^<>]+)>/.exec(rest); if (!target) throw new Error('refresh continuation has a malformed Link header; nothing folded'); rest = rest.slice(target[0].length).trimStart(); const params: Record = {}; while (rest.startsWith(';')) { const param = /^;\s*([\w!#$%&'*+.^`|~-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s;,]+))\s*/.exec(rest); if (!param) throw new Error('refresh continuation has a malformed Link parameter; nothing folded'); const name = param[1]!.toLowerCase(); if (name in params) throw new Error('refresh continuation repeats a Link parameter; nothing folded'); params[name] = param[2] !== undefined ? param[2].replace(/\\(.)/g, '$1') : param[3]!; rest = rest.slice(param[0].length); } links.push({ url: target[1]!, params }); if (rest && !rest.startsWith(',')) throw new Error('refresh continuation has a malformed Link separator; nothing folded'); if (rest) { rest = rest.slice(1).trimStart(); if (!rest) throw new Error('refresh continuation ends with a Link separator; nothing folded'); } } return links; } /** An XML answer (S3's lists: ListObjectsV2, ListMultipartUploads, ListParts) read as JSON, so a refresh scope names its * items as it does a JSON answer's (`ListBucketResult.Contents`): an element with children is an object of them, a * child repeated a list of them, a leaf its text; attributes, declarations and comments are not read. */ function fromXml(text: string): Row { const decode = (t: string): string => t.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&#(\d+);/g, (_, n: string) => String.fromCodePoint(Number(n))).replace(/&/g, '&'); type Node = { name: string; obj: Row; text: string; children: boolean }; const stack: Node[] = [{ name: '', obj: {}, text: '', children: false }]; const put = (parent: Node, name: string, value: unknown): void => { const held = parent.obj[name]; parent.obj[name] = held === undefined ? value : Array.isArray(held) ? [...held, value] : [held, value]; parent.children = true; }; for (const m of text.matchAll(/<\?[\s\S]*?\?>|||<(\/?)([A-Za-z_][\w:.-]*)[^>]*?(\/?)>|([^<]+)/g)) { const top = stack.at(-1)!; if (m[1] !== undefined) top.text += m[1]; else if (m[5] !== undefined) top.text += decode(m[5]); else if (m[3] !== undefined && m[4] === '/') put(top, m[3], ''); else if (m[3] !== undefined && m[2] !== '/') stack.push({ name: m[3], obj: {}, text: '', children: false }); else if (m[3] !== undefined && stack.length > 1) { const node = stack.pop()!; put(stack.at(-1)!, node.name, node.children ? node.obj : node.text.trim()); } } return stack[0]!.obj; } /** The manifest's resource a surface schema answers (the operation's `answers.resource` is the spec's schema name). */ function resourceOf(m: DerivedManifest, schema: string | undefined): string | undefined { if (!schema) return undefined; if (m.resources[schema]) return schema; const normalized = (name: string): string => name.replace(/_/g, '').toLowerCase(); const lower = normalized(schema); return Object.keys(m.resources).find((r) => normalized(r) === lower || normalized(storedType(m, r)) === lower); } /** The error template's fixed leaves (Slack's `ok: false`): an answer holding them all is the vendor's refusal, whatever * its status (a vendor that answers its errors 200). */ function refusalShape(m: DerivedManifest): Array<[string, unknown]> { const out: Array<[string, unknown]> = []; const walk = (v: unknown, path: string): void => { if (typeof v === 'string' && /\{\w+\}/.test(v)) return; const o = object(v); if (o) { for (const [k, x] of Object.entries(o)) walk(x, path ? `${path}.${k}` : k); return; } if (path) out.push([path, v]); }; walk(m.error, ''); return out; } /** The words of a refusal, at the template's `{message}` (else `{code}`) place. */ function refusalWords(m: DerivedManifest, body: unknown): string { let found: string | undefined; const walk = (v: unknown, path: string): void => { if (typeof v === 'string' && (v.includes('{message}') || (found === undefined && v.includes('{code}')))) { const said = at(body, path); if (said !== undefined) found = String(said); return; } const o = object(v); if (o) for (const [k, x] of Object.entries(o)) walk(x, path ? `${path}.${k}` : k); }; walk(m.error, ''); return found ?? (typeof body === 'string' ? body : JSON.stringify(body ?? null)).slice(0, 300); } /** Whether an answer is the vendor's refusal whatever its status: it holds every fixed leaf of the error template (Slack's * `ok: false`), as a perform reads it ("Refresh": a 200 refusal is never folded as an empty page). */ function refusedIn(m: DerivedManifest, body: unknown): boolean { const shape = refusalShape(m); return shape.length > 0 && shape.every(([p, v]) => at(body, p) === v); } /** Every string in a body that names a subject the vendor knows by another id, as the vendor names it. */ function resolvedDeep(value: unknown, resolve: (v: string) => string): unknown { if (typeof value === 'string') return resolve(value); if (Array.isArray(value)) return value.map((v) => resolvedDeep(v, resolve)); const o = object(value); return o ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, resolvedDeep(v, resolve)])) : value; } /** A multipart body: the recorded fields, then each recorded file part read back from the World's blob store. An * operation the vendor takes as multipart is sent so with no file part too (a Workers upload of assets alone carries * only its `metadata` field). */ async function multipart(body: unknown, files: Row[], ctx: PerformContext): Promise<{ body: Uint8Array; type: string }> { const boundary = `----volter${hashFieldValue({ body, files }).slice(0, 24)}`; const chunks: Uint8Array[] = []; const text = (t: string): void => { chunks.push(new TextEncoder().encode(t)); }; for (const [k, v] of Object.entries(object(body) ?? {})) if (v !== undefined && v !== null) text(`--${boundary}\r\ncontent-disposition: form-data; name="${k}"\r\n\r\n${typeof v === 'object' ? JSON.stringify(v) : String(v)}\r\n`); for (const f of files) { const bytes = await readResourceBlob(ctx.service ?? '', String(f.blob), ctx.root); if (!bytes) throw new Error(`the recorded file ${String(f.name)} is not in the World's blob store (${String(f.blob)})`); text(`--${boundary}\r\ncontent-disposition: form-data; name="${String(f.field)}"; filename="${String(f.name)}"\r\n${f.type ? `content-type: ${String(f.type)}\r\n` : ''}\r\n`); chunks.push(bytes); text('\r\n'); } text(`--${boundary}--\r\n`); const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); let at = 0; for (const c of chunks) { out.set(c, at); at += c.length; } return { body: out, type: `multipart/form-data; boundary=${boundary}` }; } /** What every call of an operation carries beyond its parameters: its query discriminator (S3's `?uploads`, a bare key * where its value is null) and its fixed headers (AWS JSON's `x-amz-target`), as the route that serves it reads them. */ function marked(op: DerivedOperation, path: string): string { const query = new URLSearchParams(path.includes('?') ? path.slice(path.indexOf('?') + 1) : ''); const marks = Object.entries(op.discriminator ?? {}).filter(([k]) => !query.has(k)).map(([k, v]) => (v === null ? encodeURIComponent(k) : `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)); return marks.length ? `${path}${path.includes('?') ? '&' : '?'}${marks.join('&')}` : path; } /** Where a unit's call goes: a lane on a host of its own (`remoteHost`, the real-system adapters "Lanes") to that host, * filled from the call's parameters, as an absolute URL the executor admits only on a host the descriptor declares; any * other call to its path on the root's origin. A parameter is one host label, or the literal `values` maps it to. */ function sentTo(m: DerivedManifest, path: string, params: Record): string { if (!m.remoteHost) return path; const { template, values } = m.remoteHost; const host = template.replace(/\{([^}]+)\}/g, (_, name: string) => { const raw = params[name] === undefined || params[name] === null ? '' : String(params[name]); const mapped = values?.[name]; if (mapped) { const literal = mapped[raw]; if (literal === undefined) throw new Error(`${m.vendor}: the remote host has no value for ${name} ${JSON.stringify(raw)}`); return literal; } if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/i.test(raw)) throw new Error(`${m.vendor}: the remote host's ${name} is missing or is not a host label`); return raw; }); return `https://${host}${path}`; } const fixedHeaders = (op: DerivedOperation): Record => Object.fromEntries(Object.entries(op.headers ?? {}).filter((e): e is [string, string] => typeof e[1] === 'string')); /** The body as the operation's encoding sends it. */ function encode(op: DerivedOperation, body: unknown): { body?: string; type?: string } { // a body the request carried where the spec declares none (Tinybird's Events API, NDJSON its client sends as text): // the body as recorded, as the vendor read it if (body === undefined) return {}; if (op.bodyEncoding === 'form') { // a form's nested values in the bracket form a form-encoded API reads (`scope[type]=account`, `items[0][price]=…`), // the form the kernel's own parseBracketForm reads back; never a value's JSON text const form = new URLSearchParams(); const put = (key: string, v: unknown): void => { if (v === undefined || v === null) return; if (Array.isArray(v)) { v.forEach((item, i) => put(`${key}[${i}]`, item)); return; } if (typeof v === 'object') { for (const [k, x] of Object.entries(v as Record)) put(`${key}[${k}]`, x); return; } form.append(key, String(v)); }; for (const [k, v] of Object.entries(object(body) ?? {})) put(k, v); return { body: form.toString(), type: 'application/x-www-form-urlencoded' }; } return { body: JSON.stringify(body), type: 'application/json' }; } /** The unit an entry was written through: its recorded lane, else the one whose surface names its operation (a line * protocol's lane, an SMTP submission's, has commands and no operations). */ function unitOf(units: Unit[], input: Row): Unit | undefined { const id = input.operationId; return (typeof input.lane === 'string' ? units.find((u) => u.lane === input.lane) : undefined) ?? units.find((u) => (u.surface.operations ?? []).some((o) => o.id === id)) ?? (input.graphql ? units[0] : undefined); } /** Read the schema-selected resource through response aliases and fragment selections. */ async function graphqlAnswers(m: DerivedManifest, surface: DerivedSurface, input: Row, parsed: unknown): Promise> { if (!surface.graphql) throw new Error('a GraphQL perform needs the vendored schema on its derived surface'); const g = await import('graphql'); const schema = g.buildSchema(surface.graphql.sdl, { assumeValidSDL: true }); const sent = object(input.graphql)!; const document = g.parse(String(sent.query)); const operation = g.getOperationAST(document, typeof sent.operationName === 'string' ? sent.operationName : undefined); if (!operation || operation.operation !== 'mutation') throw new Error('the recorded GraphQL write has no selected mutation'); const fragments = new Map(document.definitions.filter((d): d is import('graphql').FragmentDefinitionNode => d.kind === 'FragmentDefinition').map((d) => [d.name.value, d])); const fields = (selection: import('graphql').SelectionSetNode, seen = new Set()): import('graphql').FieldNode[] => selection.selections.flatMap((node) => { if (node.kind === 'Field') return [node]; if (node.kind === 'InlineFragment') return fields(node.selectionSet, seen); if (seen.has(node.name.value)) return []; const fragment = fragments.get(node.name.value); return fragment ? fields(fragment.selectionSet, new Set([...seen, node.name.value])) : []; }); const decode = (value: unknown, selection?: import('graphql').SelectionSetNode): unknown => { if (Array.isArray(value)) return value.map((v) => decode(v, selection)); const row = object(value); if (!row || !selection) return value; const decoded: Row = {}; for (const field of fields(selection)) { const key = field.alias?.value ?? field.name.value; if (key in row) decoded[field.name.value] = decode(row[key], field.selectionSet); } return decoded; }; const answers: Array<{ resource: string; value?: Row }> = []; for (const root of fields(operation.selectionSet)) { const definition = schema.getMutationType()?.getFields()[root.name.value]; if (!definition) continue; const type = g.getNamedType(definition.type); const value = object(at(parsed, `data.${root.alias?.value ?? root.name.value}`)); // Skipped selections (directives) have no answer and adopt nothing. if (!value) continue; const resource = resourceOf(m, type.name); if (resource) { answers.push({ resource, value: object(decode(value, root.selectionSet)) }); continue; } if (g.isObjectType(type) && root.selectionSet) for (const child of fields(root.selectionSet)) { const field = type.getFields()[child.name.value]; const resource = field ? resourceOf(m, g.getNamedType(field.type).name) : undefined; const selected = object(value[child.alias?.value ?? child.name.value]); if (resource && selected) answers.push({ resource, value: object(decode(selected, child.selectionSet)) }); } } return answers; } /** The account a root is, before a perform sends a path naming the World's ("The account a root is"): the World's * account its own doors made, unadopted, adopts the one account the root's credential lists. Read once per deploy (an * adopted account is not asked again); a list the vendor refuses, or one naming several accounts, adopts none. */ /** The accounts a root's list already named as the World's own (the World's id is the vendor's), by service and root: * nothing to adopt, so not asked again. */ const accountsMatched = new Map>(); async function adoptAccount(units: Unit[], execute: RemoteExecute, ctx: PerformContext): Promise { if (ctx.service === undefined) return; const matched = accountsMatched.get(`${ctx.service}\u0000${ctx.root ?? ''}`) ?? new Set(); accountsMatched.set(`${ctx.service}\u0000${ctx.root ?? ''}`, matched); for (const u of units) { const m = u.manifest; const decl = m.account ? m.resources[m.account] : undefined; if (!m.account || !decl) continue; const type = storedType(m, m.account); const local = (readTree(ctx.service, ctx.root) as Row[]).filter((r) => r.type === type && r.deleted !== true && ctx.resolve(type, String(r.id)) === String(r.id)); const scope = decl.refresh; const op = scope && 'list' in scope ? u.surface.operations.find((o) => o.id === scope.list) : undefined; if (!local.length || !op || local.every((l) => matched.has(`${type}:${String(l.id)}`))) continue; const answer = await execute({ method: op.method.toUpperCase(), path: sentTo(m, marked(op, `${op.basePath ?? u.surface.basePath ?? ''}${op.path}`), {}), ...(u.lane ? { lane: u.lane } : {}), headers: fixedHeaders(op) }); if (answer.status >= 400) continue; const items = itemsOf(op, parse(answer)); const id = items.length === 1 ? storedIdOf(decl, items[0]!) : undefined; if (id !== undefined && local.some((l) => String(l.id) === id)) matched.add(`${type}:${id}`); if (id === undefined || local.some((l) => String(l.id) === id)) continue; observeResources(ctx.service, [{ type, id, fields: items[0] as ObservedResource['fields'], adopts: String(local[0]!.id) }], ctx.root !== undefined ? { root: ctx.root } : {}); } } function performOf(units: Unit[]): PerformAction { // the request a group's first entry recorded (or one a protocol hook changed), sent to the vendor const derived = async (execute: RemoteExecute, group: TwinAction[], ctx: PerformContext, input: Row): Promise => { const first = group[0]!; const unit = unitOf(units, input); if (!unit) throw new RefusedWriteError('vendor', `the write records no operation of the vendor's surface (${String(input.operationId ?? 'none')})`, first.id); // A credential the request carried was not kept (no World records one in plaintext: ADR 0025), so the request as // recorded is not the request that was made; it is refused, never sent without it. const withheld = Array.isArray(input.withheld) ? (input.withheld as unknown[]).map(String) : []; if (withheld.length) throw new RefusedWriteError('vendor', `the write's ${withheld.join(', ')} ${withheld.length === 1 ? 'was' : 'were'} not kept (no World records a credential in plaintext), so it is not sent again; make it at the vendor`, first.id); const { manifest: m, surface } = unit; // ids the World minted are sent as the vendor's: every stored type's adopted aliases, tried in turn const types = [...new Set(Object.keys(m.resources).map((r) => storedType(m, r)))]; const resolve = (v: string): string => { for (const t of types) { const r = ctx.resolve(t, v); if (r !== v) return r; } return v; }; let method: string; let path: string; let body: unknown; let op: DerivedOperation | undefined; // the parameters a lane's own host is filled from, as the vendor names them let hostParams: Record = {}; if (input.graphql) { const gql = (m as { graphql?: { paths: string[] } }).graphql; method = 'POST'; path = gql?.paths[0] ?? '/graphql'; const g = await import('graphql'); const recorded = object(input.graphql)!; const query = g.print(g.visit(g.parse(String(recorded.query)), { StringValue(node) { const value = resolve(node.value); return value === node.value ? undefined : { ...node, value }; } })); body = { ...recorded, query, variables: resolvedDeep(recorded.variables, resolve) }; } else { op = surface.operations.find((o) => o.id === input.operationId)!; method = op.method.toUpperCase(); const params = { ...((object(input.path) ?? {}) as Record) }; const queried = { ...((object(input.query) ?? {}) as Record) }; const sentBody = input.body === undefined ? undefined : object(input.body) ? { ...object(input.body)! } : input.body; // a subject named by its key's parts (Slack's message: its `channel` and its `ts`): the parts the request sends, // resolved as one id and sent as the vendor's parts for (const [resource, decl] of Object.entries(m.resources)) { if (!decl.key) continue; const names = [...decl.key.matchAll(/\{([^}]+)\}/g)].map((x) => x[1]!); const where = (n: string): Record | undefined => [params, queried, object(sentBody)].find((o) => o !== undefined && typeof o[n] === 'string') as Record | undefined; if (!names.every((n) => where(n))) continue; const local = decl.key.replace(/\{([^}]+)\}/g, (_, n: string) => String(where(n)![n])); const vendorId = ctx.resolve(storedType(m, resource), local); if (vendorId === local) continue; const parts = new RegExp(`^${decl.key.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\\\{[^}]+\\\}|\{[^}]+\}/g, '(.+?)')}$`).exec(vendorId); if (parts) names.forEach((n, i) => { where(n)![n] = parts[i + 1]!; }); } if (op.resource && ctx.service !== undefined) vendorFieldParams(m, op.resource, params, ctx); path = `${op.basePath ?? surface.basePath ?? ''}${op.path}`.replace(/\{([^}]+)\}/g, (_, name: string) => encodeURIComponent(resolve(String(params[name] ?? '')))); const query = new URLSearchParams(Object.entries(queried).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((x): [string, string] => [k, resolve(String(x))]))); if ([...query].length) path += `?${query}`; path = marked(op, path); body = sentBody === undefined ? undefined : resolvedDeep(sentBody, resolve); hostParams = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, resolve(String(v))])); } const files = Array.isArray(input.files) ? (input.files as Row[]) : []; // a body recorded as it came (not JSON) goes as it came const asCame = object(input.body); const raw = asCame && typeof asCame.$text === 'string' ? { body: asCame.$text as string } : asCame && typeof asCame.$base64 === 'string' ? { body: new Uint8Array(Buffer.from(asCame.$base64 as string, 'base64')) } : undefined; const sent: { body?: string | Uint8Array; type?: string } = raw ? { ...raw, ...(typeof input.contentType === 'string' ? { type: input.contentType } : {}) } : files.length || op?.bodyEncoding === 'multipart' ? await multipart(body, files, ctx) : op ? encode(op, body) : { body: JSON.stringify(body), type: 'application/json' }; const headers: Record = { ...(op ? fixedHeaders(op) : {}), ...((object(input.headers) ?? {}) as Record), ...(sent.type ? { 'content-type': sent.type } : {}) }; // a retried deploy makes nothing twice, and two Worlds deploying into one account never collide // (a vendor keyed by a header only: a body key or a content key is the recorded request's own) const keyHeader = m.idempotency && (m.idempotency.key ? ('header' in m.idempotency.key ? m.idempotency.key.header : undefined) : m.idempotency.header); if (keyHeader) headers[keyHeader] = hashFieldValue({ credential: ctx.credential ?? '', entry: first.id }); const answer = await execute({ method, path: sentTo(m, path, hostParams), ...(unit.lane ? { lane: unit.lane } : {}), headers, ...(sent.body !== undefined ? { body: sent.body } : {}) }); const parsed = parse(answer); const gqlErrors = input.graphql && Array.isArray(at(parsed, 'errors')) ? at(parsed, 'errors') as Row[] : []; if (answer.status === 408 || answer.status === 429 || answer.status >= 500) throw new Error(`${answer.status}: ${refusalWords(m, parsed)}${answer.headers['retry-after'] ? ` (retry after ${answer.headers['retry-after']}s)` : ''}`); if (gqlErrors.length) throw new RefusedWriteError('vendor', `400: ${gqlErrors.map((e) => String(e.message)).join('; ')}`, first.id); const refused = answer.status >= 400 || refusedIn(m, parsed); if (refused) throw new RefusedWriteError('vendor', `${answer.status >= 400 ? answer.status : 400}: ${refusalWords(m, parsed)}`, first.id); // the subject the answer is: under the operation's key, inside the success envelope when the vendor has one const key = op?.answers?.key; if (input.graphql) { const answers = await graphqlAnswers(m, surface, input, parsed); const remaining = [...group]; const adopted: Array<{ actionId: string; externalId: string; data: Row }> = []; for (const answer of answers) { const index = remaining.findIndex((entry) => entry.subject.type === storedType(m, answer.resource)); if (index < 0) continue; const entry = remaining.splice(index, 1)[0]!; const decl = m.resources[answer.resource]!; const data = answer.value ?? {}; const externalId = entry.fields?.deleted === true ? ctx.resolve(entry.subject.type, entry.subject.id) : storedIdOf(decl, data) ?? ''; adopted.push({ actionId: entry.id, externalId, data }); } const primary = adopted.shift(); return primary ? { ...primary, response: answer, ...(adopted.length ? { also: adopted } : {}) } : { externalId: '', actionId: group.at(-1)!.id, response: answer }; } // an XML answer is read through its document element (S3's `InitiateMultipartUploadResult`), as a JSON one under its key const documentElement = (): Row | undefined => { const root = object(parsed); const names = root ? Object.keys(root) : []; return answer.body.trimStart().startsWith('<') && names.length === 1 ? object(root![names[0]!]) : undefined; }; const obj = object(key ? at(parsed, key) : parsed === undefined ? undefined : documentElement() ?? parsed) ?? object(parsed) ?? {}; // the answered resource: the spec's schema name, else the envelope key the answer is under (Slack's `channel`, // `message`), when the manifest has a resource of that name const answerKey = op?.answers?.key; const resource = resourceOf(m, op?.answers?.resource) ?? (answerKey && m.resources[answerKey] ? answerKey : undefined); // an answer naming no resource of the manifest (an operation's own output structure: Secrets Manager's // CreateSecretResponse, S3's CreateMultipartUploadOutput) is the group's subject's, its id read by that resource const subjectDecl = (): ResourceDecl | undefined => Object.entries(m.resources).find(([r]) => storedType(m, r) === group.at(-1)!.subject.type)?.[1]; const decl: ResourceDecl | undefined = resource ? m.resources[resource] : subjectDecl(); const idOf = (o: Row | undefined, d: ResourceDecl | undefined): string | undefined => o ? storedIdOf(d ?? { idPrefix: '' }, o) : undefined; // the group's entry the answer is: of the answered resource's stored type (a cascade writes children first), else // the last; a delete answers its subject's own vendor id const answered = resource ? [...group].reverse().find((e) => e.subject.type === storedType(m, resource)) : undefined; const primary = answered ?? group.at(-1)!; // an answer about a subject no entry of the group is (Slack's conversations.join answers the channel; the group is // the membership and its channel_join message) gives no entry its id or its fields: each settles deployed with no // vendor id, and refresh adopts it ("Perform", step 2) if (resource && !answered) return { externalId: '', actionId: primary.id, response: answer }; const deleted = primary.fields?.deleted === true; // a keyed subject's id is its key filled from the answer (its envelope's fields, Slack's `channel` and `ts`, among them) const keyed = decl?.key ? decl : Object.entries(m.resources).find(([r]) => storedType(m, r) === primary.subject.type)?.[1]; const externalId = deleted ? ctx.resolve(primary.subject.type, primary.subject.id) : keyed?.key ? storedIdOf(keyed, { ...(object(parsed) ?? {}), ...obj }) ?? '' : idOf(obj, decl) ?? (ctx.resolve(primary.subject.type, primary.subject.id) !== primary.subject.id ? ctx.resolve(primary.subject.type, primary.subject.id) : ''); const also: Array<{ actionId: string; externalId: string }> = []; for (const [companion, where] of Object.entries(decl?.companions ?? keyed?.companions ?? {})) { const id = at(parsed, where) ?? at(obj, where); const entry = group.find((e) => e !== primary && e.subject.type === storedType(m, companion)); if (entry && (typeof id === 'string' || typeof id === 'number')) also.push({ actionId: entry.id, externalId: String(id) }); } return { externalId, actionId: primary.id, data: obj, response: answer, ...(also.length ? { also } : {}) }; }; return async (execute: RemoteExecute, group: TwinAction[], ctx: PerformContext): Promise => { await adoptAccount(units, execute, ctx); const input = (group[0]!.input ?? {}) as Row; if (object(input.git)) return pushOf(units, execute, group, ctx); const unit = unitOf(units, input); // a protocol one request cannot express is the pack's hook, which composes the derived perform ("Protocols a // request cannot express") const hook = unit && typeof input.operationId === 'string' ? unit.manifest.performs?.[input.operationId] : undefined; if (!hook || !unit) return derived(execute, group, ctx, input); return hook({ execute, group, localGroup: ctx.localGroup ?? group, input, ctx, send: (changed) => derived(execute, group, ctx, changed), resolve: (type, localId) => ctx.resolve(type, localId), basePath: unit.surface.basePath ?? '', blob: (key) => readResourceBlob(ctx.service ?? '', key, ctx.root), }); }; } // ── git: a root's repositories over git's own smart HTTP (architecture, "The real-system adapters"; ADR 0031) ── type PushInput = { name: string; remote: string; ref: string; before: string; after: string }; const pushInputOf = (e: TwinAction): PushInput | undefined => object((e.input as Row | undefined)?.git) as PushInput | undefined; /** A 4xx other than 408 and 429 from the vendor's git: a refusal, as a REST answer's is ("Perform", 3). */ class GitAnswer extends Error { constructor(readonly status: number, message: string) { super(message); } } /** Git smart HTTP to a remote (the vendor's absolute git URL) over the root's executor, which applies the credential * (HostRule.basic) and charges the vendor's budget. */ function gitTransport(execute: RemoteExecute, remote: string): SmartHttpTransport { return async ({ service, body }) => { const answer = await execute({ method: body === undefined ? 'GET' : 'POST', path: body === undefined ? `${remote}/info/refs?service=${service}` : `${remote}/${service}`, headers: { 'user-agent': 'git/2.0 (volter-twin)', accept: body === undefined ? `application/x-${service}-advertisement` : `application/x-${service}-result`, ...(body === undefined ? {} : { 'content-type': `application/x-${service}-request` }), }, ...(body === undefined ? {} : { body }), responseType: 'bytes', }); if (answer.status !== 200) throw new GitAnswer(answer.status, `${answer.status}: git ${service} at ${remote}${answer.body ? `: ${answer.body.slice(0, 300)}` : ''}`); return answer.bodyBytes ?? new TextEncoder().encode(answer.body); }; } /** DEPLOY a receive-pack's group (its push rows, one per ref): each ref's latest target decided on its own, the rest * sent in one push against the root's refs (atomic when the root offers it), never forced. Each entry settles as its * ref did (`PushOutcome.refused`); every ref refused refuses the group. */ async function pushOf(units: Unit[], execute: RemoteExecute, group: TwinAction[], ctx: PerformContext): Promise { const first = group[0]!; const m = units.find((u) => u.manifest.git)?.manifest; const pushes = group.map((e) => ({ entry: e, push: pushInputOf(e) })); const refuseAll = (reason: string): never => { throw new RefusedWriteError('vendor', reason, first.id); }; if (!m || pushes.some((p) => p.push === undefined)) refuseAll('the push names no repository of the vendor\'s'); const { name, remote } = pushes[0]!.push!; if (pushes.some((p) => p.push!.name !== name || p.push!.remote !== remote)) refuseAll('one push names one repository'); const { store } = gitRepositoryOf(m!, name, ctx.root); const transport = gitTransport(execute, remote); const answered = (work: Promise): Promise => work.catch((error: unknown) => { if (error instanceof GitAnswer && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 429) refuseAll(error.message); throw error; }); const root = await answered(lsRemote(transport, 'git-receive-pack')); // each ref's latest target in the group, and why the root may not take it const targets = new Map(); for (const p of pushes) targets.set(p.push!.ref, p.push!.after); const refused = new Map(); const commands: Array<{ name: string; old: string; new: string }> = []; for (const [ref, target] of targets) { const old = root.refs.get(ref) ?? ZERO_SHA; if (old === target) continue; if (target !== ZERO_SHA && old !== ZERO_SHA) { if (ref.startsWith('refs/tags/')) { refused.set(ref, 'the tag already exists on the root'); continue; } if (!(await store.has(old))) { refused.set(ref, 'the root holds work this World has not fetched (fetch first)'); continue; } if (!(await isAncestor(store, old, target))) { refused.set(ref, `not a fast-forward of the root's ${old.slice(0, 7)}`); continue; } } commands.push({ name: ref, old, new: target }); } if (commands.length) { const report = await answered(sendPack(transport, store, commands, [...new Set(root.refs.values())], root.caps.includes('atomic'))); for (const c of commands) { const reason = report.get(c.name); if (reason !== null) refused.set(c.name, `the root refused it: ${reason}`); } } const took = pushes.filter((p) => !refused.has(p.push!.ref)); if (!took.length) refuseAll([...refused].map(([ref, reason]) => `${ref}: ${reason}`).join('; ')); return { externalId: '', actionId: took[0]!.entry.id, ...(refused.size ? { refused: pushes.filter((p) => refused.has(p.push!.ref)).map((p) => ({ actionId: p.entry.id, reason: `${p.push!.ref}: ${refused.get(p.push!.ref)}` })) } : {}), }; } /** A repository's refs a refresh will publish: the root's branches and tags, its HEAD, and the World's refs as they * stood when the refresh read them. */ type StagedMirror = { m: DerivedManifest; name: string; theirs: Map; head: string | null; held: Map; heldHead: string }; /** REFRESH a repository's code, read: the root's advertisement and the objects of its branches and tags the World's * repository lacks (immutable: kept as they arrive). Its refs are staged, published by `publishMirror` once every read of * the refresh succeeded. */ async function readMirror(m: DerivedManifest, execute: RemoteExecute, root: string | undefined, name: string, remote: string): Promise { const { store, refs } = gitRepositoryOf(m, name, root); const transport = gitTransport(execute, remote); const advertised = await lsRemote(transport, 'git-upload-pack'); const theirs = new Map([...advertised.refs].filter(([ref]) => mirrored(ref))); const held = new Map(refs.list().map((r) => [r.name, r.sha])); const wants: string[] = []; for (const sha of new Set(theirs.values())) if (!(await store.has(sha))) wants.push(sha); await fetchPack(transport, store, wants, [...new Set(held.values())]); return { m, name, theirs, head: advertised.head, held, heldHead: refs.head() }; } const mirrored = (ref: string): boolean => ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/'); /** REFRESH a repository's code, published: by compare-and-set under the repository's ref lock, the lock receive-pack * holds. A ref takes the root's value, or is deleted when the root holds it no more, only while it still holds what the * refresh read and no offered push names it (read inside the lock); HEAD follows the root's only while unchanged. */ function publishMirror(service: string, root: string | undefined, staged: StagedMirror): void { const { refs } = gitRepositoryOf(staged.m, staged.name, root); refs.withLock(() => { const waiting = new Set(settlingEntries(service, root).offered.map(pushInputOf).filter((p): p is PushInput => p?.name === staged.name).map((p) => p.ref)); const untouched = (ref: string): boolean => !waiting.has(ref) && (refs.get(ref) ?? undefined) === staged.held.get(ref); for (const [ref, sha] of staged.theirs) if (untouched(ref)) refs.set(ref, sha); for (const ref of staged.held.keys()) if (mirrored(ref) && !staged.theirs.has(ref) && untouched(ref)) refs.delete(ref); if (staged.head?.startsWith('refs/heads/') && refs.head() === staged.heldHead) refs.setHead(staged.head); }); } /** Path parameters that name a subject by a field rather than its id, sent as the vendor's value of that field, read * from the adopted landed copy ("Perform", step 1): a parent found by `parent.where` (a repository addressed as * `{owner}/{repo}`), and a subject named by the number it counts per parent (`number`, an issue's `issue_number`). * A subject the vendor has not given another id keeps the World's values, which are then the vendor's. */ function vendorFieldParams(m: DerivedManifest, resource: string, params: Record, ctx: PerformContext): void { const decl = m.resources[resource]; if (!decl || (!decl.number && !decl.parent?.where)) return; const tree = readTree(ctx.service!, ctx.root) as Row[]; const landed = readParentTreeMap(ctx.service!, ctx.root); const vendorCopy = (type: string, local: Row | undefined): Row | undefined => { if (!local) return undefined; const id = ctx.resolve(type, String(local.id)); return id === String(local.id) ? undefined : (landed.get(`${type}:${id}`)?.fields as Row | undefined); }; const fill = (template: string): string => template.replace(/\{([^}]+)\}/g, (_, n: string) => params[n] ?? ''); // the parent as the World stores it, read before any parameter becomes the vendor's const parent = decl.parent; const parentType = parent ? storedType(m, parent.resource) : undefined; const where = Object.entries(parent?.where ?? {}).map(([field, template]) => [field, template, fill(template)] as const); const localParent = where.length ? tree.find((r) => r.type === parentType && where.every(([f, , v]) => String(at(r, f)) === v)) : undefined; const parentId = parent ? (where.length ? (localParent ? String(localParent.id) : undefined) : parent.params ? fill(parent.value ?? parent.params.map((p) => `{${p}}`).join('/')) : parent.param !== undefined ? params[parent.param] : undefined) : undefined; if (decl.number && !decl.key) { const type = storedType(m, resource); const name = Object.keys(params).at(-1); const field = decl.number.field; const local = name === undefined ? undefined : tree.find((r) => r.type === type && String(r[field]) === params[name] && (!parent || String(r[parent.field]) === parentId)); const copy = vendorCopy(type, local); if (name !== undefined && copy?.[field] !== undefined) params[name] = String(copy[field]); } const parentCopy = vendorCopy(parentType ?? '', localParent); if (parentCopy) for (const [field, template] of where) { const one = /^\{([^}]+)\}$/.exec(template); const value = at(parentCopy, field); if (one && value !== undefined) params[one[1]!] = String(value); } } /** The items of a list's answer: under the operation's key, else the answer when it is a list. */ /** The items a scope names: a list, or one item where XML names a lone child (an S3 list of one object), or none. */ const listed = (v: unknown): unknown[] => (Array.isArray(v) ? v : v === undefined || v === null || v === '' ? [] : [v]); function itemsOf(op: DerivedOperation, parsed: unknown): Row[] { const v = op.answers?.key ? at(parsed, op.answers.key) : parsed; const list = Array.isArray(v) ? v : Array.isArray(at(parsed, 'data')) ? (at(parsed, 'data') as unknown[]) : Array.isArray(at(parsed, 'results')) ? (at(parsed, 'results') as unknown[]) : []; return list.map(object).filter((x): x is Row => x !== undefined); } /** The values at a dot path's keys: `*` any one key (an object map's values or an array's items), a list stepped into, * a key that holds dots matched whole, the longest first (an OpenTelemetry attribute's `user.email`). A path that * reaches nothing, or null, yields none. A vendor response's download links (an object map or an array) and a * pseudonymizer's declared fields (ADR 0036) are read by it. */ export function valuesAt(value: unknown, keys: readonly string[]): unknown[] { return placesAt(value, keys).map((p) => p.value); } /** The places `valuesAt` reads, each its value and a setter that writes a new value there (the root's setter, where the * path is empty, writes nothing): a pseudonymizer changes a record's declared fields in place through it. */ export function placesAt(value: unknown, keys: readonly string[], set: (next: unknown) => void = () => {}): Array<{ value: unknown; set(next: unknown): void }> { if (!keys.length) return value === undefined || value === null ? [] : [{ value, set }]; if (!value || typeof value !== 'object') return []; const row = value as Row; const into = (key: string, rest: readonly string[]) => placesAt(row[key], rest, (next) => { row[key] = next; }); const [key, ...rest] = keys; if (key === '*') return Object.keys(value).flatMap((k) => into(k, rest)); if (Array.isArray(value) && !/^\d+$/.test(key!)) return value.flatMap((v, i) => placesAt(v, keys, (next) => { value[i] = next; })); for (let n = keys.length; n >= 1; n--) { const joined = keys.slice(0, n).join('.'); if (Object.hasOwn(value, joined)) return into(joined, keys.slice(n)); } return []; } /** A refresh's query as the pairs it sends: a list value once per value, in order, as a query repeats a name (Sentry's * stats `groupBy=outcome&groupBy=reason`), each filled by `fill`. */ function queryPairs(query: Record, fill: (template: string) => string = (t) => t): Array<[string, string]> { return Object.entries(query).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((x): [string, string] => [k, fill(x)])); } /** The field a refresh scope's answer names its subject by, where it differs from the resource's (`refresh.idAs`: the * Hub's repo read carries the creation's ObjectId as `_id` and its own `namespace/name` as `id`). */ function scopeIdOf(scope: object, fields: Record): string | undefined { const field = (scope as { idAs?: string }).idAs; if (field?.includes('{')) return field.replace(/\{([^}]+)\}/g, (_, name: string) => { const value = at(fields, name); if (value === undefined || value === null || value === '') throw new Error(`refresh identity lacks ${name}; nothing folded`); return String(value); }); const value = field ? at(fields, field) : undefined; return value === undefined || value === null || value === '' ? undefined : String(value); } /** A refresh larger than one window of the vendor's rate budget paces itself: a call the budget refuses before making * it (RateBudgetError) waits the time the refusal names, at most two minutes a wait, and is made then. The budget is * never exceeded and no vendor answer is retried; without it a refresh needing more than one window never finishes * (Slack's, after a deploy spent the window: every rerun refused again from the start). */ function paced(execute: RemoteExecute): RemoteExecute { return async (request) => { for (let waits = 0; ; waits++) { try { return await execute(request); } catch (error) { const wait = (error as { name?: string; retryAfterMs?: number }).name === 'RateBudgetError' ? (error as { retryAfterMs: number }).retryAfterMs : undefined; if (wait === undefined || wait > 120_000 || waits >= 60) throw error; await new Promise((done) => setTimeout(done, wait + 250)); } } }; } /** The values a scoped read's pattern captures from a root's scope, or null when it does not match: each `{name}` one * segment. */ function scopeCaptures(vendor: string, pattern: string, scope: string): Record | null { const want = pattern.split('/').filter(Boolean), have = scope.split('/').filter(Boolean); if (want.length !== have.length) return null; const captured: Record = {}; for (const [i, part] of want.entries()) { const name = /^\{([^}]+)\}$/.exec(part)?.[1]; if (name) { try { captured[name] = decodeURIComponent(have[i]!); } catch { throw new Error(`${vendor}: the root's scope ${JSON.stringify(scope)} has a malformed segment ${JSON.stringify(have[i])}; nothing folded`); } } else if (part !== have[i]) return null; } return captured; } /** An item and every item nested under it at `field`, however deep. */ function nested(item: Row, field: string): Row[] { return [item, ...listed(item[field]).map((x) => object(x)).filter((x): x is Row => x !== undefined).flatMap((x) => nested(x, field))]; } function refreshOf(units: Unit[], service: string): NonNullable { return async (unpaced, opts) => { const execute = paced(unpaced); const observed: ObservedResource[] = []; const complete: Completed[] = []; // what the root's credential may not read (a token scoped to some of the account): left as the World holds it, said const unread: Array<{ type: string; path: string; status: number }> = []; let answered = 0; for (const { manifest: m, surface, lane } of units) { const onLane = lane ? { lane } : {}; const tenantBinding: Record = {}; if (m.refreshIdentity) { const identity = surface.operations.find(operation => operation.id === m.refreshIdentity!.operation); if (!m.tenant || !identity || identity.method !== 'get' || identity.path.includes('{')) throw new Error(`${m.vendor}: refresh identity needs a parameterless GET and declared tenant field`); const answer = await execute({ method: 'GET', path: `${identity.basePath ?? surface.basePath ?? ''}${identity.path}`, ...onLane, headers: fixedHeaders(identity) }); if (answer.status >= 400 || refusedIn(m, parse(answer))) throw new Error(`${m.vendor}: root account identity refused; nothing folded`); const tenant = at(parse(answer), m.refreshIdentity.field); if (typeof tenant !== 'string' || !tenant) throw new Error(`${m.vendor}: root account identity is absent; nothing folded`); tenantBinding[m.tenant.field] = tenant; } // parents before children, however deep // a root scoped to one of the vendor's things reads each resource with a matching scoped read by it (`scopedRefresh`) const windowed = new Map }>(); if (opts.scope) for (const [resource, decl] of Object.entries(m.resources)) for (const read of decl.scopedRefresh ?? []) { const captured = scopeCaptures(m.vendor, read.scope, opts.scope); if (captured && !windowed.has(resource)) windowed.set(resource, { read, captured }); } const scoped = Object.entries(m.resources).filter(([r, d]) => !windowed.has(r) && d.refresh && !('none' in d.refresh)); const depth = (r: string, seen = new Set()): number => { const p = m.resources[r]?.parent?.resource; return p && !seen.has(p) ? 1 + depth(p, seen.add(r)) : 0; }; // the scoped reads after the rest, each after the resource its `each` names const pending = [...windowed.keys()]; const windows: string[] = []; while (pending.length) { const next = pending.findIndex((r) => !pending.some((o) => o === windowed.get(r)!.read.each?.from)); if (next < 0) throw new Error(`${m.vendor}: scoped refresh reads name each other in a cycle; nothing folded`); windows.push(...pending.splice(next, 1)); } const order = [...scoped.sort(([a], [b]) => depth(a) - depth(b)), ...windows.map((r): [string, ResourceDecl] => [r, m.resources[r]!])]; for (const [resource, decl] of order) { const window = windowed.get(resource); const scope = window?.read ?? decl.refresh!; if ('none' in scope) continue; if (m.refreshIdentity && (!('list' in scope) || 'graphql' in scope)) throw new Error(`${m.vendor}: account-bound refresh requires REST list scopes`); if ('graphql' in scope && scope.graphql) { await refreshGraphql(m, resource, decl, scope, execute, opts.scope, observed, complete); answered += 1; continue; } const opId = 'list' in scope ? scope.list : 'get' in scope ? scope.get : ''; const op = surface.operations.find((o) => o.id === opId); if (!op) throw new Error(`${m.vendor}: ${resource}'s refresh names ${opId}, no operation of the surface`); const type = storedType(m, resource); // the known, read one by one: a vendor that lists no whole type (Volter Identity's people and organizations) is // read back subject by subject: each the vendor is known to hold (the parent tree: landed or observed, never a // World-only subject, which a 404 would wrongly remove), by the vendor's id, its other path parameters filled // from its own fields; a 404 is one the vendor no longer has, and only the subjects read are whole if ('get' in scope && scope.known && !window) { const aliases = aliasesFrom(parentEntries(service, opts.root)); const held = [...readParentTreeMap(service, opts.root)].filter(([, r]) => r.type === type && r.fields.deleted !== true); // and each a door made (a person's act on the vendor's site: a group they add the bot to), which the vendor holds // as the World does though no deploy landed it const rooted = new Set(held.map(([k]) => k)); const doorMade = new Set(wholeLog(service, opts.root).filter((e) => e.subject.type === type && (e.input as Row | undefined)?.door !== undefined).map((e) => String(e.subject.id))); for (const r of readTree(service, opts.root) as Row[]) { const key = `${type}:${String(r.id)}`; if (r.type !== type || r.deleted === true || !doorMade.has(String(r.id)) || held.some(([k]) => k === key)) continue; const { type: _t, id, ...fields } = r; held.push([key, { type, id: String(id), fields } as (typeof held)[number][1]]); } const read: string[] = []; // a 403 leaves the type as the World holds it, never complete let refused = false; for (const [key, r] of held) { const subject = { ...r.fields, id: r.id } as Row; const vendorId = aliases.get(key) ?? String(r.id); for (const [name, template] of Object.entries(scope.params ?? {})) subject[name] = template.replace(/\{([^}]+)\}/g, (_, field: string) => { if (field === 'id') return vendorId; if (subject[field] === undefined || subject[field] === null) throw new Error(`${m.vendor}: ${resource}'s refresh parameter ${name} lacks ${field}; nothing folded`); return String(subject[field]); }); // each path parameter is the subject's own field of that name (the Hub's {namespace} and {repo}); one the subject // holds no field for, or `id`, is the vendor's id for it const path = `${op.basePath ?? surface.basePath ?? ''}${op.path}`.replace(/\{([^}]+)\}/g, (_, n: string) => encodeURIComponent(String(n === 'id' || subject[n] === undefined || subject[n] === null ? vendorId : subject[n]))); // a read naming its subject in the query (an RPC method: Telegram's getChat?chat_id=): the scope's `query`, each // `{name}` filled as a path parameter is const fillSubject = (t: string): string => t.replace(/\{([^}]+)\}/g, (_, n: string) => String(n === 'id' || subject[n] === undefined || subject[n] === null ? vendorId : subject[n])); const asked = queryPairs(scope.query ?? {}, fillSubject); const target = marked(op, path); const sent = asked.length ? `${target}${target.includes('?') ? '&' : '?'}${new URLSearchParams(asked)}` : target; const answer = await execute({ method: op.method.toUpperCase(), path: sentTo(m, sent, subject), ...onLane, headers: fixedHeaders(op) }); // a door's subject the vendor does not show the root (another bot's private chat) stays as the World holds it if (answer.status === 401) throw new Error(`401: the vendor refused the root's credential (${op.method.toUpperCase()} ${path}); nothing folded`); if (!rooted.has(key) && answer.status >= 400 && answer.status !== 429) continue; if (answer.status === 403) { unread.push({ type, path, status: 403 }); refused = true; break; } if (answer.status === 429) throw new Error(`429: rate limited${answer.headers['retry-after'] ? `, retry after ${answer.headers['retry-after']}s` : ''}`); read.push(String(subject.id)); answered += 1; // the vendor's answer for a subject it no longer has: a 404, or the scope's `gone` (Telegram's 400 `chat not found`) if (answer.status === 404 || (scope.gone && answer.status === scope.gone.status && refusalWords(m, parse(answer)).includes(scope.gone.says))) continue; if (answer.status >= 400 || refusedIn(m, parse(answer))) throw new Error(`${m.vendor}: ${resource} refresh ${op.id} (${op.method.toUpperCase()} ${op.path}): ${answer.status}: ${refusalWords(m, parse(answer))}`); const parsed = parse(answer); let full: Row; if (op.answers?.list) { const items = itemsOf(op, parsed); const matching = items.find((item) => (scopeIdOf(scope, item) ?? storedIdOf(decl, item)) === vendorId); if (!matching && items.length) throw new Error(`${m.vendor}: ${resource} refresh ${op.id} omitted the requested subject; nothing folded`); if (!matching) continue; full = matching; } else full = object(op.answers?.key ? at(parsed, op.answers.key) : parsed) ?? {}; const local = (m as { worldFields?: Record> }).worldFields?.[resource] ?? {}; const fields = Object.fromEntries(Object.entries(full).filter(([k]) => !(k in local))); if (decl.parent) { if (r.fields[decl.parent.field] !== undefined) fields[decl.parent.field] = r.fields[decl.parent.field]; Object.assign(fields, keptFields(m, resource, decl.parent.keep, fillSubject)); } // the subject asked for, where its answer names no id of its own (a singleton under its account) const id = scopeIdOf(scope, fields) ?? storedIdOf(decl, fields) ?? String(r.id); observed.push({ type, id, fields: fields as ObservedResource['fields'] }); } if (!refused) complete.push({ type, ids: read }); continue; } // each parent observed: the path parameters it fills and the value the child's parent field holds (its id, or for // a parent the path names by several parameters, `parent.value` filled from them as the twin stores it) // a scoped read's bindings stand where a parent's parameters do: the scope's captures, with each value its `each` // finds among another resource's observations of this refresh const eachFrom = window?.read.each ? storedType(m, window.read.each.from) : undefined; const parents = window ? (window.read.each ? [...new Set(observed.filter((o) => o.type === eachFrom).map((o) => at(o.fields as Row, window.read.each!.path)).filter((v) => v !== undefined && v !== null && v !== '').map(String))] .map((v) => ({ value: undefined as string | undefined, params: { ...window.captured, [window.read.each!.as]: v } })) : [{ value: undefined as string | undefined, params: window.captured }]) // a windowed read of a parented resource keeps the parent its bindings name .map((b) => ({ ...b, value: decl.parent ? parentValueOf(decl.parent, b.params) : undefined })) : decl.parent ? parentsOf(decl.parent, observed.filter((o) => o.type === storedType(m, decl.parent!.resource))) : [undefined]; // a scoped read is a window, never the whole type let whole = !window && 'list' in scope && scope.complete !== false; for (const under of parents) for (const variant of scope.variants ?? [{ headers: {} }]) { const parent = under?.value; // the list's own headers, `{name}` its parent's parameter, and the variant's const filled = (t: string): string => t.replace(/\{([^}]+)\}/g, (_, n: string) => under?.params[n] ?? ''); const listHeaders = { ...Object.fromEntries(Object.entries(scope.headers ?? {}).map(([n, t]) => [n, filled(t)])), ...variant.headers }; // a list asked by POST (an RPC list) carries its page in its body, as the operation's encoding sends it const rpc = op.method.toLowerCase() !== 'get'; const unpaginated = 'list' in scope && scope.unpaginated === true; const limit = !unpaginated && m.list?.limit && [...(op.query ?? []), ...(rpc ? op.body ?? [] : [])].some((q) => q.name === m.list!.limit.param) ? { [m.list.limit.param]: String(m.list.limit.max) } : {}; // a scoped read's query names its bindings; one it lacks is refused, never sent empty const bound = (t: string): string => t.replace(/\{([^}]+)\}/g, (_, n: string) => { const v = under?.params[n]; if (v === undefined || v === '') throw new Error(`${m.vendor}: ${resource}'s scoped refresh query names {${n}}, which its scope does not bind; nothing folded`); return v; }); let page: Record = { ...(window ? Object.fromEntries(Object.entries(scope.query ?? {}).map(([k, t]) => [k, Array.isArray(t) ? t.map(bound) : bound(t)])) : scope.query), ...limit }; const seenLinks = new Set(); for (let taken = 0; ;) { let unfilled = false; const path = `${op.basePath ?? surface.basePath ?? ''}${op.path}`.replace(/\{([^}]+)\}/g, (_, n: string) => { const v = under?.params[n] ?? ''; if (!v) unfilled = true; return encodeURIComponent(v); }); // a parent the operation names in its query, not its path (Slack's conversations.history `channel`) // and a parent named by several parameters, each the path does not take that the operation declares in its query // (Slack's reactions.get: a message's `channel` and `timestamp`) const byQuery = decl.parent?.param && parent !== undefined && !op.path.includes(`{${decl.parent.param}}`) ? { [decl.parent.param]: String(parent) } : decl.parent?.params?.length && under ? Object.fromEntries(Object.entries(under.params).filter(([n]) => !op.path.includes(`{${n}}`) && (op.query ?? []).some((x) => x.name === n))) : {}; // a list asked by POST carries its parent in its body too, unless the operation reads it from its query const parentInQuery = !rpc || (op.query ?? []).some((x) => x.name === decl.parent?.param); // a parameter the operation declares in its query, and not its body, goes in the query of a list asked by POST // too (TikTok's video list: `fields` in the query, its cursor in the body) const inQuery = (n: string): boolean => (op.query ?? []).some((x) => x.name === n) && !(op.body ?? []).some((b) => b.name === n); const q = new URLSearchParams(queryPairs(rpc ? { ...Object.fromEntries(Object.entries(page).filter(([k]) => inQuery(k))), ...(parentInQuery ? byQuery : {}) } : { ...page, ...byQuery })); // Fixed parameters and cursors take the operation's body types, not their manifest string encoding. const typedPage = Object.fromEntries(Object.entries(page).filter(([k]) => !rpc || !inQuery(k)).map(([k, v]) => { if (Array.isArray(v)) return [k, v]; const type = (op.body ?? []).find((b) => b.name === k)?.type; const value = type === 'integer' ? exactInteger(v) : type === 'number' ? Number(v) : type === 'boolean' && (v === 'true' || v === 'false') ? v === 'true' : v; return [k, value]; })); const sent = rpc ? encode(op, { ...typedPage, ...(parentInQuery ? {} : byQuery) }) : undefined; const answer = await execute({ method: op.method.toUpperCase(), path: sentTo(m, marked(op, [...q].length ? `${path}?${q}` : path), under?.params ?? {}), ...onLane, headers: { ...fixedHeaders(op), ...listHeaders, ...(sent?.type ? { 'content-type': sent.type } : {}) }, ...(sent?.body !== undefined ? { body: sent.body } : {}), }); if (answer.status === 401) throw new Error(`401: the vendor refused the root's credential (${op.method.toUpperCase()} ${path}); nothing folded`); if (answer.status === 403) { unread.push({ type, path, status: 403 }); whole = false; break; } if (answer.status === 429) throw new Error(`429: rate limited${answer.headers['retry-after'] ? `, retry after ${answer.headers['retry-after']}s` : ''}`); // one subject read by its parent and not there (an account with no workers.dev subdomain): nothing to observe. A // path missing a parameter (an empty segment) is the kernel's mistake, never the vendor's absence if ('get' in scope && answer.status === 404 && !unfilled) { answered += 1; break; } if (answer.status >= 400 || refusedIn(m, parse(answer))) throw new Error(`${m.vendor}: ${resource} refresh ${op.id} (${op.method.toUpperCase()} ${op.path}): ${answer.status}: ${refusalWords(m, parse(answer))}`); answered += 1; const parsed = parse(answer); const shape = 'list' in scope ? scope.shape : undefined; const items = 'get' in scope ? [object(op.answers?.key ? at(parsed, op.answers.key) : parsed) ?? {}] : 'items' in scope && scope.items ? listed(at(parsed, scope.items)).map((x) => object(x)).filter((x): x is Row => x !== undefined) : itemsOf(op, parsed); const keyed = 'list' in scope && scope.keyed === true; const map = keyed ? object(at(parsed, scope.items ?? '$body')) : undefined; if (keyed && (!map || Object.values(map).some((value) => (shape?.value ? object(value) !== undefined : !object(value))))) throw new Error(`${m.vendor}: ${resource}'s keyed refresh must return an object of ${shape?.value ? 'scalars' : 'resource objects'}; nothing folded`); // the answer's items as subjects' fields (refresh.shape): a scalar item or map value named, a nested array spread let entries: Array<[string | undefined, Row]> = keyed ? Object.entries(map!).map(([key, value]): [string | undefined, Row] => (shape?.value ? [shape.keyAs ? undefined : key, { [shape.value]: value, ...(shape.keyAs ? { [shape.keyAs]: key } : {}) }] : [key, object(value)!])) : shape?.scalar && 'items' in scope && scope.items ? listed(at(parsed, scope.items)).filter((x) => x !== null && typeof x !== 'object').map((x): [undefined, Row] => [undefined, { [shape.scalar!]: x }]) : items.map((item) => [undefined, item]); // paging reads the answer's own items, before any spread const pageItems = entries; if (shape?.recurse) entries = entries.flatMap(([key, item]) => nested(item, shape.recurse!).map((x, i): [string | undefined, Row] => [i ? undefined : key, x])); if (shape?.spread) { const { path: inner, as, carry } = shape.spread; entries = entries.flatMap(([, item]) => { const carried = Object.fromEntries(Object.entries(carry ?? {}).map(([f, p]) => [f, at(item, p)])); return listed(at(item, inner)).flatMap((el): Array<[undefined, Row]> => { const own = object(el) ?? (as && el !== null && el !== undefined ? { [as]: el } : undefined); return own ? [[undefined, { ...carried, ...own }]] : []; }); }); } for (const [mapId, item] of entries) { let full = item; if ('list' in scope && scope.detail) { const detail = surface.operations.find((o) => o.id === scope.detail); if (!detail) throw new Error(`${m.vendor}: ${resource}'s refresh detail names ${scope.detail}, no operation of the surface`); const id = mapId ?? storedIdOf(decl, { ...under?.params, ...item }); // the item's own id names it in the detail's path where its stored id is a composite key (a Cloudflare // script stored `/` is read at `/scripts/{script_name}` by its name) const own = item[decl.idAs ?? 'id']; // a detail parameter the scope maps from the row's fields and the bindings (`detailParams`); a row lacking one // is not read const mapped = Object.fromEntries(Object.entries(scope.detailParams ?? {}).map(([n, t]) => [n, t.replace(/\{([^}]+)\}/g, (_, f: string) => String(under?.params[f] ?? item[f] ?? ''))])); if (Object.values(mapped).some((v) => v === '')) continue; const path = `${detail.basePath ?? surface.basePath ?? ''}${detail.path}`.replace(/\{([^}]+)\}/g, (_, n: string) => { const value = mapped[n] ?? under?.params[n] ?? item[n] ?? (decl.key && (typeof own === 'string' || typeof own === 'number') ? own : id); if (value === undefined) throw new Error(`${m.vendor}: ${resource}'s refresh detail has no value for ${n}`); return encodeURIComponent(String(value)); }); // the subject a detail read names in its body or query (`detailWith`: AWS JSON's DescribeSecret, `{ SecretId }`) const withValues = Object.fromEntries(Object.entries(scope.detailWith ?? {}).map(([k, t]) => [k, t.replace(/\{([^}]+)\}/g, (_, n: string) => String(n === 'id' ? id : item[n] ?? ''))])); const detailRpc = detail.method.toLowerCase() !== 'get'; const detailQuery = { ...(scope.query ?? {}), ...(detailRpc ? {} : withValues) }; const detailSent = detailRpc && Object.keys(withValues).length ? encode(detail, withValues) : undefined; const answer = await execute({ method: detail.method.toUpperCase(), path: sentTo(m, marked(detail, Object.keys(detailQuery).length ? `${path}?${new URLSearchParams(queryPairs(detailQuery))}` : path), { ...item, ...under?.params }), ...onLane, headers: { ...fixedHeaders(detail), ...(detailSent?.type ? { 'content-type': detailSent.type } : {}) }, ...(detailSent?.body !== undefined ? { body: detailSent.body } : {}) }); if (answer.status >= 400 || refusedIn(m, parse(answer))) throw new Error(`${m.vendor}: ${resource} refresh detail ${detail.id} (${detail.method.toUpperCase()} ${detail.path}): ${answer.status}: ${refusalWords(m, parse(answer)) || 'the vendor refused the refresh detail; nothing folded'}`); const detailBody = parse(answer); const detailKey = scope.detailMerge ?? detail.answers?.key; const fragment = object(detailKey ? at(detailBody, detailKey) : detailBody); if (scope.detailMerge && !fragment) throw new Error(`${m.vendor}: ${resource}'s refresh detail fragment is not an object; nothing folded`); const detailFields = fragment ?? {}; full = scope.detailMerge ? { ...item, ...detailFields } : detailFields; } // the vendor's shape alone: a World field the twin discloses (manifest.worldFields: Substrate's // twin_local_ports) is the answering World's, never the vendor's, and is not folded in const local = (m as { worldFields?: Record> }).worldFields?.[resource] ?? {}; const vendorShape = Object.fromEntries(Object.entries(full).filter(([k]) => !(k in local))); // what a child keeps (`parent.keep`), private: its parent's parameters, a scoped read's bindings, else the row's // own fields; in a window a value nothing holds is refused const kept = keptFields(m, resource, decl.parent?.keep, (t) => t.replace(/\{([^}]+)\}/g, (_, n: string) => { const v = under?.params[n] ?? vendorShape[n]; if (window && (v === undefined || v === null || v === '')) throw new Error(`${m.vendor}: ${resource}'s parent.keep names {${n}}, which neither its scope nor the row holds; nothing folded`); return v === undefined || v === null ? '' : String(v); })); const fields = { ...vendorShape, ...(!decl.shared ? tenantBinding : {}), ...kept, ...(decl.parent && parent !== undefined ? { [decl.parent.field]: parent } : {}) }; // a key part the item does not carry is the path parameter its parent was listed under (Cloudflare's secret, // `{account_id}/{script_name}::{name}`, listed as its name and type alone), or a scoped read's binding const id = mapId ?? scopeIdOf(scope, window ? { ...under?.params, ...fields } : fields) ?? storedIdOf(decl, { ...under?.params, ...fields }); if (id === undefined) continue; observed.push({ type, id, fields: fields as ObservedResource['fields'] }); } taken += pageItems.length; if ('get' in scope || unpaginated) break; if (taken >= 10_000) { whole = false; break; } if ('nextLink' in scope && scope.nextLink) { const nextLink = scope.nextLink; const header = Object.entries(answer.headers).find(([name]) => name.toLowerCase() === nextLink.header.toLowerCase())?.[1]; const links = header ? linkRelations(header).filter((link) => link.params.rel?.split(/\s+/).includes(nextLink.rel)) : []; if (links.length > 1) throw new Error(`${m.vendor}: ambiguous refresh Link relation; nothing folded`); const link = links[0]; if (!link || Object.entries(nextLink.when ?? {}).some(([name, value]) => link.params[name.toLowerCase()] !== value)) break; let marker: string | null; try { marker = new URL(link.url).searchParams.get(nextLink.query); } catch { throw new Error(`${m.vendor}: refresh Link continuation is not an absolute URL; nothing folded`); } if (!marker) throw new Error(`${m.vendor}: refresh Link URL lacks its declared cursor; nothing folded`); const param = scope.cursor ?? nextLink.query; if (page[param] === marker || seenLinks.has(marker)) throw new Error(`${m.vendor}: ${resource}'s list repeated its continuation; nothing folded`); seenLinks.add(marker); page = { ...page, [param]: marker }; continue; } // the next page by the manifest's list model. The list is whole only where its end shows: a cursor model // gives no next cursor (a short page may still name one), or a page is empty or shorter than the limit // asked; a list the twin cannot page on, or whose page size it does not know, is not known whole. // the cursor the scope names (AWS's NextToken), sent back as its parameter if ('next' in scope && scope.next) { // the vendor's own flag that no page follows ends it, whatever cursor the page names if ('more' in scope && scope.more !== undefined && !['true', true].includes(at(parsed, scope.more) as string | boolean)) break; const markers = typeof scope.next === 'string' ? { [scope.cursor ?? scope.next]: scope.next } : scope.next; const next = Object.fromEntries(Object.entries(markers).flatMap(([param, where]) => { const marker = at(parsed, where); return marker === undefined || marker === null || marker === '' ? [] : [[param, String(marker)]]; })); if (!Object.keys(next).length) break; // a page that names the cursor it was asked with would be read forever: nothing folds if (Object.entries(next).every(([k, v]) => page[k] === v)) throw new Error(`${m.vendor}: ${resource}'s list repeated its continuation; nothing folded`); page = { ...page, ...next }; continue; } if (m.list?.cursor) { const next = at(parsed, 'next_cursor') ?? at(parsed, 'response_metadata.next_cursor'); if (!next) break; page = { ...page, [m.list.cursor.param]: String(next) }; continue; } const size = Number(limit[m.list?.limit.param ?? ''] ?? 0); if (!pageItems.length || (size && pageItems.length < size)) break; if (!size) { whole = false; break; } const last = pageItems.at(-1)![0] ?? pageItems.at(-1)![1][decl.idAs ?? 'id']; if (m.list?.after) page = { ...page, [m.list.after]: String(last) }; else if (m.list?.page) page = { ...page, [m.list.page.param]: String(Number(page[m.list.page.param] ?? 1) + 1) }; else if (m.list?.offset) page = { ...page, [m.list.offset.param]: String(taken) }; else { whole = false; break; } } } // a type under a parent is whole only for the parents observed: what it held under another parent stands. A root // scoped to one resource (`RootConfig.scope`, GitHub's `repos/o/r`) lists only what is under it, so a type with no // parent is never the account's whole list there if (whole && !decl.parent && !opts.scope) complete.push(m.refreshIdentity && m.tenant && !decl.shared ? { type, field: m.tenant.field, within: [String(tenantBinding[m.tenant.field])] } : type); else if (whole && parents.length && decl.parent) complete.push({ type, field: decl.parent.field, within: parents.flatMap((p) => (p?.value === undefined ? [] : [p.value])) }); } } // every read refused is a credential the vendor refuses, never an account that holds nothing if (unread.length && !answered) throw new Error(`403: the vendor refused the root's credential for every read (${unread.map((u) => u.path).join(', ')}); nothing folded`); const downloads: Array<{ key: string; bytes: Uint8Array }> = []; for (const { manifest: m, surface, lane } of units) for (const [resource, decl] of Object.entries(m.resources)) { const scope = decl.refresh; if (!scope || 'none' in scope || !scope.blobs?.length) continue; for (const row of observed.filter((o) => o.type === storedType(m, resource))) for (const blob of scope.blobs) { // the bytes an operation of the unit answers for the subject (R2's GetObject: its list names no download link) if ('operation' in blob) { if (!blob.field.startsWith('_') || (blob.headersField !== undefined && !blob.headersField.startsWith('_'))) throw new Error(`${m.vendor}: ${resource}'s refresh blob fields must be private`); const op = surface.operations.find((o) => o.id === blob.operation); if (!op || op.method.toUpperCase() !== 'GET') throw new Error(`${m.vendor}: ${resource}'s refresh blob names ${blob.operation}, no GET of the surface`); const under = decl.parent ? parentsOf(decl.parent, observed.filter((o) => o.type === storedType(m, decl.parent!.resource))).find((p) => p.value === row.fields[decl.parent!.field]) : undefined; const values: Row = { ...row.fields, ...under?.params, id: row.id }; const path = `${op.basePath ?? surface.basePath ?? ''}${op.path}`.replace(/\{([^}]+)\}/g, (_, n: string) => { if (values[n] === undefined || values[n] === null) throw new Error(`${m.vendor}: ${resource}'s refresh blob has no value for ${n}`); return encodeURIComponent(String(values[n])); }); const answer = await execute({ method: 'GET', path: sentTo(m, marked(op, path), values), ...(lane ? { lane } : {}), headers: { ...fixedHeaders(op), ...blob.headers }, responseType: 'bytes' }); if (answer.status < 200 || answer.status >= 300 || !answer.bodyBytes) throw new Error(`${m.vendor}: refresh blob ${blob.operation} answered ${answer.status}; nothing folded`); const key = `refresh/${encodeURIComponent(row.type)}/${encodeURIComponent(row.id)}`; // only the headers the scope names: the answer's own (its date, its length) would change every read const keptHeaders = Object.fromEntries(Object.entries(answer.headers).filter(([h]) => (blob.keepHeaders ?? []).some((n) => (n.endsWith('*') ? h.toLowerCase().startsWith(n.slice(0, -1).toLowerCase()) : h.toLowerCase() === n.toLowerCase()))).map(([h, v]) => [h.toLowerCase(), v])); row.fields = { ...row.fields, [blob.field]: key, ...(blob.headersField ? { [blob.headersField]: keptHeaders } : {}) } as ObservedResource['fields']; downloads.push({ key, bytes: answer.bodyBytes }); continue; } for (const value of valuesAt(row.fields, blob.path.split('.'))) { if (typeof value !== 'string') throw new Error(`${m.vendor}: refresh blob ${blob.path} is not a URL`); let url = new URL(value); const boundUrl = readRoot(service, opts.root)?.url; const bound = boundUrl ? new URL(boundUrl) : undefined; const prefix = bound?.pathname.replace(/\/+$/, '') ?? ''; const primary = m.origin?.placeholder ? new URL(m.origin.placeholder).hostname : m.descriptor?.hosts?.find((h) => 'host' in h && !h.exclude); const primaryHost = typeof primary === 'string' ? primary : primary && 'host' in primary ? primary.host : undefined; let answer: RemoteExecuteResponse | undefined; let pathname = ''; for (let hops = 0; hops <= 5; hops++) { const fromRoot = !!bound && url.origin === bound.origin && (url.pathname === prefix || url.pathname.startsWith(prefix + '/')); pathname = fromRoot ? url.pathname.slice(prefix.length) || '/' : url.pathname; if (url.username || url.password || (!fromRoot && (url.protocol !== 'https:' || (url.port && url.port !== '443'))) || (!fromRoot && !m.descriptor?.hosts?.some((h) => 'host' in h && !h.exclude && h.host === url.hostname && (!h.pathPattern || new RegExp(h.pathPattern).test(url.pathname))))) throw new Error(`${m.vendor}: refresh blob host is not declared: ${url.hostname}`); answer = await execute({ method: 'GET', path: fromRoot || url.hostname === primaryHost ? pathname + url.search : url.href, headers: { host: url.host }, responseType: 'bytes' }); if (![301, 302, 303, 307, 308].includes(answer.status)) break; if (hops === 5 || !answer.headers.location) throw new Error(`${m.vendor}: invalid refresh blob redirect; nothing folded`); url = new URL(answer.headers.location, url); } if (!answer || answer.status < 200 || answer.status >= 300 || !answer.bodyBytes) throw new Error(`${m.vendor}: refresh blob ${blob.path} answered ${answer?.status}; nothing folded`); const fill = (template: string, key = ''): string => template.replace(/\{pathname\}/g, decodeURIComponent(pathname)).replace(/\{key\}/g, key).replace(/\{header:([^}]+)\}/g, (_, name: string) => { const value = answer!.headers[name.toLowerCase()]; if (value === undefined) throw new Error(`${m.vendor}: refresh blob header ${name} is missing; nothing folded`); return value; }); const key = fill(blob.key); if (!key || key.startsWith('/') || key.includes('\0') || key.split(/[\\/]/).includes('..') || /\{[^}]+\}/.test(key)) throw new Error(`${m.vendor}: invalid refresh blob key`); if (blob.resource) { if (!blob.resource.startsWith('_') || !m.resources[blob.resource]) throw new Error(`${m.vendor}: refresh blob metadata requires a declared bookkeeping resource`); observed.push({ type: storedType(m, blob.resource), id: key, fields: Object.fromEntries(Object.entries(blob.fields ?? {}).map(([name, template]) => [name, fill(template, key)])) }); } downloads.push({ key, bytes: answer.bodyBytes }); } } } // the code of each repository observed, read over git; its refs are published with the blobs, once every read succeeded const mirrors: StagedMirror[] = []; for (const { manifest: m } of units) { if (!m.git) continue; const { resource, remote } = m.git.repository; for (const row of observed.filter((o) => o.type === storedType(m, resource) && o.deleted !== true)) { mirrors.push(await readMirror(m, execute, opts.root, gitNameOf(m, row.id, opts.root), fillTemplate(remote, { ...row.fields, id: row.id }))); } } for (const download of downloads) await writeResourceBlob(service, download.key, download.bytes, opts.root); for (const staged of mirrors) publishMirror(service, opts.root, staged); adopt(service, opts.root, units, observed); const report = observeResources(service, observed, { ...(opts.root !== undefined ? { root: opts.root } : {}), complete }); return unread.length ? { ...(report as object), unread } : report; }; } /** A declared GraphQL read over the same executor and atomic observation batch as REST. */ async function refreshGraphql(m: DerivedManifest, resource: string, decl: ResourceDecl, scope: Exclude, { none: string }>, execute: RemoteExecute, rootScope: string | undefined, observed: ObservedResource[], complete: Completed[]): Promise { const gql = scope.graphql!; const endpoint = m.graphql?.paths[0]; if (!endpoint) throw new Error(`${m.vendor}: a GraphQL refresh needs a GraphQL endpoint`); const type = storedType(m, resource); const parents = decl.parent ? parentsOf(decl.parent, observed.filter((o) => o.type === storedType(m, decl.parent!.resource))) : [undefined]; let whole = 'list' in scope && scope.complete !== false; for (const under of parents) { const substitute = (v: unknown): unknown => typeof v === 'string' && /^\{[^}]+\}$/.test(v) ? under?.params[v.slice(1, -1)] ?? v : Array.isArray(v) ? v.map(substitute) : object(v) ? Object.fromEntries(Object.entries(object(v)!).map(([k, x]) => [k, substitute(x)])) : v; const variables = substitute(gql.variables ?? {}) as Row; const cursors = new Set(); for (let taken = 0; ;) { const answer = await execute({ method: 'POST', path: endpoint, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: gql.query, variables }) }); const parsed = parse(answer); if (answer.status >= 400 || (Array.isArray(at(parsed, 'errors')) && (at(parsed, 'errors') as unknown[]).length)) throw new Error(`${answer.status}: the vendor refused the GraphQL refresh; nothing folded: ${JSON.stringify(parsed)}`); const value = at(parsed, gql.items); if (value === undefined) throw new Error(`${m.vendor}: the GraphQL refresh returned no ${gql.items}; nothing folded`); const items = listed(value).map(object).filter((x): x is Row => x !== undefined); for (const item of items) { const fields = { ...item, ...(decl.parent && under ? { [decl.parent.field]: under.value } : {}) }; const id = storedIdOf(decl, { ...under?.params, ...fields }); if (id !== undefined) observed.push({ type, id, fields: fields as ObservedResource['fields'] }); } taken += items.length; if ('get' in scope || ('list' in scope && scope.unpaginated)) break; if (!gql.pageInfo) { whole = false; break; } const info = object(at(parsed, gql.pageInfo)); if (!info || typeof info.hasNextPage !== 'boolean') throw new Error(`${m.vendor}: missing GraphQL page information; nothing folded`); if (!info.hasNextPage) break; if (taken >= 10_000) { whole = false; break; } const cursor = info.endCursor; if (typeof cursor !== 'string' || !cursor || cursors.has(cursor)) throw new Error(`${m.vendor}: invalid GraphQL continuation; nothing folded`); cursors.add(cursor); variables[gql.cursor ?? 'after'] = cursor; } } if (whole && !decl.parent && !rootScope) complete.push(type); else if (whole && parents.length && decl.parent) complete.push({ type, field: decl.parent.field, within: parents.flatMap((p) => (p?.value === undefined ? [] : [p.value])) }); } /** Fields a refresh writes beside the vendor's (a child's `parent.keep`): each private, never a vendor field a World * value would overwrite, its template filled by `fill`. */ function keptFields(m: DerivedManifest, resource: string, keep: Record | undefined, fill: (template: string) => string): Row { return Object.fromEntries(Object.entries(keep ?? {}).map(([field, template]) => { if (!field.startsWith('_')) throw new Error(`${m.vendor}: ${resource}'s parent.keep names ${field}, which is not private; nothing folded`); return [field, fill(template)]; })); } /** A parent's value from the parameters that name it: its `value` template, its several `params` joined, or its one id. */ function parentValueOf(parent: NonNullable, params: Record): string | undefined { if (!parent.params?.length) return parent.param ? params[parent.param] : undefined; if (!parent.params.every((n) => params[n] !== undefined)) return undefined; return (parent.value ?? parent.params.map((n) => `{${n}}`).join('/')).replace(/\{([^}]+)\}/g, (_, n: string) => params[n] ?? ''); } /** The parents a child type is listed under, from the parent type's observations: the path parameters each fills and * the value the child's `parent.field` holds. A single `param` is the parent's id. A parent the path names by several * parameters (`params`, GitHub's `{owner}/{repo}`) reads each from the parent's fields through its `where` templates * (`full_name: '{owner}/{repo}'`), and the child holds `value` filled from them (the parameters joined by `/` when it * names none), as the derived core stores it ("Refresh"). A parent whose fields fill not every parameter is skipped. */ function parentsOf(parent: NonNullable, observations: ObservedResource[]): Array<{ params: Record; value: string }> { const out = new Map; value: string }>(); for (const o of observations) { if (!parent.params?.length) { out.set(o.id, { params: parent.param ? { [parent.param]: o.id } : {}, value: o.id }); continue; } const params: Record = {}; for (const [field, template] of Object.entries(parent.where ?? {})) { const names: string[] = []; // a template that is one parameter whole takes the field whole, its slashes included (an S3 key) const whole = /^\{([^}]+)\}$/.exec(template); if (whole) { const v = at(o.fields, field); if (v !== undefined && v !== null && v !== '') params[whole[1]!] = String(v); continue; } const pattern = template.replace(/\{([^}]+)\}|[.*+?^$()|[\]\\]/g, (m, n?: string) => (n ? (names.push(n), '([^/]+)') : `\\${m}`)); const got = new RegExp(`^${pattern}$`).exec(String(at(o.fields, field) ?? '')); if (got) names.forEach((n, i) => { params[n] = got[i + 1]!; }); } const value = parentValueOf(parent, params); if (value === undefined) continue; out.set(value, { params, value }); } return [...out.values()]; } /** A vendor's subject's stored id: its key template filled from its fields (its parent's among them), else its id * field. Undefined when the subject names none. */ function storedIdOf(decl: ResourceDecl, fields: Row): string | undefined { if (decl.key) { let missing = false; const id = decl.key.replace(/\{([^}]+)\}/g, (_, n: string) => { const v = fields[n]; if (typeof v !== 'string' && typeof v !== 'number') missing = true; return String(v ?? ''); }); return missing ? undefined : id; } const id = fields[decl.idAs ?? 'id']; return typeof id === 'string' || typeof id === 'number' ? String(id) : undefined; } /** Adoption ("Refresh"): an observation whose vendor id the World holds under no subject, matching a subject a deploy * settled with no vendor id (the same type and parent, and equal on the resource's `alternateKeys`, else the only * such subject under that parent), is that subject: it lands as its alias instead of a second subject beside it. */ function adopt(service: string, root: string | undefined, units: Unit[], observed: ObservedResource[]): void { const entries = parentEntries(service, root); const aliases = aliasesFrom(entries); const tree = readParentTreeMap(service, root); const pending = new Map }>>(); for (const e of entries) { if (e.receipt?.status !== 'deployed' || e.receipt.externalId || e.landsId === undefined || e.aliasOf !== undefined) continue; const key = `${e.subject.type}:${e.subject.id}`; const held = tree.get(key); if (aliases.has(key) || !held || held.fields.deleted === true) continue; const list = pending.get(e.subject.type) ?? []; if (!list.some((p) => p.id === e.subject.id)) list.push({ id: e.subject.id, fields: held.fields }); pending.set(e.subject.type, list); } // the account a root is ("The account a root is"): the root's credential reaches one account of the type the pack's // paths name it by; observed alone, it is the World's own account (made by the World's door, so no deploy settled it) for (const u of units) { if (!u.manifest.account) continue; const type = storedType(u.manifest, u.manifest.account); const seen = observed.filter((o) => o.type === type); if (seen.length !== 1 || tree.has(`${type}:${seen[0]!.id}`)) continue; const local = (readTree(service, root) as Row[]).find((r) => r.type === type && r.deleted !== true && !aliases.has(`${type}:${String(r.id)}`) && String(r.id) !== seen[0]!.id); if (local) { seen[0]!.adopts = String(local.id); aliases.set(`${type}:${String(local.id)}`, seen[0]!.id); } } if (!pending.size) return; const declOf = (type: string): { m: DerivedManifest; decl: ResourceDecl } | undefined => { for (const u of units) { const hit = Object.entries(u.manifest.resources).find(([r]) => storedType(u.manifest, r) === type); if (hit) return { m: u.manifest, decl: hit[1] }; } return undefined; }; for (const o of observed) { const pool = pending.get(o.type); if (!pool?.length || tree.has(`${o.type}:${o.id}`)) continue; const { m, decl } = declOf(o.type) ?? {}; const parentField = decl?.parent?.field; // a local child names its parent by the parent's local id, which the parent's adoption aliased to the vendor's const parentType = decl?.parent && m ? storedType(m, decl.parent.resource) : undefined; const resolved = (v: unknown): string => aliases.get(`${parentType}:${String(v)}`) ?? String(v); const siblings = pool.filter((p) => parentField === undefined || resolved(p.fields[parentField]) === String(o.fields[parentField])); const keys = decl?.adoptBy ?? decl?.alternateKeys ?? []; const match = keys.length ? siblings.filter((p) => keys.every((k) => p.fields[k] !== undefined && p.fields[k] === o.fields[k])) : siblings.length === 1 ? siblings : []; if (match.length !== 1) continue; o.adopts = match[0]!.id; pool.splice(pool.indexOf(match[0]!), 1); // its children, observed after it, name it by the local id this adoption aliases aliases.set(`${o.type}:${o.adopts}`, o.id); } } /** The event's resource: the declared `types`, else the manifest's events read backwards, else `.created|updated|deleted`. */ function eventResource(m: DerivedManifest, decl: IngestDecl, type: string): NonNullable[string] | undefined { if (decl.types?.[type]) return decl.types[type]; for (const [operation, sent] of Object.entries(m.events?.types ?? {})) { if ((Array.isArray(sent) ? sent : [sent]).includes(type)) { const r = resourceOf(m, operation.split('.')[0]); if (r) return { resource: r, ...(/\.delete/.test(operation) ? { deleted: true as const } : {}) }; } } const pattern = /^(.+)\.(created|updated|deleted)$/.exec(type); const r = pattern ? resourceOf(m, pattern[1]) : undefined; return r ? { resource: r, ...(pattern![2] === 'deleted' ? { deleted: true as const } : {}) } : undefined; } /** A version older than the held one: numbers as numbers ("9" before "10"), timestamps as instants, else as text. */ function older(theirs: unknown, held: unknown): boolean { if (theirs === undefined || theirs === null || held === undefined || held === null) return false; const a = Number(theirs); const b = Number(held); if (/^-?\d+$/.test(String(theirs)) && /^-?\d+$/.test(String(held))) return compareExactNumbers(theirs, held) < 0; if (String(theirs).trim() !== '' && String(held).trim() !== '' && Number.isFinite(a) && Number.isFinite(b)) return a < b; const ta = Date.parse(String(theirs)); const tb = Date.parse(String(held)); if (Number.isFinite(ta) && Number.isFinite(tb)) return ta < tb; return String(theirs) < String(held); } function ingestOf(units: Unit[], decl: IngestDecl, service: string): NonNullable { return async (request, ctx) => { const body = await request.text(); const headers = Object.fromEntries(request.headers); const now = Math.floor(clockForm.machineNow() / 1000); const schemes = (Array.isArray(decl.scheme) ? decl.scheme : [decl.scheme]) as EventScheme[]; if (!ctx.secret || !schemes.some((s) => verifyEvent(s, ctx.secret!, body, headers, { now, tolerance: 300 }))) return Response.json({ error: 'invalid signature' }, { status: 401 }); let event: unknown; try { event = parseExactJson(body); } catch { return Response.json({ error: 'the event is not JSON' }, { status: 400 }); } if (decl.handshake && Object.entries(decl.handshake.when).every(([k, v]) => at(event, k) === v)) { const answer = decl.handshake.answer.startsWith('$body.') ? at(event, decl.handshake.answer) : decl.handshake.answer; return new Response(typeof answer === 'string' ? answer : JSON.stringify(answer), { status: 200 }); } const named = [decl.type.header ? request.headers.get(decl.type.header) : decl.type.body ? at(event, decl.type.body) : undefined, decl.type.action ? at(event, decl.type.action) : undefined].filter((x) => typeof x === 'string' && x !== ''); const type = named.join('.'); for (const { manifest: m } of units) { const found = eventResource(m, decl, type); if (!found) continue; const d = m.resources[found.resource]!; // the object where its type carries it, with its parent's value where the event names the parent beside it const carried = object(at(event, found.object ?? decl.object)); const parent = found.parent && d.parent ? at(event, found.parent) : undefined; const withParent = carried && (typeof parent === 'string' || typeof parent === 'number') ? { ...carried, [d.parent!.field]: String(parent) } : carried; // the subject's id where the type names it (kept out of the fields: the vendor's object carries no such field), and // what the type itself says of the subject const named = found.id && withParent ? at(withParent, found.id) : undefined; const item = withParent ? { ...(found.id && !found.id.includes('.') ? Object.fromEntries(Object.entries(withParent).filter(([k]) => k !== found.id)) : withParent), ...(found.fields ?? {}) } : undefined; const id = found.id ? (typeof named === 'string' || typeof named === 'number' ? String(named) : undefined) : item ? storedIdOf(d, item) : undefined; if (!item || id === undefined) break; const stored = storedType(m, found.resource); // an event older than the root's copy folds nothing const held = d.version ? (readTree(service, ctx.root) as Row[]).find((r) => r.type === stored && r.id === String(id)) : undefined; if (held && d.version && older(item[d.version], held[d.version])) break; observeResources(service, [{ type: stored, id: String(id), fields: item as ObservedResource['fields'], ...(found.deleted ? { deleted: true } : {}) }], ctx.root !== undefined ? { root: ctx.root } : {}); break; } return Response.json({ received: true }); }; } function adaptersOf(units: Unit[], service: string, ingest: IngestDecl | undefined): StateSystemAdapters { return { perform: performOf(units), refresh: refreshOf(units, service), ...(ingest ? { ingest: ingestOf(units, ingest, service) } : {}) }; } /** A derived pack's adapters, from its manifest and its generated surface. */ export function deriveStateSystem(manifest: DerivedManifest, surface: DerivedSurface, lanes: Record = {}): StateSystemAdapters { // a pack with an API of its own and lanes beside it (Clerk's Backend API and its Frontend API, `fapi`): one state // system over its surface and each lane's const units = [{ manifest, surface }, ...Object.entries(lanes).map(([lane, u]) => ({ ...u, lane }))]; return adaptersOf(units, manifest.service, manifest.ingest ?? units.find((u) => u.manifest.ingest)?.manifest.ingest); } /** A vendor of lanes' adapters: one state system over every lane's surface (the lanes keep the vendor's one store). */ export function deriveVendorStateSystem(vendor: VendorManifest, lanes: Record): StateSystemAdapters { const units = Object.entries(lanes).map(([lane, u]) => ({ ...u, lane })); const service = units[0]?.manifest.service ?? vendor.vendor; return adaptersOf(units, service, vendor.ingest ?? units.find((u) => u.manifest.ingest)?.manifest.ingest); }