Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions clients/typescript/holder-function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { RegistryError } from './core.ts'

const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u
const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u
const maximumRequestBytes = 32_768
const bodyTooLarge = Symbol('body too large')

interface HolderSubmission<Preparation extends object> {
recordId: string
ifMatch: string
preparation: Preparation
}

interface HolderCommand<Input extends object> {
recordId: string
ifMatch: string
idempotencyKey: string
input: Input
signal: AbortSignal
}

/** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */
interface HolderActionBinding<Preparation extends object, Input extends object> {
path: string
parseSubmission: (body: unknown) => HolderSubmission<Preparation> | undefined
parsePreparation: (body: unknown) => Input | undefined
invoke: (credential: string, command: HolderCommand<Input>) => Promise<{ recordId: string }>
}

function reply(body: object, status: number): Response {
return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } })
}

function parseJson(source: string): unknown {
const value: unknown = JSON.parse(source, (_key, member: unknown) => {
if (typeof member === 'number' &&
(!Number.isFinite(member) || Number.isInteger(member) && !Number.isSafeInteger(member))) {
throw new SyntaxError('Unsupported JSON number.')
}
return member
})
// On valid JSON, a quoted token followed by a colon is an object key.
// Decode the key before comparing so Unicode escapes cannot hide duplicates.
const objects: Set<string>[] = []
for (const [token, quoted, colon] of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}]/gu)) {
if (token === '{') objects.push(new Set())
if (token === '}') objects.pop()
if (quoted && colon) {
const keys = objects.at(-1)!
const key: string = JSON.parse(quoted)
if (keys.has(key)) throw new SyntaxError('Duplicate JSON member.')
keys.add(key)
}
}
return value
}

async function readSubmission(request: Request): Promise<unknown> {
if (!request.body) return undefined
const reader = request.body.getReader()
const decoder = new TextDecoder('utf-8', { fatal: true })
let bytes = 0
let body = ''
try {
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
bytes += chunk.value.byteLength
if (bytes > maximumRequestBytes) {
await reader.cancel()
return bodyTooLarge
}
body += decoder.decode(chunk.value, { stream: true })
}
return parseJson(body + decoder.decode())
} finally {
reader.releaseLock()
}
}

/** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */
export function createHolderActionHandler<Preparation extends object, Input extends object>(
{ path, parseSubmission, parsePreparation, invoke }: HolderActionBinding<Preparation, Input>,
prepare: (input: Preparation) => unknown | Promise<unknown>,
): (request: Request) => Promise<Response> {
if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.')

return async request => {
const url = new URL(request.url)
if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) {
return reply({ message: 'Unknown function route.' }, 404)
}
const credential = /^Bearer ([A-Za-z0-9._-]+)$/u.exec(request.headers.get('authorization') ?? '')?.[1]
if (!credential) return reply({ message: 'Sign in to continue.' }, 401)

const idempotencyKey = request.headers.get('idempotency-key')
const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()
if (!idempotencyKey || !uuid.test(idempotencyKey.toLowerCase()) || mediaType !== 'application/json') {
return reply({ message: 'Send a JSON request with its attempt key.' }, 400)
}
let submission: HolderSubmission<Preparation> | undefined
try {
const body = await readSubmission(request)
if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413)
if (body !== undefined) submission = parseSubmission(body)
} catch {
return reply({ message: 'Send a valid JSON request.' }, 400)
}
if (!submission || !uuid.test(submission.recordId) || !strongTag.test(submission.ifMatch)) {
return reply({ message: 'Send a record and its reviewed condition.' }, 400)
}
const { recordId, ifMatch, preparation } = submission

let input: Input | undefined
try {
request.signal.throwIfAborted()
input = parsePreparation(await prepare(preparation))
} catch {
return reply({ message: 'The function could not prepare the request.' }, 502)
}
if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502)

try {
const result = await invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal })
if (result.recordId === recordId) return reply({ recordId }, 200)
} catch (error) {
if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown &&
error.status !== undefined && error.status >= 400 && error.status < 500) {
return reply({ message: 'BReg refused the request.' }, error.status)
}
}
return reply({ message: 'The Action outcome is unavailable. Retry the same attempt.' }, 502)
}
}
Loading