@requence/service 0.8.2-edge.1159 → 0.8.2-edge.1162
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -729
- package/build/index.js +255 -67
- package/build/index.js.map +11 -6
- package/build/types/helpers/src/protocol/command.d.ts +36 -0
- package/build/types/helpers/src/protocol/command.d.ts.map +1 -1
- package/build/types/helpers/src/protocol/taskOptions.d.ts +3 -0
- package/build/types/helpers/src/protocol/taskOptions.d.ts.map +1 -1
- package/build/types/service/src/createAmqpConnection.d.ts +0 -1
- package/build/types/service/src/createAmqpConnection.d.ts.map +1 -1
- package/build/types/service/src/helpers.d.ts +20 -1
- package/build/types/service/src/helpers.d.ts.map +1 -1
- package/build/types/service/src/index.d.ts +2 -0
- package/build/types/service/src/index.d.ts.map +1 -1
- package/build/types/service/src/store.d.ts +104 -0
- package/build/types/service/src/store.d.ts.map +1 -0
- package/package.json +2 -1
package/build/index.js.map
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../node_modules/.bun/dlv@1.1.3/node_modules/dlv/dist/dlv.js", "../src/index.ts", "../../helpers/src/utils/guards.ts", "../../helpers/src/utils/mapData.ts", "../../helpers/src/utils/fileObject.ts", "../../helpers/src/utils/streamObject.ts", "../../helpers/src/utils/claimCheckObject.ts", "../../helpers/src/utils/requenceCallback.ts", "../../helpers/src/utils/serviceRender.ts", "../../helpers/src/utils/surfaceHandler.ts", "../../helpers/src/utils/uiRebuild.ts", "../../helpers/src/utils/obj.ts", "../../helpers/src/utils/amqpHeartbeat.ts", "../src/createAmqpConnection.ts", "../../helpers/src/msgpack/index.ts", "../../files/src/errors.ts", "../../files/src/streamFraming.ts", "../../files/src/remoteBody.ts", "../../files/src/RequenceFile.ts", "../../files/src/RequenceStream.ts", "../../files/src/handlers/transport.ts", "../../files/src/handlers/fileHandler.ts", "../../files/src/withRequenceStreams.ts", "../../files/src/handlers/streamHandler.ts", "../../files/src/handlers/claimCheckHandler.ts", "../../files/src/sanitizeLogData.ts", "../../callbacks/src/handler.ts", "../../transformer/src/errors.ts", "../../transformer/src/guards.ts", "../../transformer/src/walk.ts", "../../transformer/src/transform.ts", "../src/surfaceHandler.ts", "../src/transformer.ts", "../src/boundary.ts", "../src/callbackGrowth.ts", "../src/durableCallback.ts", "../src/helpers.ts", "../src/uiWatch.ts", "../src/ui.ts", "../src/utils.ts"],
|
|
3
|
+
"sources": ["../../../node_modules/.bun/dlv@1.1.3/node_modules/dlv/dist/dlv.js", "../src/index.ts", "../../helpers/src/utils/guards.ts", "../../helpers/src/utils/mapData.ts", "../../helpers/src/utils/fileObject.ts", "../../helpers/src/utils/streamObject.ts", "../../helpers/src/utils/claimCheckObject.ts", "../../helpers/src/utils/requenceCallback.ts", "../../helpers/src/utils/serviceRender.ts", "../../helpers/src/utils/surfaceHandler.ts", "../../helpers/src/utils/uiRebuild.ts", "../../helpers/src/utils/obj.ts", "../../helpers/src/utils/amqpHeartbeat.ts", "../src/createAmqpConnection.ts", "../../helpers/src/msgpack/index.ts", "../../files/src/errors.ts", "../../files/src/streamFraming.ts", "../../files/src/remoteBody.ts", "../../files/src/RequenceFile.ts", "../../files/src/RequenceStream.ts", "../../files/src/handlers/transport.ts", "../../files/src/handlers/fileHandler.ts", "../../files/src/withRequenceStreams.ts", "../../files/src/handlers/streamHandler.ts", "../../files/src/handlers/claimCheckHandler.ts", "../../files/src/sanitizeLogData.ts", "../../callbacks/src/handler.ts", "../../transformer/src/errors.ts", "../../transformer/src/guards.ts", "../../transformer/src/walk.ts", "../../transformer/src/transform.ts", "../src/surfaceHandler.ts", "../src/transformer.ts", "../src/boundary.ts", "../src/callbackGrowth.ts", "../src/durableCallback.ts", "../src/helpers.ts", "../../store/src/address.ts", "../../store/src/capability.ts", "../../store/src/errors.ts", "../../store/src/client.ts", "../src/store.ts", "../src/uiWatch.ts", "../src/ui.ts", "../src/utils.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"module.exports=function(t,e,l,n,o){for(e=e.split?e.split(\".\"):e,n=0;n<e.length;n++)t=t?t[e[n]]:o;return t===o?l:t};\n//# sourceMappingURL=dlv.js.map\n",
|
|
6
|
-
"import fs from 'node:fs'\nimport type { ConnectionOptions as TlsConnectionOptions } from 'node:tls'\n\nimport { deobfuscate } from '@requence/helpers'\nimport logger from '@requence/logger/simple'\nimport type { AmqpConnectionManagerOptions } from 'amqp-connection-manager'\n\nimport createAmqpConnection, {\n type ConnectionApi,\n type ConnectionStateListener,\n type MessageHandler,\n connectionOptionsSchema,\n} from './createAmqpConnection.ts'\n\nexport { RequenceFile, RequenceStream } from '@requence/files'\nexport {\n createCallback,\n type RequenceCallback,\n type WrappedRequenceCallback,\n} from '@requence/helpers'\nexport {\n type Bindable,\n type ConfigurationOf,\n type DurableCallback,\n type DurableCallbackContext,\n type DurableCallbackHandle,\n type DurableCallbackHandler,\n createDurableCallback,\n} from './durableCallback.ts'\nexport * from './errors.ts'\n// Types only: the facade's components are declarations of a runtime the *host*\n// provides, so re-exporting them as values here would emit a runtime re-export\n// of bindings that do not exist. A component author reaches them through the\n// `@requence/service/surface-ui` subpath instead — see `surfaceUi.ts`.\nexport type {\n ButtonProps,\n CheckboxProps,\n SelectOption,\n SelectProps,\n StackProps,\n SurfaceSpace,\n TextFieldProps,\n TextProps,\n} from './surfaceUi.ts'\nexport * from './ui.ts'\nexport * from './utils.ts'\n\nexport {\n type ConnectionState,\n type ConnectionStateListener,\n MessageHandler,\n} from './createAmqpConnection.ts'\n// Undocumented — privileged consumers (the reserved requence-logic runtime)\n// cast their handler context to this; see helpers.ts.\nexport type { PrivilegedContext, PrivilegedSends } from './helpers.ts'\nexport type ServiceApi<\n V extends keyof RequenceService.Version | (string & {}),\n> = ConnectionApi<V>\n\ninterface ServiceOptions<V extends string> {\n accessToken?: string\n devToken?: string\n version: V\n /**\n * Optional, author-chosen label announced in the AMQP client properties and\n * shown in the Requence UI next to the online count — \"which of my three\n * deployments is this?\".\n *\n * A DEBUGGING LABEL, not an identifier: it is not unique, nothing keys off\n * it, and no behaviour depends on it. Capped at 64 characters (longer labels\n * are truncated, never rejected).\n */\n name?: string\n prefetch?: number\n connectionTimeout?: number\n /** heartbeat interval in seconds — defaults to 30 */\n heartbeatInterval?: number\n silent?: boolean\n connectionOptions?: AmqpConnectionManagerOptions['connectionOptions']\n /** Max serialized body size in bytes before a PayloadTooLargeError is thrown. */\n maxMessageSize?: number\n // Undocumented (privileged consumers): skip file/stream/callback\n // rehydration on ingress; claim-checks still resolve. See helpers.ts.\n passthroughByteReferences?: boolean\n /**\n * Notified whenever the underlying AMQP connection is lost or (re)established.\n * amqp-connection-manager auto-reconnects, so this is the only observable\n * signal of a mid-life outage — use it to drive liveness/health reporting.\n */\n onConnectionStateChange?: ConnectionStateListener\n}\n\n// TLS connection options overridable via the environment. These are a\n// fallback only: a value supplied in code through `connectionOptions` always\n// wins (see resolveConnectionOptions). `CA` carries inline PEM, `CA_FILE` a\n// path to a PEM file (inline wins when both are set); `REJECT_UNAUTHORIZED`\n// disables certificate verification when falsy (\"false\"/\"0\"/\"no\").\nfunction resolveConnectionOptions(\n connectionOptions: AmqpConnectionManagerOptions['connectionOptions'],\n): AmqpConnectionManagerOptions['connectionOptions'] {\n const rejectEnv = process.env.REJECT_UNAUTHORIZED\n const caEnv = process.env.CA\n const caFileEnv = process.env.CA_FILE\n\n const tlsDefaults: TlsConnectionOptions = {}\n if (rejectEnv !== undefined) {\n tlsDefaults.rejectUnauthorized = !/^(false|0|no)$/i.test(rejectEnv.trim())\n }\n if (caEnv) {\n tlsDefaults.ca = caEnv\n } else if (caFileEnv) {\n tlsDefaults.ca = fs.readFileSync(caFileEnv)\n }\n\n if (Object.keys(tlsDefaults).length === 0) {\n return connectionOptions\n }\n\n // Env defaults first, code-supplied options last → code overrides env.\n return { ...tlsDefaults, ...connectionOptions }\n}\n\nlet pkgJson: any | null\nfunction loadPkgJson() {\n if (!pkgJson) {\n pkgJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'))\n }\n return pkgJson\n}\n\n// The dev-token warning is about the process, not about one version: a worker\n// serving several versions would otherwise repeat it once per createService().\nlet didWarnDevToken = false\n\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(version: V, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(options: ServiceOptions<V>, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(\n optionsOrVersion: ServiceOptions<V> | string,\n optionalMessageHandler?: MessageHandler<V>,\n) {\n let options: ServiceOptions<V>\n let messageHandler: MessageHandler<V>\n if (typeof optionsOrVersion === 'string') {\n options = {\n version: optionsOrVersion as V,\n }\n messageHandler = optionalMessageHandler as MessageHandler<V>\n } else {\n options = optionsOrVersion\n messageHandler = optionalMessageHandler as MessageHandler<V>\n }\n\n let token =\n options.accessToken ??\n process.env.REQUENCE_SERVICE_ACCESS_TOKEN ??\n process.env.REQUENCE_ACCESS_TOKEN\n\n if (!token) {\n try {\n const pkgJson = loadPkgJson()\n token =\n pkgJson.requence?.service?.accessToken ?? pkgJson.requence?.accessToken\n } catch {\n //\n }\n }\n\n let devToken =\n options.devToken ??\n process.env.REQUENCE_SERVICE_DEV_TOKEN ??\n process.env.REQUENCE_DEV_TOKEN\n\n if (!devToken) {\n try {\n const pkgJson = loadPkgJson()\n devToken =\n pkgJson.requence?.service?.devToken ?? pkgJson.requence?.devToken\n } catch {\n //\n }\n }\n\n if (!token) {\n throw new Error('no access token provided')\n }\n\n const parts = deobfuscate(token)\n\n if (parts.length < 2 || parts[0] !== 'service') {\n throw new Error('invalid access token')\n }\n const url = parts[1]\n let devOverlay: string | undefined\n\n if (devToken) {\n const devParts = deobfuscate(devToken)\n if (devParts[0] !== 'api') {\n throw new Error(\n 'invalid dev token: please provide a personal access token',\n )\n }\n if (devParts[2] !== parts[2]) {\n throw new Error(\n 'invalid dev token: access token and dev token belong to different requence instances',\n )\n }\n devOverlay = devParts[1]\n\n // A dev token is not a mode this process announces anywhere else: it\n // quietly moves the worker off the deployed version's queue and onto a\n // personal overlay queue that the broker deletes once the process stops.\n // Deployed with one set, the service looks healthy and serves nothing.\n if (!didWarnDevToken) {\n didWarnDevToken = true\n logger.warn(\n 'Requence: started with a |dev token| — this worker consumes a personal dev-overlay queue instead of the deployed version, and that queue is deleted shortly after the process stops. Do not deploy with one: unset |REQUENCE_DEV_TOKEN| / |REQUENCE_SERVICE_DEV_TOKEN|, or remove |requence.devToken| from package.json.',\n )\n }\n }\n\n const envMaxMessageSize = process.env.REQUENCE_MAX_MESSAGE_SIZE\n ? Number(process.env.REQUENCE_MAX_MESSAGE_SIZE)\n : undefined\n\n return createAmqpConnection<V>(\n {\n // The schema strips unknown keys (and cannot carry a function), so the\n // listener is merged onto the parsed options rather than passed through it.\n ...connectionOptionsSchema.parse({\n ...options,\n connectionOptions: resolveConnectionOptions(options.connectionOptions),\n maxMessageSize: options.maxMessageSize ?? envMaxMessageSize,\n url,\n devOverlay,\n }),\n onConnectionStateChange: options.onConnectionStateChange,\n },\n messageHandler,\n )\n}\n",
|
|
6
|
+
"import fs from 'node:fs'\nimport type { ConnectionOptions as TlsConnectionOptions } from 'node:tls'\n\nimport { deobfuscate } from '@requence/helpers'\nimport logger from '@requence/logger/simple'\nimport type { AmqpConnectionManagerOptions } from 'amqp-connection-manager'\n\nimport createAmqpConnection, {\n type ConnectionApi,\n type ConnectionStateListener,\n type MessageHandler,\n connectionOptionsSchema,\n} from './createAmqpConnection.ts'\n\nexport { RequenceFile, RequenceStream } from '@requence/files'\n// The store's named errors, re-exported beside `RequenceFile` for the same\n// reason: they are raised inside a handler, and `@requence/store` is not a\n// package a service author can reach. A store call is an HTTP call and fails\n// like one — every refusal has a class, so a caller that wants to handle one\n// reads it off the class rather than off a status.\nexport {\n StoreAddressFullError,\n StoreError,\n StoreRequestError,\n StoreTaskNotAllowedError,\n StoreUnauthorizedError,\n StoreUnavailableError,\n StoreValueNotStorableError,\n StoreValueTooLargeError,\n type StoreBinding,\n} from '@requence/store'\nexport {\n createCallback,\n type RequenceCallback,\n type WrappedRequenceCallback,\n} from '@requence/helpers'\nexport {\n type Bindable,\n type ConfigurationOf,\n type DurableCallback,\n type DurableCallbackContext,\n type DurableCallbackHandle,\n type DurableCallbackHandler,\n createDurableCallback,\n} from './durableCallback.ts'\nexport * from './errors.ts'\n// Types only: the facade's components are declarations of a runtime the *host*\n// provides, so re-exporting them as values here would emit a runtime re-export\n// of bindings that do not exist. A component author reaches them through the\n// `@requence/service/surface-ui` subpath instead — see `surfaceUi.ts`.\nexport type {\n ButtonProps,\n CheckboxProps,\n SelectOption,\n SelectProps,\n StackProps,\n SurfaceSpace,\n TextFieldProps,\n TextProps,\n} from './surfaceUi.ts'\nexport type { RequenceStore, StoreSlot } from './store.ts'\nexport * from './ui.ts'\nexport * from './utils.ts'\n\nexport {\n type ConnectionState,\n type ConnectionStateListener,\n MessageHandler,\n} from './createAmqpConnection.ts'\n// Undocumented — privileged consumers (the reserved requence-logic runtime)\n// cast their handler context to this; see helpers.ts.\nexport type { PrivilegedContext, PrivilegedSends } from './helpers.ts'\nexport type ServiceApi<\n V extends keyof RequenceService.Version | (string & {}),\n> = ConnectionApi<V>\n\ninterface ServiceOptions<V extends string> {\n accessToken?: string\n devToken?: string\n version: V\n /**\n * Optional, author-chosen label announced in the AMQP client properties and\n * shown in the Requence UI next to the online count — \"which of my three\n * deployments is this?\".\n *\n * A DEBUGGING LABEL, not an identifier: it is not unique, nothing keys off\n * it, and no behaviour depends on it. Capped at 64 characters (longer labels\n * are truncated, never rejected).\n */\n name?: string\n prefetch?: number\n connectionTimeout?: number\n /** heartbeat interval in seconds — defaults to 30 */\n heartbeatInterval?: number\n silent?: boolean\n connectionOptions?: AmqpConnectionManagerOptions['connectionOptions']\n /** Max serialized body size in bytes before a PayloadTooLargeError is thrown. */\n maxMessageSize?: number\n // Undocumented (privileged consumers): skip file/stream/callback\n // rehydration on ingress; claim-checks still resolve. See helpers.ts.\n passthroughByteReferences?: boolean\n /**\n * Notified whenever the underlying AMQP connection is lost or (re)established.\n * amqp-connection-manager auto-reconnects, so this is the only observable\n * signal of a mid-life outage — use it to drive liveness/health reporting.\n */\n onConnectionStateChange?: ConnectionStateListener\n}\n\n// TLS connection options overridable via the environment. These are a\n// fallback only: a value supplied in code through `connectionOptions` always\n// wins (see resolveConnectionOptions). `CA` carries inline PEM, `CA_FILE` a\n// path to a PEM file (inline wins when both are set); `REJECT_UNAUTHORIZED`\n// disables certificate verification when falsy (\"false\"/\"0\"/\"no\").\nfunction resolveConnectionOptions(\n connectionOptions: AmqpConnectionManagerOptions['connectionOptions'],\n): AmqpConnectionManagerOptions['connectionOptions'] {\n const rejectEnv = process.env.REJECT_UNAUTHORIZED\n const caEnv = process.env.CA\n const caFileEnv = process.env.CA_FILE\n\n const tlsDefaults: TlsConnectionOptions = {}\n if (rejectEnv !== undefined) {\n tlsDefaults.rejectUnauthorized = !/^(false|0|no)$/i.test(rejectEnv.trim())\n }\n if (caEnv) {\n tlsDefaults.ca = caEnv\n } else if (caFileEnv) {\n tlsDefaults.ca = fs.readFileSync(caFileEnv)\n }\n\n if (Object.keys(tlsDefaults).length === 0) {\n return connectionOptions\n }\n\n // Env defaults first, code-supplied options last → code overrides env.\n return { ...tlsDefaults, ...connectionOptions }\n}\n\nlet pkgJson: any | null\nfunction loadPkgJson() {\n if (!pkgJson) {\n pkgJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'))\n }\n return pkgJson\n}\n\n// The dev-token warning is about the process, not about one version: a worker\n// serving several versions would otherwise repeat it once per createService().\nlet didWarnDevToken = false\n\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(version: V, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(options: ServiceOptions<V>, messageHandler: MessageHandler<V>): ServiceApi<V>\nexport function createService<\n V extends keyof RequenceService.Version | (string & {}),\n>(\n optionsOrVersion: ServiceOptions<V> | string,\n optionalMessageHandler?: MessageHandler<V>,\n) {\n let options: ServiceOptions<V>\n let messageHandler: MessageHandler<V>\n if (typeof optionsOrVersion === 'string') {\n options = {\n version: optionsOrVersion as V,\n }\n messageHandler = optionalMessageHandler as MessageHandler<V>\n } else {\n options = optionsOrVersion\n messageHandler = optionalMessageHandler as MessageHandler<V>\n }\n\n let token =\n options.accessToken ??\n process.env.REQUENCE_SERVICE_ACCESS_TOKEN ??\n process.env.REQUENCE_ACCESS_TOKEN\n\n if (!token) {\n try {\n const pkgJson = loadPkgJson()\n token =\n pkgJson.requence?.service?.accessToken ?? pkgJson.requence?.accessToken\n } catch {\n //\n }\n }\n\n let devToken =\n options.devToken ??\n process.env.REQUENCE_SERVICE_DEV_TOKEN ??\n process.env.REQUENCE_DEV_TOKEN\n\n if (!devToken) {\n try {\n const pkgJson = loadPkgJson()\n devToken =\n pkgJson.requence?.service?.devToken ?? pkgJson.requence?.devToken\n } catch {\n //\n }\n }\n\n if (!token) {\n throw new Error('no access token provided')\n }\n\n const parts = deobfuscate(token)\n\n if (parts.length < 2 || parts[0] !== 'service') {\n throw new Error('invalid access token')\n }\n const url = parts[1]\n let devOverlay: string | undefined\n\n if (devToken) {\n const devParts = deobfuscate(devToken)\n if (devParts[0] !== 'api') {\n throw new Error(\n 'invalid dev token: please provide a personal access token',\n )\n }\n if (devParts[2] !== parts[2]) {\n throw new Error(\n 'invalid dev token: access token and dev token belong to different requence instances',\n )\n }\n devOverlay = devParts[1]\n\n // A dev token is not a mode this process announces anywhere else: it\n // quietly moves the worker off the deployed version's queue and onto a\n // personal overlay queue that the broker deletes once the process stops.\n // Deployed with one set, the service looks healthy and serves nothing.\n if (!didWarnDevToken) {\n didWarnDevToken = true\n logger.warn(\n 'Requence: started with a |dev token| — this worker consumes a personal dev-overlay queue instead of the deployed version, and that queue is deleted shortly after the process stops. Do not deploy with one: unset |REQUENCE_DEV_TOKEN| / |REQUENCE_SERVICE_DEV_TOKEN|, or remove |requence.devToken| from package.json.',\n )\n }\n }\n\n const envMaxMessageSize = process.env.REQUENCE_MAX_MESSAGE_SIZE\n ? Number(process.env.REQUENCE_MAX_MESSAGE_SIZE)\n : undefined\n\n return createAmqpConnection<V>(\n {\n // The schema strips unknown keys (and cannot carry a function), so the\n // listener is merged onto the parsed options rather than passed through it.\n ...connectionOptionsSchema.parse({\n ...options,\n connectionOptions: resolveConnectionOptions(options.connectionOptions),\n maxMessageSize: options.maxMessageSize ?? envMaxMessageSize,\n url,\n devOverlay,\n }),\n onConnectionStateChange: options.onConnectionStateChange,\n },\n messageHandler,\n )\n}\n",
|
|
7
7
|
"import { z } from 'zod/v4'\n\nconst recordSchema = z.record(z.string(), z.unknown())\nexport function isRecord(data: unknown): data is Record<string, unknown> {\n return recordSchema.safeParse(data).success\n}\n\nconst uuidSchema = z.uuid()\nexport function isUuid(data: unknown): data is string {\n return uuidSchema.safeParse(data).success\n}\n",
|
|
8
8
|
"import { isRecord } from './guards.ts'\n\ntype DataVistor<T> = (\n data: T,\n path: Array<string | number>,\n) => Promise<any> | any\n\ninterface DataVistors {\n Null?: DataVistor<null>\n String?: DataVistor<string>\n Number?: DataVistor<number>\n Object?: DataVistor<object>\n Array?: DataVistor<Array<any>>\n Buffer?: DataVistor<Uint8Array>\n Function?: DataVistor<(...args: any[]) => any>\n Symbol?: DataVistor<symbol>\n}\n\ntype HasPromiseVistor<T extends DataVistors, Then, Else> = T[keyof T] extends (\n ...args: any[]\n) => any\n ? Promise<any> extends ReturnType<T[keyof T]>\n ? Then\n : Else\n : Else\n\nfunction resolve<T>(value: T | Promise<T>, onResolve: (value: T) => void) {\n if (value instanceof Promise) {\n return Promise.resolve()\n .then(() => value)\n .then(onResolve)\n }\n return onResolve(value)\n}\n\nfunction notUndefined(value: unknown, fallback: unknown) {\n return resolve(value, (resolvedValue) =>\n typeof resolvedValue === 'undefined' ? fallback : resolvedValue,\n )\n}\n\nclass AbortMapData extends Error {}\n\nexport function mapData<\n Output,\n Input = unknown,\n V extends DataVistors = DataVistors,\n>(\n data: Input,\n visitors: V,\n): HasPromiseVistor<\n V,\n Promise<unknown extends Output ? Input : Output>,\n unknown extends Output ? Input : Output\n> {\n let aborted = false\n const traverseData = (data: any, path: Array<string | number>): any => {\n if (aborted) {\n return data\n }\n try {\n if (Array.isArray(data)) {\n return resolve(visitors.Array?.(data, path), (resolvedData) => {\n if (resolvedData) {\n return resolvedData\n }\n const items = data.map((item, index) =>\n traverseData(item, [...path, index]),\n )\n if (items.some((item) => item instanceof Promise)) {\n return Promise.all(items)\n }\n\n return items\n })\n }\n if (data === null) {\n return notUndefined(visitors.Null?.(data, path), data)\n }\n const runtimeBuffer = (\n globalThis as { Buffer?: { isBuffer(obj: unknown): boolean } }\n ).Buffer\n if (runtimeBuffer?.isBuffer(data)) {\n return notUndefined(visitors.Buffer?.(data as Uint8Array, path), data)\n }\n if (typeof data === 'string') {\n return notUndefined(visitors.String?.(data, path), data)\n }\n if (typeof data === 'number') {\n return notUndefined(visitors.Number?.(data, path), data)\n }\n if (typeof data === 'symbol') {\n return notUndefined(visitors.Symbol?.(data, path), data)\n }\n if (typeof data === 'function') {\n return notUndefined(visitors.Function?.(data, path), data)\n }\n if (isRecord(data)) {\n return resolve(visitors.Object?.({ ...data }, path), (resolvedData) => {\n const nextData = resolvedData ?? data\n if (!isRecord(nextData)) {\n return nextData\n }\n const entries = Object.entries(nextData).map(([key, value]) => [\n key,\n traverseData(value, [...path, key]),\n ])\n\n if (entries.some(([, value]) => value instanceof Promise)) {\n return Promise.all(\n entries.map(([key, value]) =>\n Promise.resolve()\n .then(() => value)\n .then((resolvedValue) => [key, resolvedValue]),\n ),\n ).then((entries) => Object.fromEntries(entries))\n }\n\n return Object.fromEntries(entries)\n })\n }\n if (typeof data === 'object' && data) {\n return notUndefined(visitors.Object?.(data, path), data)\n }\n return data\n } catch (error) {\n if (error instanceof AbortMapData) {\n aborted = true\n return data\n }\n throw error\n }\n }\n\n return traverseData(data, [])\n}\n\nmapData.abort = () => {\n throw new AbortMapData()\n}\n",
|
|
9
9
|
"import { z } from 'zod/v4'\n\nconst fileObjectSchema = z.object({\n size: z.int().positive(),\n mime: z.string(),\n url: z.url(),\n __REQUENCE_type: z.literal('RequenceFile'),\n})\n\nexport type FileObject = z.infer<typeof fileObjectSchema>\n\nexport function toFileObject(fileInfo: {\n size: number\n mime: string\n url: string\n}): FileObject {\n return {\n ...fileInfo,\n __REQUENCE_type: 'RequenceFile',\n }\n}\n\nexport function isFileObject(data: unknown): data is FileObject {\n return fileObjectSchema.safeParse(data).success\n}\n",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"import { z } from 'zod/v4'\n\n/**\n * Marks a service message as a **dev-loop bundle swap** (#108) rather than a\n * result for one of the operator's dispatches.\n *\n * A rebuild changes which bytes the frame imports and nothing else — not the\n * props, not the handlers, not the node — so it is deliberately not a render. A\n * render would need the registering message to be unsettled and its registry\n * alive, which is what took the dev loop away from a deferred form: the handler\n * that drew it returned at the defer, so there is nothing left to re-render\n * through. A swap needs none of that, and so works identically for a live panel,\n * a deferred form, and a surface on a task that has already finished.\n *\n * Read on the same path as a result, and answered before it — like\n * `SURFACE_INTERACTION_ERROR_HEADER`, this message has no correlation id, no\n * index and no place in the ordered dispatch buffer, because it belongs to no\n * message of the operator's.\n */\nexport const UI_REBUILD_HEADER = 'uiRebuild'\n\n/**\n * What a rebuild says: *this component of this dev session is now these bytes*.\n *\n * `devSession` is opaque here and produced by the service SDK, which is the only\n * party that can: it is the one identity that survives the process being\n * restarted (a dev token plus the service version it is overlaying), so the\n * surfaces a session drew before a restart are still the same session's\n * afterwards. It deliberately carries no dev token in the clear — the token is\n * hashed into it — because it comes to rest in `task_surface`.\n *\n * `uiId` is the component's stable id (#103), which is what makes the swap\n * addressable at all: the hash is the thing that changed, so it cannot be the\n * thing looked up. A surface repoints when it belongs to this session AND shows\n * this component, whatever hash it is currently on — which is why a swap reaches\n * a surface that has sat through several rebuilds unseen.\n *\n * `source` always travels. The render payload's per-task dedup does not apply: a\n * swap is the first anyone has heard of this hash, and the surfaces it repoints\n * are precisely the ones that would otherwise be left naming a bundle nobody\n * stored.\n */\nexport const uiRebuildSchema = z.object({\n devSession: z.string(),\n uiId: z.string(),\n hash: z.string(),\n source: z.string(),\n})\n\nexport type UiRebuild = z.infer<typeof uiRebuildSchema>\n",
|
|
16
16
|
"import dlv from 'dlv'\nimport { dset } from 'dset'\n\nexport function setByPath<T extends Record<string, unknown>, U = T>(\n obj: T,\n keys: string | ArrayLike<string | number>,\n value: unknown,\n) {\n const clonedObj = structuredClone(obj)\n dset(clonedObj, keys, value)\n return clonedObj as unknown as U\n}\n\nexport const getByPath = dlv\n",
|
|
17
17
|
"// The negotiated AMQP heartbeat is the CLIENT's choice: the broker sets no\n// `heartbeat` in `deploy/swarm/rabbitmq/rabbitmq.conf`, so its own 60s default\n// is only a ceiling. `amqp-connection-manager` defaults to 5s, which makes any\n// event-loop stall longer than 10s (two missed intervals) fatal to every\n// connection in the deployment at once — that is what dropped eight connections\n// simultaneously in the 2026-07-30 incident.\n//\n// 30s tolerates ~60s of stall: longer than any GC/IO pause that does not already\n// mean the process is dead, short enough that a genuinely wedged client is still\n// reaped.\nexport const DEFAULT_AMQP_HEARTBEAT_SECONDS = 30\n\n// Sets the heartbeat as a URL query parameter, which is the one mechanism every\n// client understands: plain `amqplib` reads it during negotiation, and\n// `amqp-connection-manager` appends its own 5s default only when the param is\n// absent (`dist/cjs/AmqpConnectionManager.js`), so this wins there too.\n//\n// Non-destructive by design — an explicit `?heartbeat=` in the configured URL\n// always wins, and the input URL is never mutated.\nexport function withAmqpHeartbeat(url: URL): URL {\n const next = new URL(url.toString())\n if (!next.searchParams.has('heartbeat')) {\n next.searchParams.set('heartbeat', String(DEFAULT_AMQP_HEARTBEAT_SECONDS))\n }\n return next\n}\n",
|
|
18
|
-
"import { createHash } from 'node:crypto'\n\nimport type { CallbackIngressContext } from '@requence/callbacks'\nimport {\n type CallbackObject,\n DEFAULT_AMQP_HEARTBEAT_SECONDS,\n DEFAULT_SURFACE_ID,\n DURABLE_CALLBACK_QUEUE_ARGUMENTS,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n type MaybePromise,\n SURFACE_HANDLER_QUEUE_ARGUMENTS,\n SURFACE_HANDLER_TAG,\n SURFACE_INTERACTION_ERROR_HEADER,\n type SurfaceHandlerObject,\n UI_REBUILD_HEADER,\n type UiRebuild,\n deobfuscate,\n durableCallbackInvocationSchema,\n getByPath,\n obfuscate,\n serviceCallbackQueueName,\n serviceHandlerQueueName,\n surfaceHandlerInvocationSchema,\n} from '@requence/helpers'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport {\n decodeWireBody,\n encodeWireBody,\n wireCodecFromContentType,\n} from '@requence/helpers/msgpack'\nimport {\n CAPABILITY_HEADER_KEYS,\n buildServiceClientProperties,\n buildServiceIdentityHeaders,\n readRequiredCapabilities,\n unsupportedCapabilities,\n} from '@requence/helpers/protocol'\nimport logger from '@requence/logger/simple'\nimport { type Options, connect } from 'amqp-connection-manager'\nimport type { ConfirmChannel, ConsumeMessage } from 'amqplib'\nimport { z } from 'zod/v4'\n\nimport {\n type OutboundBoundary,\n createInboundBoundary,\n createOutboundBoundary,\n} from './boundary.ts'\nimport { createCallbackGrowthWatch } from './callbackGrowth.ts'\nimport {\n durableCallbackContext,\n findDurableCallback,\n} from './durableCallback.ts'\nimport {\n PayloadTooLargeError,\n RequenceConnectionError,\n UnsupportedCapabilityError,\n} from './errors.ts'\nimport createContextHelper, {\n AbortError,\n type ContextHelper,\n type JSONValue,\n RetryError,\n SkipError,\n handlerStorage,\n unwrapOutputValue,\n} from './helpers.ts'\nimport { libVersion } from './macro.ts' with { type: 'macro' }\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\nimport {\n type MutableRequenceUI,\n findUIById,\n watchUIRebuilds,\n} from './uiWatch.ts'\n\ntype InternalNamedOutput = '__internal_named_output__'\n\n/**\n * A thrown value as a sentence a viewer can read — the text a recorded\n * interaction failure quotes (#107).\n *\n * The message and not the stack: the stack goes to this process's stderr, where\n * the author is, while the row is served to whoever is looking at the surface.\n */\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\ntype Input<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['input']\ntype Configuration<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['configuration']\ntype OutputName<\n V extends keyof RequenceService.Version,\n K = keyof RequenceService.Version[V]['outputs'],\n> = K extends '__default__' ? null : K\n\ntype OutputValue<\n V extends keyof RequenceService.Version,\n O extends OutputName<V>,\n ON = O extends null ? '__default__' : O,\n> = ON extends keyof RequenceService.Version[V]['outputs']\n ? RequenceService.Version[V]['outputs'][ON]\n : never\n\ninterface ServiceContextHelper<\n V extends keyof RequenceService.Version,\n> extends Omit<\n ContextHelper,\n 'input' | 'configuration' | 'getData' | 'getConfiguration' | 'toOutput'\n> {\n input: Input<V>\n configuration: Configuration<V>\n\n toOutput<O extends OutputName<V>>(\n name: O,\n value: OutputValue<V, O>,\n ): InternalNamedOutput\n}\n\ntype ApiOutputName<V> = V extends keyof RequenceService.Version\n ? OutputName<V>\n : string | null\ntype ApiOutputValue<V, O> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O>\n : unknown\n : unknown\n\ninterface ActorApi<V> {\n sendToOutput<O extends ApiOutputName<V>>(\n outputName: O,\n data: ApiOutputValue<V, O>,\n options?: { overwrite?: boolean },\n ): void\n send(data: ApiOutputValue<V, null>, options?: { overwrite?: boolean }): void\n // Publishes a state writeback (`state: true` header). The operator honors\n // it only for privileged nodes; ordinary services' state messages are\n // ignored there.\n sendState(state: unknown): void\n /**\n * Renders a UI component on the deferred node, for as long as this `act()`\n * call runs — the `act()` re-attach of\n * `knowledge/service-ui-surfaces.md`.\n *\n * Identical in contract to `context.render`: `props` is a plain object, and\n * functions inside it arrive in the component as invokable callbacks. The\n * difference is *whose* they are — they register in this `act()` call's own\n * registry, so they live exactly as long as the call. A deferring LINEAR\n * handler cannot hold one at all (its callbacks die when it returns), which is\n * why a live surface on a deferred node has to be rendered from here.\n *\n * That is also what makes it survive a restart: reload the pending keys,\n * `act()` again, and this render — fresh connection, fresh callbacks —\n * replaces the stale surface through the last-write-wins surface row. Nothing\n * about the component or the browser has to know it happened.\n *\n * **You own the double-attach lock.** See {@link ConnectionApi.act}: two\n * replicas that both load the same pending key will both render, and the\n * second one silently takes the surface over. Requence cannot hold that lock\n * for you — it warns loudly instead.\n *\n * A render is a patch here exactly as on the main path (#102), which is what\n * makes a re-attach cheap: restate what this process knows and let the fold\n * keep the rest.\n *\n * A function written *here* is connection-bound: it closes over this `act()`\n * call, so it dies with it. A function in the UI's own defaults is durable\n * whoever renders it (#103) — which is what an actor should reach for when it\n * wants a control to keep working after it has gone.\n */\n render<Props>(\n ui: RequenceUI<Props>,\n props: RenderProps<Props>,\n options?: { surfaceId?: string },\n ): void\n abort(error: string | Error): void\n}\n\nexport interface ConnectionApi<V> {\n close(): Promise<void>\n open(): Promise<ConnectionApi<V>>\n /**\n * Deliver the result of a deferred message, later and from anywhere: pass the\n * key `context.defer()` returned and the actor runs with a send API for that\n * message. It is also the only live window a deferred node has — see\n * {@link ActorApi.render}.\n *\n * **Double-attach is YOUR lock to hold.** You own the pending-key storage, so\n * you own the exclusivity. This connection refuses a key it is already acting\n * on, but that check is per-connection and in memory: two replicas that both\n * load the pending keys on boot will both `act()` the same key, both register\n * callbacks, and both render — and the second render replaces the first one's\n * surface, so clicks silently go to whichever instance rendered last. Requence\n * does not arbitrate this (that would need cross-replica holder state plus a\n * takeover path so a dead holder cannot block a key forever); it makes the\n * symptom loud instead, by warning when a render replaces a surface that is\n * still live on another connection.\n *\n * Take a lease on the key in your own store before acting, and only act on\n * keys you hold.\n */\n act(\n messageKey: string,\n actor: (\n api: ActorApi<V>,\n ) =>\n | ApiOutputValue<V, null>\n | Promise<ApiOutputValue<V, null>>\n | void\n | Promise<void>\n | AsyncGenerator<ApiOutputValue<V, null>>\n | Generator<ApiOutputValue<V, null>>,\n ): Promise<void>\n}\n\nexport const messageKeySchema = z\n .string()\n .transform((str) => deobfuscate(str))\n .pipe(z.tuple([z.uuid(), z.uuid()]).rest(z.string()))\n .transform((arr) => ({\n taskId: arr[0],\n messageId: arr[1],\n uploadUrl: arr[2] || undefined,\n streamUrl: arr[3] || undefined,\n // Byte limits appended to the defer key alongside the transport URLs.\n // Old 4-part keys (pre-limits) parse with both absent → consumer defaults.\n maxPayloadSize:\n arr[4] && Number.isFinite(Number(arr[4])) ? Number(arr[4]) : undefined,\n maxFileSize:\n arr[5] && Number.isFinite(Number(arr[5])) ? Number(arr[5]) : undefined,\n // Appended for #150, so an `act()` call can emit a durable callback\n // reference: the node is the reference's whole address, and an acting process\n // has no dispatch to read it off. Absent in a key minted before this, which\n // then behaves exactly as it did — that path could not emit one either.\n nodeId: arr[6] || undefined,\n }))\n\nconst headerSchema = z\n .object({\n properties: z.object({\n correlationId: z.uuid(),\n headers: z.object({\n taskId: z.uuid(),\n mode: z.enum(['LINEAR', 'CONTINUOUS']).default('LINEAR'),\n }),\n }),\n })\n .transform((msg) => ({\n messageId: msg.properties.correlationId,\n taskId: msg.properties.headers.taskId,\n mode: msg.properties.headers.mode,\n }))\n\nconst payloadSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({ contentType: z.string().optional() }),\n })\n // The dispatch codec is whatever the operator declared, never an assumption:\n // `ui/backend` bakes the choice per service node, so two nodes of one task can\n // legitimately arrive under different codecs, and a replica that has just been\n // rolled forward still receives JSON for tasks created before it attached.\n .transform((msg) => decodeWireBody(msg.content, msg.properties.contentType))\n .pipe(\n z.object({\n // Optional because a dispatch may carry no input at all, and the JSON\n // codec drops an `undefined` value rather than encoding one — under zod 4\n // that absence would throw here and fail the node with a message about the\n // envelope. The msgpack codec keeps the key (as nil), so this only ever\n // shows on the JSON wire.\n input: z.unknown().optional(),\n configuration: z.unknown().optional(),\n // Which node of the graph this dispatch is for — the address a durable\n // callback reference carries out with it (#150). Optional like the rest of\n // this envelope: a dispatch minted before it existed simply cannot emit\n // one, and the callback handler says exactly that.\n nodeId: z.string().optional(),\n options: z.object({\n uploadUrl: z.url().optional(),\n streamUrl: z.url().optional(),\n maxPayloadSize: z.number().optional(),\n maxFileSize: z.number().optional(),\n }),\n }),\n )\n\nconst backchannelMessageSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({\n correlationId: z.string(),\n contentType: z.string().optional(),\n // The task, for the failure report below. Every backchannel publish stamps\n // it (the operator needs it to hash the unroutable copy onto the task's own\n // shard), so it is here rather than in the payload.\n //\n // `catch` so this can never reject a delivery: the headers are a *reporting*\n // input, and a malformed one must cost the report, not the invocation the\n // message was carrying.\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n })\n // Header-driven like every other decoder on these wires. The backchannel itself\n // stays JSON — it is a low-volume control wire — but reading the header means it\n // is not the one consumer a later codec change has to remember to visit.\n .transform((message) => ({\n ...message,\n content: decodeWireBody(message.content, message.properties.contentType),\n }))\n .pipe(\n z.object({\n content: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('stop'),\n }),\n z.object({\n type: z.literal('callback'),\n callbackId: z.uuid(),\n /**\n * `.optional()` is load-bearing, and it is not decoration: under zod 4\n * an `any` field is NOT optional, so a body with no `arg` key fails to\n * parse — and the parse failure here is a bare `return`, the one path\n * on this consumer that says nothing at all.\n *\n * A body without the key is ordinary: the wire is JSON, and a handler\n * invoked with no argument (`onInject(): void`) serializes to a key\n * `JSON.stringify` deletes. The publisher normalises to `null` now, so\n * this covers a publisher that has not been rolled forward rather than\n * the everyday case.\n */\n arg: z.any().optional(),\n /**\n * Present exactly when this callback IS a connection-bound surface\n * handler invocation (#107): the surface row it came from, so a\n * failure can be stated on the surface the viewer is looking at.\n *\n * A peer callback carries none, and must not: it belongs to a live\n * message that can fail in the ordinary way.\n */\n surface: z.uuid().optional(),\n }),\n ]),\n properties: z.object({\n correlationId: z.string(),\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n }),\n )\n .transform((message) => ({\n payload: message.content,\n messageId: message.properties.correlationId,\n taskId: message.properties.headers?.taskId,\n }))\n\nconst abortSymbol = Symbol()\n\nexport const connectionOptionsSchema = z.object({\n url: z.union([\n z\n .string()\n .regex(/^amqps?:\\/\\/(.+):(.+)@(.+)$/)\n .transform((str) => new URL(str)),\n z\n .instanceof(URL)\n .refine((url) => url.protocol.match(/^amqps?:/), 'Wrong protocol'),\n ]),\n version: z.string(),\n // Author-chosen debugging label announced in the AMQP client properties.\n // Not length-validated on purpose — an over-long label is capped, never a\n // startup failure. Nothing keys off it.\n name: z.string().optional(),\n devOverlay: z.string().optional(),\n silent: z.boolean().optional(),\n prefetch: z.number().int().optional(),\n connectionTimeout: z.number().positive().default(3_000),\n heartbeatInterval: z.number().int().positive().optional(),\n connectionOptions: z.any().optional(),\n // Hard cap on the serialized message body. A body above this is rejected with a\n // clear PayloadTooLargeError *before* it reaches the broker — the broker itself\n // only signals oversize by tearing down the connection, which amqplib surfaces\n // as an opaque \"channel closed\". Set to match the broker's max_message_size.\n maxMessageSize: z\n .number()\n .int()\n .positive()\n .default(128 * 1024 * 1024), // RabbitMQ's historical default max_message_size\n // Undocumented (privileged consumers): skip file/stream/callback rehydration\n // on ingress — claim-checks still resolve; byte references reach the handler\n // as raw `__REQUENCE_type` wire objects. See helpers.ts.\n passthroughByteReferences: z.boolean().optional(),\n})\n\nexport type PrivilegedConnectionOptions = z.output<\n typeof connectionOptionsSchema\n>\nexport type ConnectionOptions = Omit<\n PrivilegedConnectionOptions,\n 'passthroughByteReferences'\n>\n\n// Live connection state, surfaced so a caller (e.g. the logic runtime's health\n// probe) can react to loss/recovery instead of trusting a one-shot startup\n// signal. `connected: false` carries the disconnect error when the broker\n// supplied one; `connected: true` fires on the initial connect and on every\n// subsequent auto-reconnect.\nexport interface ConnectionState {\n connected: boolean\n err?: Error\n}\nexport type ConnectionStateListener = (state: ConnectionState) => void\n\ntype MessageHandlerContext<V> = V extends keyof RequenceService.Version\n ? ServiceContextHelper<V>\n : ContextHelper\ntype MessageHandlerReturnValue<\n V,\n O = null,\n> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O> | InternalNamedOutput\n : void\n : JSONValue\n\ntype MessageHandlerFunction<V> = (\n context: MessageHandlerContext<V>,\n) => MaybePromise<MessageHandlerReturnValue<V> | void>\n\ntype MessageHandlerGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => Generator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\ntype MessageHandlerAsyncGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => AsyncGenerator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\n\nexport type MessageHandler<V> = V extends keyof RequenceService.Version\n ? RequenceService.Version[V]['mode'] extends 'LINEAR'\n ? MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n\nfunction isMessageHandlerGenerator<V extends keyof RequenceService.Version>(\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n handler: Function,\n): handler is MessageHandlerGenerator<V> | MessageHandlerAsyncGenerator<V> {\n return (\n handler.constructor.name === 'GeneratorFunction' ||\n handler.constructor.name === 'AsyncGeneratorFunction'\n )\n}\n\nconst activeMessages = new Map<string, Promise<void>>()\n\n/**\n * The codec each in-flight dispatch arrived under, keyed by messageId.\n *\n * **A reply echoes the codec of its dispatch.** That is what keeps this direction\n * of the wire free of any capability logic: the service never chooses, never\n * configures and never negotiates a codec — it answers in the language it was\n * addressed in. The operator's result consumer then reads the content type back\n * off the reply, so the round trip needs no field anywhere in the protocol.\n *\n * A messageId absent from this map means JSON, which is both the pre-migration\n * status quo and the right answer for an operator loopback that never went\n * through a dispatch.\n */\nconst messageCodecs = new Map<string, WireCodec>()\n\n// A delivery tag belongs to the exact channel that delivered the message. When\n// that channel closes (e.g. the connection dropped mid-processing), amqplib\n// turns ack/nack into a synchronous `IllegalOperationError: Channel closed`.\n// The broker has already requeued the delivery for redelivery, so there is\n// nothing left to acknowledge — and we must NOT route this through the\n// reconnecting channelWrapper, which would send the stale tag on the new\n// channel and trip a 406 PRECONDITION_FAILED that kills the fresh channel.\nfunction isChannelClosedError(error: unknown): boolean {\n return error instanceof Error && error.name === 'IllegalOperationError'\n}\n\nfunction safeAck(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.ack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\n/**\n * The addressing half of an invocation, as the *headers* of the publish that\n * carries it to the operator — which is what differs between the two lifetimes\n * and the whole of what differs.\n *\n * A service publishes an invocation onto its own results stream either way: it\n * cannot reach a backchannel or a callbacks queue itself, and it should not try.\n * The operator is the party that knows where each arm goes — one live\n * connection's backchannel, or the emitting node's *version* (#150) — so both are\n * stated in a form it can route and neither is dropped here.\n */\nfunction invocationHeaders(\n payload: CallbackObject,\n // The node this invocation is published FROM — the graph node whose message is\n // running right now. On both arms, and not part of the address: the operator\n // needs it only to name the invoking node in the record, and it says so here\n // because the record it used to be looked up in can already be gone. An\n // invocation carries no publish index (by design — `done` must not wait on its\n // slot), so nothing serialises it against the `done` of this very node, and a\n // bookkeeping miss used to discard the invocation itself (#147).\n //\n // Absent where the publisher genuinely cannot know it: a defer key minted\n // before #150 carries no node, and that path behaves exactly as it did.\n invokingNodeId: string | undefined,\n): {\n connectionId?: string\n callbackId?: string\n callbackName?: string\n callbackNodeId?: string\n invokingNodeId?: string\n} {\n return {\n ...(invokingNodeId ? { invokingNodeId } : {}),\n ...(payload.lifetime === 'connection'\n ? // The EMITTER's connection, not this one: on this arm the header names the\n // backchannel to deliver to.\n { connectionId: payload.sourceId, callbackId: payload.callbackId }\n : { callbackName: payload.name, callbackNodeId: payload.nodeId }),\n }\n}\n\n/**\n * The body of that publish: the consumer's argument, and — on the durable arm —\n * the data the emitting service bound to this reference beside it.\n *\n * `bound` makes the round trip through the invoking service because that is the\n * only place it exists: the operator never held it (a claim-checked emission is\n * opaque to it) and the emitting version is where it is going. It travels\n * VERBATIM, exactly as the emitter minted it — only `arg` goes through this\n * boundary, since only `arg` was written here.\n */\nfunction invocationPayload(payload: CallbackObject, arg: unknown): unknown {\n return payload.lifetime === 'connection' ? arg : { arg, bound: payload.bound }\n}\n\nfunction safeNack(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.nack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nexport default function createConnection<V>(\n {\n url,\n version,\n prefetch = 1,\n silent = false,\n connectionTimeout,\n // Without a default this is `undefined` and amqp-connection-manager falls\n // back to 5s, which makes any event-loop stall >10s fatal to the connection.\n // Defaulted here rather than per service so every deployed service converges\n // on the same interval on its next release.\n heartbeatInterval = DEFAULT_AMQP_HEARTBEAT_SECONDS,\n connectionOptions,\n name,\n devOverlay = '',\n maxMessageSize,\n onConnectionStateChange,\n ...rest\n }: ConnectionOptions & { onConnectionStateChange?: ConnectionStateListener },\n messageHandler: MessageHandler<V>,\n) {\n const passthroughByteReferences =\n (rest as PrivilegedConnectionOptions).passthroughByteReferences ?? false\n // A non-generator handler's result path already refuses callbacks: its\n // registry entries are deleted the moment the message settles, which for a\n // returning handler is immediately. Same rule for render props — this is the\n // one place it is decided, and it is a property of the handler, not of a\n // message. (Kept separate from the narrowing call in the consume loop, whose\n // job is to type the handler.)\n const canRegisterCallbacks = isMessageHandlerGenerator(messageHandler)\n const baseQueue = `${url.username}@${version}`\n const queue = devOverlay\n ? `${baseQueue}-dev-overlay-${devOverlay}`\n : baseQueue\n const exchange = url.username\n const connection = connect(url.toString(), {\n connectionOptions: {\n ...connectionOptions,\n // Who we are, what we run, what we can decode — declared in the AMQP\n // connection frame so `ui/backend` knows it BEFORE the first dispatch.\n // amqp-connection-manager reuses these options on every reconnect, so\n // the announcement re-lands automatically. Merged LAST: the requence_*\n // keys are the contract and a caller may not shadow them.\n clientProperties: {\n ...connectionOptions?.clientProperties,\n ...buildServiceClientProperties({\n libVersion: libVersion(),\n serviceVersion: version,\n name,\n devOverlay: Boolean(devOverlay),\n }),\n },\n },\n heartbeatIntervalInSeconds: heartbeatInterval,\n })\n\n // amqp-connection-manager auto-reconnects, but without a listener a mid-\n // processing disconnect is completely silent: the raw amqplib channel that an\n // in-flight handler closed over is torn down, and the broker requeues every\n // unacked delivery. Surface it so the drop is at least observable.\n connection.on('disconnect', ({ err }: { err?: Error }) => {\n if (!silent && err) {\n logger.error('Requence AMQP connection lost:', err.message)\n }\n onConnectionStateChange?.({ connected: false, err })\n })\n\n // A reconnect fires 'connect' again, but the connectedPromise's listener has\n // already unsubscribed, so recovery was previously invisible. Track whether\n // we have connected before to distinguish the initial connect from a\n // reconnect: log the recovery (mirroring the loss above) and surface it so\n // the caller can flip its state back. Fires for the initial connect too;\n // callers treat `connected: true` idempotently.\n let hasConnected = false\n connection.on('connect', () => {\n if (hasConnected && !silent) {\n logger.info('Requence AMQP reconnected')\n }\n hasConnected = true\n onConnectionStateChange?.({ connected: true })\n })\n\n const connectedPromise = new Promise<void>((resolve, reject) => {\n const unsubscribe = () => {\n clearTimeout(timeout)\n connection.removeListener('connect', handleConnect)\n connection.removeListener('connectFailed', handleConnectFailed)\n }\n\n const timeout = setTimeout(() => {\n handleConnectFailed({\n err: new RequenceConnectionError('Requence connection timeout'),\n })\n }, connectionTimeout)\n\n const handleConnect = () => {\n unsubscribe()\n resolve()\n }\n\n const handleConnectFailed = ({ err }: { err: Error }) => {\n unsubscribe()\n if (\n err.message.startsWith(\n 'Handshake terminated by server: 403 (ACCESS-REFUSED)',\n )\n ) {\n reject(new RequenceConnectionError('Invalid service credentials'))\n } else {\n reject(err)\n }\n }\n\n connection.addListener('connect', handleConnect)\n connection.addListener('connectFailed', handleConnectFailed)\n })\n\n const connectionId = crypto.randomUUID()\n // The dev session this connection belongs to (#108), or `''` outside dev mode.\n //\n // What every surface this connection draws is stamped with, and what a rebuild\n // names to find them again. Scoped to the **session** rather than the\n // connection precisely so it survives the dev process being restarted: the\n // service, the version it overlays and the developer's token are all still the\n // same afterwards, so the surfaces drawn a moment before the restart are still\n // this session's.\n //\n // The token is hashed rather than carried, because this id comes to rest in\n // ui/backend's `task_surface` and a dev overlay key is a personal access token.\n // The service and version stay readable, which is what makes a stored session\n // id diagnosable at all.\n const devSession = devOverlay\n ? `${baseQueue}#${createHash('sha256').update(devOverlay).digest('hex').slice(0, 16)}`\n : ''\n // Derived from the queue this connection actually consumes, overlay suffix\n // included — NOT from the base name. The operator builds the routing key as\n // `service-<node.name>@<node.version>-backchannel-<connectionId>`, and in a\n // dev session ui/backend has rewritten that node's version to\n // `<version>-dev-overlay-<devKey>` (which is how the dispatch reaches this\n // worker in the first place). Anchoring to the base name instead made every\n // inbound backchannel message of a dev-mode service unroutable — the `stop`\n // that terminates a CONTINUOUS generator and, since surfaces, every callback\n // invocation. The unroutable publish then came back through the alternate\n // exchange and was read as a dead connection, so a click on a perfectly live\n // surface killed it (D5's detect-on-interaction, on a false premise).\n const backchannelQueue = `${queue}-backchannel-${connectionId}`\n // Components whose source has already left this connection, keyed\n // `<taskId>:<hash>`. ui/backend stores bundles hash-addressed and that row\n // outlives every render, so only the first render of a component **into a\n // given task** carries the ≤1 MiB source; later ones carry the hash alone.\n // There is no channel to ask ui/backend what it already has (D16: an unknown\n // hash-only render is an error state), so this set is the whole answer.\n //\n // The task is in the key, and not just the hash, because bundle retention is\n // per-task (D19): the last-referent sweep removes a bundle once NO task\n // references it, and a worker that stays connected for days can outlive every\n // task that referenced its component. Keyed by hash alone, every later render\n // from that connection would carry the hash of a bundle nobody stores —\n // permanently, self-healing only on reconnect, with nothing in the retention\n // path able to fix it (at the moment of the sweep the bundle genuinely has no\n // referents). Keyed by task, the first render into any task always carries the\n // source, so the state the sweep can produce is exactly the state a fresh key\n // repairs. It costs one ≤1 MiB transfer per task per component rather than one\n // per connection.\n //\n // Residual, accepted with D16: this records that the source was *published*,\n // not that it was ingested. If the operator discards that render (a\n // superseded epoch after a re-dispatch), a later render of the same component\n // into the same task carries no source and its surface stays an error state\n // until the process reconnects.\n const sentComponents = new Set<string>()\n const generatorTerminators = new Map<string, (reason: string) => void>()\n // Each registry entry keeps the invocation dispatcher of the message that\n // registered the callback. Entries are deleted when that message settles,\n // so a stored dispatcher is live exactly as long as its callback is — this\n // is what lets a nested function in a callback argument reconstruct as\n // invokable (chaining): its invocations egress through the registering\n // message's context (results stream → operator → peer backchannel).\n const callbacks = new Map<\n string,\n {\n callback: (...args: any[]) => void\n onCallbackInvoke: CallbackIngressContext['onCallbackInvoke']\n }\n >()\n\n // What tells an author their registry is growing, and which `yield` is doing\n // it (#151). Connection-scoped because one of its two counters is: a worker\n // holding fifty tasks at nine hundred callbacks each is the case no single\n // delivery can see. `callbacks.size` rather than a count of its own, so\n // rendered handler props — the same registry, the same growth — are in it.\n const callbackGrowth = createCallbackGrowthWatch({\n service: baseQueue,\n devOverlay: Boolean(devOverlay),\n connectionCount: () => callbacks.size,\n // The service's own log, like every other author mistake in this file. Not a\n // task update: the only person who can fix this is the one writing the\n // service, and they are reading this process's output.\n warn: (text) => logger.warn(text),\n })\n\n // Backchannel ingress (concept invariant 2): a callback argument was\n // egress-transformed by the invoking side (files/streams → references,\n // oversized values → claim-checks), so it must rehydrate here before\n // reaching user code. Connection-scoped: the callback owner is typically a\n // CONTINUOUS service whose lifetime differs from any single message, so no\n // per-message signal applies. `onCallbackInvoke` is supplied per call from\n // the registry entry, so nested functions reconstruct invokable.\n // Passthrough consumers (the logic runtime's guest channel) keep byte/callback\n // references raw here too — claim-checks still resolve, but files/streams/\n // callbacks reach the registered callback as their JSON-safe wire objects so\n // they can cross the guest's process boundary.\n const backchannelInbound = createInboundBoundary(\n passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {},\n )\n\n const channelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n if (devOverlay) {\n await channel.assertQueue(queue)\n await channel.bindQueue(queue, 'service', queue)\n }\n await channel.checkExchange(exchange)\n await channel.checkExchange(`${exchange}-retry`)\n await channel.checkQueue(queue)\n await channel.prefetch(prefetch)\n\n await channel.assertQueue(backchannelQueue, {\n exclusive: true,\n })\n\n await channel.bindQueue(backchannelQueue, 'service', backchannelQueue)\n\n await channel.consume(\n backchannelQueue,\n async (message) => {\n const result = backchannelMessageSchema.safeParse(message)\n\n if (!result.success) {\n return\n }\n\n const backchannelMessage = result.data\n\n switch (backchannelMessage.payload.type) {\n case 'stop': {\n generatorTerminators.get(backchannelMessage.messageId)?.(\n 'task stopped',\n )\n break\n }\n case 'callback': {\n const { surface } = backchannelMessage.payload\n const { taskId } = backchannelMessage\n // Reportable only when both halves are here: an interaction names\n // the surface it came from, and a report needs the task to be\n // routed. A peer callback names neither, and its failures belong to\n // its own live message.\n const report =\n surface && taskId\n ? (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n : () => {}\n\n const entry = callbacks.get(backchannelMessage.payload.callbackId)\n if (!entry) {\n // Said out loud rather than dropped (#106). This is where a\n // connection-bound surface handler lands, and an entry that is\n // gone means the message that registered it has settled — so the\n // click behind it did nothing and nobody was told. Unconditional\n // for the reason the durable arm's misses are: `silent`\n // suppresses connection noise, not a lost interaction. There is\n // no request left to fail (the mutation returned *accepted* long\n // before) and no failure channel here — the backchannel consumes\n // with noAck, outside any message context. For an *interaction*\n // there is now one more place to put it (#107): the surface.\n logger.warn(\n `Requence: dropped an invocation of callback |${backchannelMessage.payload.callbackId}| — nothing is registered under it, so the message that registered it has settled`,\n )\n report(\n 'the process that drew this surface has finished with it, so nothing ran the handler',\n )\n break\n }\n let arg: unknown\n try {\n arg = await backchannelInbound(backchannelMessage.payload.arg, {\n onCallbackInvoke: entry.onCallbackInvoke,\n })\n } catch (error) {\n // The backchannel consumes with noAck and outside any message\n // context, so a failed rehydration has no failure channel.\n // Never hand user code a raw reference — log and drop the\n // invocation instead.\n logger.warn(\n `dropped callback invocation |${backchannelMessage.payload.callbackId}|: argument rehydration failed`,\n error instanceof Error ? error.message : error,\n )\n report(\n 'the interaction could not be delivered: its argument could not be read',\n )\n break\n }\n try {\n // Awaited so an async handler's rejection is caught here rather\n // than becoming an unhandled rejection in the consume callback —\n // which, `noAck` and outside any message context, was the one way\n // a thrown handler could take the whole process down.\n await entry.callback(arg)\n } catch (error) {\n logger.error(\n `Requence: callback |${backchannelMessage.payload.callbackId}| threw:`,\n error instanceof Error\n ? (error.stack ?? error.message)\n : error,\n )\n report(`the handler failed: ${errorText(error)}`)\n }\n break\n }\n }\n },\n {\n noAck: true,\n },\n )\n },\n })\n\n // ChannelWrapper is an EventEmitter; an unhandled 'error' would otherwise\n // propagate. Observe it rather than letting it surface as an uncaught error.\n channelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP channel error:', err.message)\n }\n })\n\n /**\n * Say on the surface that this process could not run an interaction (#107).\n *\n * The only feedback channel an interaction has once it has been accepted. The\n * mutation behind a click returns *accepted* long before the invocation reaches\n * here — for a durable handler, possibly a redeploy before — so there is no\n * request to fail, no message to abort, and for a durable handler no connection\n * the viewer ever had. What is left is the surface itself, which the viewer is\n * still looking at.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id or index: a handler invocation is not a dispatch of the\n * operator's, so it has no message to be a result FOR, which is exactly why the\n * operator answers this header before everything else on that path.\n *\n * Fire-and-forget, and never fatal: this is the report of a failure, and a\n * failure to report it must not become a second one. Unconditional, `silent`\n * included, for the reason every miss here is logged unconditionally — `silent`\n * suppresses connection noise, not a lost interaction.\n */\n const reportInteractionFailure = (params: {\n taskId: string\n surface: string\n message: string\n }) => {\n void channelWrapper\n .publish(\n exchange,\n '',\n Buffer.from(\n JSON.stringify({\n surface: params.surface,\n // Truncated at the source as well as in the update schema: what keeps\n // this publish bounded is the cut made before it, and a thrown error's\n // message is author text of no bounded length.\n message: params.message.slice(\n 0,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n ),\n }),\n ),\n {\n contentType: 'application/json',\n persistent: true,\n headers: {\n taskId: params.taskId,\n [SURFACE_INTERACTION_ERROR_HEADER]: true,\n },\n },\n )\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not report a failed surface interaction on |${params.surface}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n /**\n * The dev loop (#108): a rebuilt component is a **bundle swap**, not a render.\n *\n * A rebuild changes which bytes the frame imports and nothing else, so nothing\n * about the render that drew a surface is an input here — not its props, not\n * its handlers, not whether the message that published it is still unsettled.\n * That last one is what the re-issue this replaced could never get past: a\n * deferring handler returns at the defer, taking its callback registry with it,\n * so a deferred form could not be iterated on without starting a new task for\n * every edit. Now the notice names the session and the component, ui/backend\n * repoints the rows, and every surface — a live panel, a deferred form, one\n * on a task that finished last week — swaps identically.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id, index or task: a rebuild is not a result for any dispatch of\n * the operator's, which is why the operator answers this header before it looks\n * for either.\n *\n * Fire-and-forget and never fatal, like the failure report above: the dev loop\n * is an addition to a running service, not a reason for one to fall over.\n */\n const publishBundleSwap = (ui: MutableRequenceUI) => {\n const swap: UiRebuild = {\n devSession,\n uiId: ui.id,\n hash: ui.hash,\n // Always, unlike a render's: this hash is new to everyone by definition,\n // and the surfaces this repoints are exactly the ones that would otherwise\n // name a bundle nobody stored.\n source: ui.source,\n }\n\n void channelWrapper\n .publish(exchange, '', Buffer.from(JSON.stringify(swap)), {\n contentType: 'application/json',\n persistent: true,\n headers: { [UI_REBUILD_HEADER]: true },\n })\n .then(() => {\n if (!silent) {\n logger.info(\n `Requence: component |${ui.id}| rebuilt (${ui.hash.slice(0, 12)}) — swapped on every surface of this dev session`,\n )\n }\n })\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not publish the rebuild of |${ui.id}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n // Only a dev-mode connection turns the watch on; `createUI` itself registers\n // unconditionally and starts nothing.\n const stopUIWatch = devSession\n ? watchUIRebuilds({\n onRebuild: publishBundleSwap,\n // The watch is process-global; `silent` is this connection's. It\n // reports, we decide.\n onWarning: (warning) => {\n if (!silent) {\n logger.warn(warning)\n }\n },\n })\n : undefined\n\n /**\n * Runs one durable handler invocation (#103): resolve `(uiId, path)` against\n * the components this process registered at module scope, and call the\n * function sitting there in that UI's default props.\n *\n * No context is injected, deliberately — a durable handler reaches whatever it\n * needs (`service.act()`, its own stores) through its own closure, which is\n * the same closure a module-scope function has in any other process of this\n * version. That is what \"durable\" means here.\n *\n * Every miss is **said out loud** rather than dropped: the click that produced\n * it is long gone, the mutation behind it returned *accepted*, and this\n * process is the only party that can tell an author their component named\n * something that does not exist. Unconditional, `silent` included: `silent`\n * suppresses connection noise, not a lost interaction.\n *\n * And every miss that can name a surface is also **recorded on it** (#107),\n * which is the half a viewer can see: this process's stderr is nowhere near the\n * person who pressed the button, least of all for the case that motivated it — a\n * durable handler running minutes later, in an instance the viewer never had a\n * connection to. A malformed payload is the one exception, and necessarily: it\n * is the only miss that cannot say which surface it was for.\n */\n const runHandlerInvocation = async (raw: unknown) => {\n const parsed = surfaceHandlerInvocationSchema.safeParse(raw)\n if (!parsed.success) {\n logger.error(\n 'Requence: dropped a malformed surface handler invocation:',\n parsed.error.message,\n )\n return\n }\n const { taskId, surface, uiId, path, arg } = parsed.data\n const where = `UI |${uiId}| prop |${path.join('.') || '<root>'}| (task |${taskId}|)`\n const report = (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n\n const ui = findUIById(uiId)\n if (!ui) {\n logger.error(\n `Requence: no component registered as |${uiId}| — dropped a handler invocation for ${where}`,\n )\n report(\n `the service has no component registered as \"${uiId}\", so nothing ran the handler`,\n )\n return\n }\n\n // Resolved against the DEFAULTS, because that is the only place a durable\n // handler can have been written: a function in a render's own props closes\n // over that render's process and never gets a durable reference. An empty\n // path would name the defaults object itself, which is never a function.\n const handler: unknown = getByPath(\n ui.defaults as Record<string, unknown> | undefined,\n path,\n )\n if (typeof handler !== 'function') {\n logger.error(\n `Requence: no handler at ${where} — the component's defaults have ${\n handler === undefined ? 'nothing' : typeof handler\n } there`,\n )\n report(\n `this component has no handler at \"${path.join('.') || '<root>'}\", so nothing ran`,\n )\n return\n }\n\n try {\n await (handler as (value: unknown) => unknown)(arg)\n } catch (error) {\n // Caught here rather than left to the consumer's own catch, which is one\n // frame too far out to know which surface this was: the *report* needs the\n // parsed invocation. Rethrown so that frame still logs the stack and acks.\n report(`the handler failed: ${errorText(error)}`)\n throw error\n }\n }\n\n // The per-version handler queue, consumed alongside the dispatch queue and on\n // a channel of its own: a durable invocation is not a dispatch, and sharing\n // the dispatch channel would put it behind that channel's prefetch — so one\n // long-running LINEAR message would stall every click on the version.\n //\n // Competing consumers by design: a durable handler belongs to the service\n // VERSION, so whichever instance is free serves it, and an invocation with no\n // instance running waits in the queue instead of being lost.\n const handlerQueue = serviceHandlerQueueName(queue)\n const handlerChannelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n // Asserted rather than checked, unlike the dispatch queue: ui/backend's\n // provisioner asserts it too (which is what makes it exist BEFORE any\n // instance runs, so an invocation can wait out a redeploy), but a service\n // must not fail to start against a broker whose version assert has not\n // caught up. Both sides declare the same shared literal, because a\n // mismatch is a 406 that kills this channel. In a dev session the queue is\n // this overlay's own, so nobody else asserts it at all, and these\n // arguments are the only ones it ever gets.\n //\n // The TTL is what stops the queue being a mailbox (#116): an invocation\n // nobody consumes expires instead of running whenever someone next\n // deploys, and dead-letters back to the operator so the viewer is told.\n await channel.assertQueue(handlerQueue, SURFACE_HANDLER_QUEUE_ARGUMENTS)\n await channel.bindQueue(handlerQueue, 'service', handlerQueue)\n await channel.prefetch(prefetch)\n await channel.consume(handlerQueue, async (message) => {\n if (!message) {\n return\n }\n try {\n await runHandlerInvocation(JSON.parse(message.content.toString()))\n } catch (error) {\n // A throwing handler is the author's bug and there is no request left\n // to fail (#107 puts it back on the surface). Reported and acked: a\n // requeue would rerun a side-effecting handler forever.\n logger.error(\n 'Requence: surface handler threw:',\n error instanceof Error ? (error.stack ?? error.message) : error,\n )\n }\n safeAck(channel, message)\n })\n },\n })\n\n /**\n * Runs the callback a durable invocation names (#147).\n *\n * It is given the bound data, the graph's argument and the node's static\n * configuration, and nothing else — no message, no connection, no task\n * context. That is the whole of what makes it durable: this instance may have\n * been started long after the one that emitted the reference exited.\n */\n async function runDurableCallbackInvocation(payload: unknown) {\n const parsed = durableCallbackInvocationSchema.safeParse(payload)\n if (!parsed.success) {\n // Unconditional, like the misses below: `silent` suppresses connection\n // noise, not an invocation nobody will ever hear about again.\n logger.error(\n 'Requence: dropped a malformed durable callback invocation — it does not name a callback this build can run',\n )\n return\n }\n\n const { name, bound, arg, configuration, taskId, nodeId } = parsed.data\n const registration = findDurableCallback(name)\n if (!registration) {\n // Loud, and it says which run is affected: there is no request left to\n // fail — the graph called the callback and moved on — so the only way this\n // is ever seen is if somebody says it. A name that resolves to nothing is\n // a deployed version that no longer declares what an emitted reference\n // names, which is exactly the case worth hearing about.\n throw new Error(\n `no durable callback registered as \"${name}\" — a reference naming it was emitted by node ${nodeId} of task ${taskId}, and this version declares none`,\n )\n }\n\n await registration.handler(\n arg,\n durableCallbackContext(name, bound, configuration),\n )\n }\n\n // The per-version callbacks queue, alongside the handler queue and for the\n // same reasons (#147): its own channel, so a durable invocation never queues\n // behind a long-running LINEAR dispatch; competing consumers, so whichever\n // instance of the version is free serves it; and a queue rather than a live\n // connection, so an invocation waits out a redeploy instead of dying with the\n // process that emitted the reference.\n const callbackQueue = serviceCallbackQueueName(queue)\n const callbackChannelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n // Asserted, not checked, and from the literal both parties share — see the\n // handler queue above: the provisioner's assert is what makes the queue\n // exist before any instance runs, this one is what keeps a service\n // startable against a broker that assert has not reached, and a mismatch\n // between the two is a 406 that kills this channel.\n await channel.assertQueue(callbackQueue, DURABLE_CALLBACK_QUEUE_ARGUMENTS)\n await channel.bindQueue(callbackQueue, 'service', callbackQueue)\n await channel.prefetch(prefetch)\n await channel.consume(callbackQueue, async (message) => {\n if (!message) {\n return\n }\n try {\n await runDurableCallbackInvocation(\n JSON.parse(message.content.toString()),\n )\n } catch (error) {\n // Acked either way: a requeue would rerun a side-effecting callback\n // forever, and a callback is the one thing a graph asked for\n // explicitly.\n logger.error(\n 'Requence: durable callback threw:',\n error instanceof Error ? (error.stack ?? error.message) : error,\n )\n }\n safeAck(channel, message)\n })\n },\n })\n\n callbackChannelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP callback channel error:', err.message)\n }\n })\n\n handlerChannelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP handler channel error:', err.message)\n }\n })\n\n const publish = ({\n data,\n outputName,\n messageId,\n priority,\n ...headers\n }: {\n index: number\n data?: unknown\n outputName?: string | null\n messageId: string\n taskId: string\n priority?: number\n version: string\n debugMethod?: 'log' | 'warn' | 'info' | 'error'\n debug?: boolean\n // Marks a `context.render` payload (component + props + surface). Like\n // `debug`, it is a side-channel the operator forwards as a task update\n // rather than graph output — but it rides the ordered dispatch buffer, so\n // two renders of one surface can never be re-ordered into a stale one.\n render?: boolean\n connectionId?: string\n callbackId?: string\n // The durable arm's address (#150): the declared name and the node whose\n // version serves it, in place of the connection pair above. The operator\n // routes on which of the two is present.\n callbackName?: string\n callbackNodeId?: string\n // Which node published an invocation — see `invocationHeaders`. Not an\n // address: it is what lets the operator name the invoking node without a\n // message record that may already be gone.\n invokingNodeId?: string\n propertyPath?: (string | number)[]\n begin?: boolean\n deferred?: boolean\n done?: boolean\n // Privileged result protocol: `overwrite` marks a data message whose\n // value replaces (instead of merges into) downstream aggregation;\n // `state` marks a nodeStates writeback. The operator honors both only\n // for privileged nodes. Flow through via `...headers`.\n overwrite?: boolean\n state?: boolean\n // Per-attempt id: identifies this consume-handler invocation so the\n // operator can fence a superseded attempt's stragglers on the same\n // messageId. Flows through via `...headers`.\n epoch?: string\n // Who ran this node, stamped on the `begin` publish ONLY (see\n // `buildServiceIdentityHeaders`). The operator freezes these into the\n // NODE_START update; they are display-only and nothing branches on them.\n libVersion?: string\n serviceName?: string\n capabilities?: string\n }) => {\n const { body, contentType } = encodeWireBody(\n data ?? null,\n messageCodecs.get(messageId) ?? 'json',\n )\n\n // Guard the body size before it hits the broker. An oversized publish makes\n // RabbitMQ drop the whole connection, which amqplib reports as a generic\n // \"channel closed\" for every in-flight message — impossible to attribute to\n // size after the fact. Rejecting here yields a precise, catchable error and\n // leaves the connection intact for other messages.\n if (body.byteLength > maxMessageSize) {\n return Promise.reject(\n new PayloadTooLargeError(body.byteLength, maxMessageSize),\n )\n }\n\n return channelWrapper.publish(exchange, '', body, {\n correlationId: messageId,\n contentType,\n persistent: true,\n priority,\n headers: {\n outputName: outputName ?? null,\n connectionId,\n ...headers,\n },\n })\n }\n\n /**\n * Everything a publish on behalf of one message needs, and the whole of what\n * differs between the two publish paths — the main path's consume handler and an\n * `act()` call. Shared by {@link buildSendApi} and {@link buildRender} so the\n * two cannot drift apart: they publish for the same message, through the same\n * boundary, on the same index counter.\n *\n * `epoch`/`priority` are main-path-only (an `act()` call is not a consume\n * attempt) and are omitted from the published headers when absent, keeping the\n * deferred path's output byte-identical to what it always was.\n */\n type PublishDeps = {\n outbound: OutboundBoundary\n registerCallback: (\n callback: (...args: any[]) => void,\n // Where the function was written, for the growth warning (#151) — the\n // walk's path for a callback, the payload path for a handler prop.\n path: ReadonlyArray<string | number>,\n ) => {\n sourceId: string\n callbackId: string\n }\n taskId: string\n messageId: string\n nextIndex: () => number\n epoch?: string\n priority?: number\n // act() only: wait for the deferring message's own processing to finish.\n gate?: () => Promise<void>\n }\n\n // The privileged send API (unit 05 headers), shared by the main-path handler\n // context and act()'s ActorApi: imperative data/state publishes through the\n // caller's outbound boundary, enrolled in its ledger so `settle()` gates the\n // done marker on them — a final state emission mechanically flushes before\n // `done`.\n const buildSendApi = (deps: PublishDeps) => {\n const base = {\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n ...(deps.priority === undefined ? {} : { priority: deps.priority }),\n }\n return {\n async sendToOutput(\n outputName: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: outputName as string | null,\n onCallback: deps.registerCallback,\n }),\n outputName: outputName as string | null,\n // only set when requested — omitted publishes stay identical\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async send(data: unknown, options?: { overwrite?: boolean }) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: null,\n onCallback: deps.registerCallback,\n }),\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async sendState(state: unknown) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n // out-of-band like callback publishes: state bypasses the\n // operator's ordered dispatch buffer, so it must not consume a\n // publishIndex slot — `done` would otherwise wait on a gap.\n index: 0,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n // through the outbound boundary: a large state blob offloads\n // via claim-check like any large body, and the tracked publish\n // is settled before `done` goes out.\n data: await deps.outbound.send(state, { outputName: null }),\n state: true,\n ...base,\n }),\n )\n },\n }\n }\n\n // The render publish, shared by `context.render` on the main path and\n // `send.render` inside `act()` (#70). Everything that differs between the two\n // paths is a dep — the index counter, the callback registrar, the attempt\n // headers, and act()'s gate on the deferring message's own processing — so a\n // surface behaves identically whoever published it, which is what makes the\n // dev loop, the hash bookkeeping and the liveness rule path-agnostic.\n const buildRender = (deps: PublishDeps) => {\n /**\n * One function prop → one handler reference (#103). The **path decides the\n * lifetime**, because the path is where the function was written:\n *\n * - `defaults.*` — module scope. Any instance of this version can run it,\n * now or after a redeploy, so the reference names only the UI and the prop\n * and the invocation goes to the version's handler queue. Nothing is\n * registered here: there is nothing to keep alive, and that is the point.\n * - `props.*` — written at this render call, closing over the running\n * handler. Only this process can run it, so it registers in the publishing\n * message's own registry and dies with it, exactly as a callback does —\n * including the refusal on a LINEAR handler, whose registry entries are\n * gone the moment it returns.\n *\n * The path the reference carries is relative to the **props the component\n * receives**, not to the payload: the two layers fold into one object at\n * ingestion (#102), and the browser names a path in what it was served.\n */\n const registerSurfaceHandler = (\n ui: RequenceUI,\n handler: (...args: unknown[]) => void,\n payloadPath: ReadonlyArray<string | number>,\n ): SurfaceHandlerObject => {\n const [layer, ...path] = payloadPath\n if (layer === 'defaults') {\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'durable',\n uiId: ui.id,\n path,\n }\n }\n if (layer !== 'props') {\n // Only the two author-supplied layers can hold a function; anything\n // else is the SDK's own payload and a function there is a bug here.\n throw new Error(\n `a function in a render payload is only a handler under props or defaults (found at \"${payloadPath.join('.')}\")`,\n )\n }\n // Counted like a callback, under its full payload path: it is the same\n // registry and the same growth, and a render in a loop is the same mistake.\n // The `props.` prefix is what tells the author it was a handler prop (#151).\n const { sourceId, callbackId } = deps.registerCallback(\n handler,\n payloadPath,\n )\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'connection',\n uiId: ui.id,\n path,\n connectionId: sourceId,\n handlerId: callbackId,\n }\n }\n\n const renderSurface = (params: {\n ui: RequenceUI\n props: unknown\n surfaceId: string\n }): void => {\n // The index is taken NOW, not when the serialization resolves: the\n // operator dispatches a message's results in index order, so\n // allocating here is what makes two renders of one surface arrive\n // in call order. The cost is a hole in the buffer if the\n // serialization fails — moot for a message that settles: the publish is\n // tracked, so the same failure fails the node at the caller's settle gate.\n const index = deps.nextIndex()\n // Per (task, component), never per component: see `sentComponents`. The\n // hash is read at call time, not at registration, because the dev loop\n // rewrites it in place (D10).\n const sentKey = `${deps.taskId}:${params.ui.hash}`\n const withSource = !sentComponents.has(sentKey)\n if (withSource) {\n sentComponents.add(sentKey)\n }\n\n const issue = () =>\n deps.outbound\n .send(\n {\n // `id` rides along on every render, source-carrying or not: it is\n // what a dev-loop bundle swap addresses the surface by (#108), and\n // the surface row it lands on is last-write-wins.\n component: withSource\n ? {\n id: params.ui.id,\n hash: params.ui.hash,\n source: params.ui.source,\n }\n : { id: params.ui.id, hash: params.ui.hash },\n props: params.props,\n // Restated on every render, and deliberately NOT merged into the\n // props above (#102): the receiver folds them *under* the surface's\n // stored props, so a default is overridden by anything any render\n // of that surface ever said, while this render's props override\n // everything. Merging here — what #101 did — would collapse the two\n // ranks into one and let a default clobber an earlier override.\n //\n // Read off the handle at call time, like the hash, so the next\n // render after a rebuild carries whatever it changed them to.\n // Omitted entirely when the component declared none, keeping that\n // payload byte-identical to what it always was.\n ...(params.ui.defaults === undefined\n ? {}\n : { defaults: params.ui.defaults }),\n surfaceId: params.surfaceId,\n // Stamped on every surface this connection draws, so a rebuild can\n // find them again and repoint them (#108) — and find only them: a\n // developer's edit must never reach a production surface of the\n // same component. `null` outside a dev overlay, which is every\n // render a deployed service makes.\n devSession: devSession || null,\n },\n {\n outputName: null,\n // The claim-check may offload an oversized render — but\n // never the bundle: the operator parses `component.hash`\n // out of the body, so a reference there is unreadable.\n // Pinned rather than left to the sizes falling the right\n // way (props larger than the ≤1 MiB source), which only\n // holds while the task's threshold is the 4 MiB default.\n //\n // `defaults` is pinned because it is the base layer of the\n // surface's fold — offloaded, it would silently take every prop\n // the service never restates out of the surface, and every\n // durable handler with them. `props` stays the only candidate,\n // which is what makes an oversized render a named error state\n // rather than a broken surface.\n inlineKeys: ['component', 'defaults'],\n // Switches this send onto the render egress chain, where a\n // function is a surface handler rather than a peer callback\n // (#103). Which of the two lifetimes it gets is decided by where\n // it was written, which the walk reports as the path.\n onSurfaceHandler: (handler, path) =>\n registerSurfaceHandler(params.ui, handler, path),\n },\n )\n .then((data) =>\n publish({\n index,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data,\n render: true,\n // Omitted rather than passed as `undefined` when absent, so\n // act()'s publishes keep the header set they always had.\n ...(deps.priority === undefined\n ? {}\n : { priority: deps.priority }),\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n }),\n )\n\n // The gate is awaited before the payload is built, never before the index\n // is taken — the slot has to be reserved in call order even when the\n // publish itself has to wait.\n const gated = deps.gate?.()\n deps.outbound.track(\n (gated ? gated.then(issue) : issue()).catch((error: unknown) => {\n // The source never left, so the next render of this component into\n // this task must carry it again — otherwise ui/backend would receive a\n // hash it has never seen and show an error state.\n if (withSource) {\n sentComponents.delete(sentKey)\n }\n throw error\n }),\n )\n }\n\n return renderSurface\n }\n\n channelWrapper.addSetup(async (channel: ConfirmChannel) => {\n channel.consume(queue, async (message) => {\n if (!message) {\n return\n }\n\n let publishIndex = 0\n let acked = false\n let terminated = false\n const registeredCallbackIds = new Set<string>()\n let resolveActiveMessage = () => {}\n // Captured for the finally block; header parsing now happens inside the\n // try so a malformed header goes through the error handling below instead\n // of throwing out of this async consumer as an unhandled rejection.\n let messageIdForCleanup: string | undefined\n // One epoch per consume-handler invocation (declared out here so the\n // catch-branch republishes can stamp it too). On redelivery/reconnect a\n // second invocation gets a fresh epoch, letting the operator tell the\n // attempts apart and fence the superseded one.\n const epoch = crypto.randomUUID()\n\n try {\n const { messageId, taskId, mode } = headerSchema.parse(message)\n messageIdForCleanup = messageId\n\n // The capability gate, ahead of everything the dispatch could ask of\n // this build — including its own decoding. A requirement stated in the\n // body would be unreadable exactly when it matters, so it rides in the\n // headers and is checked here, before `payloadSchema` touches the bytes.\n //\n // An empty requirement (every message published before this existed)\n // passes untouched.\n const unsupported = unsupportedCapabilities(\n readRequiredCapabilities(message.properties.headers),\n )\n if (unsupported.length > 0) {\n throw new UnsupportedCapabilityError(unsupported)\n }\n\n // Recorded before anything can publish, so every reply on this message —\n // including one from an error path — echoes the codec it arrived under.\n const dispatchCodec = wireCodecFromContentType(\n message.properties.contentType,\n )\n messageCodecs.set(messageId, dispatchCodec)\n\n let deferred = false\n let deferredReason: string | null = null\n\n const messageExecution = Promise.withResolvers<void>()\n activeMessages.set(messageId, messageExecution.promise)\n messageExecution.promise.then(() => {\n activeMessages.delete(messageId)\n })\n resolveActiveMessage = () => {\n messageExecution.resolve()\n }\n\n const payload = payloadSchema.parse(message)\n\n // The per-message abort controller is hoisted out of\n // createContextHelper so the outbound boundary can share its signal.\n const abortController = new AbortController()\n\n // Names the run in the warning (#151), so an author with several tasks\n // open knows which one to go and look at.\n const growth = callbackGrowth.forDelivery({ taskId })\n\n // One callback registrar for every egress sub-path (result, deferred\n // send, callback arg). Registered callbacks carry this message's\n // dispatcher so nested functions in their invocation arguments\n // reconstruct invokable (chaining).\n const registerCallback = (\n callback: (...args: any[]) => void,\n path: ReadonlyArray<string | number>,\n ) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n // After the entry is in, so the connection count the warning states is\n // the number this process is holding. Never refuses and never evicts:\n // a cap kills a legitimate long-lived handle at an arbitrary number\n // that nobody can set correctly.\n growth.record(path)\n return { sourceId: connectionId, callbackId }\n }\n\n // The component's single outbound boundary: owns ctx construction,\n // the background-upload ledger (done-gate) and the fail policy.\n // Fail-hard sends surface via outbound.settle() before the done\n // marker + ack; best-effort (log) sends degrade to warnings.\n const outbound = createOutboundBoundary({\n uploadUrl: payload.options.uploadUrl,\n streamUrl: payload.options.streamUrl,\n maxPayloadSize: payload.options.maxPayloadSize,\n maxFileSize: payload.options.maxFileSize,\n // What a durable callback reference emitted on this message is\n // addressed by (#150).\n nodeId: payload.nodeId,\n // Replies echo the dispatch codec, so the claim-check must measure\n // with it too — measured size == published size.\n wireCodec: dispatchCodec,\n signal: abortController.signal,\n warn: (msg, error) =>\n logger.warn(\n `${msg} (task ${taskId})`,\n error instanceof Error ? error.message : (error ?? ''),\n ),\n })\n\n // This message's single invocation egress: callback arguments are\n // real node output (they carry an outputName), so they go through the\n // same boundary as results — nested files offload, nested functions\n // become callbacks. The send + publish are tracked in the boundary's\n // ledger, so a failure fails the task at the settle gate. Used both\n // for callbacks arriving in this message's input (via\n // createContextHelper) and for callbacks this message registers\n // (chained invocations dispatched from the backchannel).\n const dispatchInvocation = (\n invocation: CallbackObject & { arg: unknown },\n ) => {\n outbound.track(\n outbound\n .send(invocation.arg, {\n outputName: invocation.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data: invocationPayload(invocation, data),\n outputName: invocation.outputName,\n propertyPath: invocation.propertyPath,\n ...invocationHeaders(invocation, payload.nodeId),\n epoch,\n }),\n ),\n )\n }\n\n // This message's publish context: one index counter, one boundary, one\n // attempt. Shared by the privileged send API below and by the render.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n epoch,\n priority: message.properties.priority,\n }\n\n const onRender = buildRender({\n ...publishDeps,\n // The one deliberate difference on this path: a function written at\n // the render call becomes a reference to THIS message's registry, so\n // it is live exactly as long as the message — and a non-generator\n // handler cannot hold one at all, because its registry entries go the\n // moment it returns.\n //\n // A function in the UI's DEFAULTS never reaches here: it is durable,\n // registers nothing, and is therefore the one handler a LINEAR\n // handler can publish — which is exactly what lets a form outlive the\n // process that drew it (#103).\n //\n // Worded for the surface author rather than reusing the result path's\n // callback wording: what this catches is a function in RENDER PROPS,\n // and naming the fix matters more than naming the rule. The tempting\n // shape is a promise the render's own handler resolves — which would\n // hold the message open for a human-speed wait, on an unacked\n // delivery a redeploy hands to another instance. `defer` plus a\n // durable default is that same form, written so it survives.\n registerCallback: canRegisterCallbacks\n ? registerCallback\n : () => {\n throw new Error(\n 'A LINEAR version handler may not register function props — the registration dies when the handler returns. To wait for a viewer, call context.defer() and declare the handler in the UI defaults instead: a durable handler outlives this process.',\n )\n },\n })\n\n const [extendedContext, terminatePromise] = (await createContextHelper({\n taskId,\n // Rehydration (FileObject/StreamObject -> RequenceFile/RequenceStream)\n // happens inside createContextHelper via its inbound boundary — the\n // signal-aware pass whose instances reach the handler.\n input: payload.input,\n configuration: payload.configuration,\n abortController,\n passthroughByteReferences,\n // Privileged send API on the handler ctx (runtime-only, hidden from\n // the ContextHelper type): shares this message's outbound boundary,\n // publishIndex counter, epoch and priority.\n sends: {\n ...buildSendApi(publishDeps),\n // Passthrough consumers hold raw callback wire refs — this is\n // their invocation egress, routed through the same\n // dispatchInvocation as a rehydrated callback call (fire-and-\n // forget; the outbound ledger settles the publish).\n invokeCallback: (ref, arg) => dispatchInvocation({ ...ref, arg }),\n options: payload.options,\n },\n onLog(debugMethod, data) {\n // Best-effort: a debug log must never fail the task. The boundary\n // sanitizes the payload (functions/opaque instances → labels),\n // degrades offload failures to warnings, and keeps the done-gate\n // waiting for the upload without letting it fail the task. On a\n // transform error it resolves `undefined` and nothing is published.\n void outbound.send(data, { bestEffort: true }).then((mapped) => {\n if (mapped === undefined) {\n return\n }\n publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: mapped,\n debugMethod,\n priority: message.properties.priority,\n debug: true,\n epoch,\n })\n })\n },\n onRender,\n onDefer(reason) {\n deferred = true\n deferredReason = reason || null\n\n return obfuscate(\n taskId,\n messageId,\n payload.options.uploadUrl ?? '',\n payload.options.streamUrl ?? '',\n payload.options.maxPayloadSize?.toString() ?? '',\n payload.options.maxFileSize?.toString() ?? '',\n payload.nodeId ?? '',\n )\n },\n onCallback: dispatchInvocation,\n })) as unknown as [\n MessageHandlerContext<V>,\n PromiseWithResolvers<string>,\n ]\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n priority: message.properties.priority,\n begin: true,\n epoch,\n // The one stamp per node execution: this build, this box. It becomes\n // the NODE_START update's `service`, which is written once and never\n // re-derived — so anything absent here is lost for that run.\n ...buildServiceIdentityHeaders({\n libVersion: libVersion(),\n name,\n }),\n })\n\n if (isMessageHandlerGenerator(messageHandler)) {\n if (mode === 'CONTINUOUS') {\n // CONTINUOUS: ACK immediately, operator watchdog supervises. A\n // LINEAR message stays unacked until done — prefetch keeps\n // bounding concurrent work and the broker redelivers on a crash.\n safeAck(channel, message)\n acked = true\n }\n\n const generator = messageHandler(extendedContext)\n const terminationPromise = Promise.withResolvers<typeof abortSymbol>()\n generatorTerminators.set(messageId, (reason) => {\n terminated = true\n // Suppress native AbortError that may reject generator.return() when\n // context.terminated.signal fires and cancels a pending await inside\n // the generator (e.g. node:timers/promises setTimeout with { signal }).\n ;(generator.return() as Promise<unknown>).catch(\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return\n }\n throw error\n },\n )\n terminationPromise.resolve(abortSymbol)\n terminatePromise.resolve(reason)\n })\n\n await handlerStorage.run(\n extendedContext as ContextHelper,\n async () => {\n while (true) {\n type IterResult = IteratorResult<\n MessageHandlerReturnValue<V, null>,\n void | MessageHandlerReturnValue<V, null>\n >\n // Catch native AbortError from context.terminated.signal so\n // generator implementations don't need their own try/catch.\n const nextPromise = Promise.resolve(generator.next()).then(\n (r) => r,\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return { value: undefined, done: true } as IterResult\n }\n throw error\n },\n )\n const next = await Promise.race([\n terminationPromise.promise,\n nextPromise,\n ])\n if (next === abortSymbol) {\n break\n }\n\n const { value: result, done } = next\n\n if (deferred) {\n deferred = false\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n }\n\n const { value: rawValue, outputName } =\n unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: registerCallback,\n })\n\n if (!done || typeof value !== 'undefined') {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n\n if (done) {\n break\n }\n }\n },\n )\n } else {\n const result = await handlerStorage.run(\n extendedContext as ContextHelper,\n () => messageHandler(extendedContext),\n )\n const { value: rawValue, outputName } = unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: () => {\n throw new Error(\n 'callbacks can only be used in generator functions',\n )\n },\n })\n if (deferred && value) {\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n deferred = false\n }\n\n if (!deferred || value) {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n setImmediate(async () => {\n try {\n // The boundary's settle gate: waits for every tracked background\n // upload/publish, then throws an AggregateError on any fail-hard\n // failure — which surfaces here and reaches the outer catch ->\n // exception republish -> throwServiceError -> failNode. The done\n // marker + ack only happen once every upload succeeded.\n if (!deferred) {\n await outbound.settle()\n }\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: deferredReason,\n priority: message.properties.priority,\n deferred,\n done: !deferred,\n epoch,\n })\n\n if (!acked) {\n safeAck(channel, message)\n }\n resolve()\n } catch (error) {\n reject(error)\n }\n })\n })\n } catch (error) {\n if (error instanceof SkipError) {\n if (!acked) {\n safeNack(channel, message)\n }\n return\n }\n if (error instanceof RetryError) {\n if (!acked) {\n safeAck(channel, message)\n }\n const properties: Options.Publish = {\n ...message.properties,\n expiration: error.delay || 1_000, // 1s\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n version, // to other services\n message.content,\n properties,\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to republish message for retry:',\n publishError,\n )\n }\n })\n\n return\n }\n\n // A refusal, not a failure: this box is the wrong one, the message is\n // fine. It goes back by REPUBLISHING to `<exchange>-retry`, never by\n // nacking, because a nack can carry no rejection count and a classic\n // queue offers none either — see `CAPABILITY_HEADER_KEYS.mismatch` in\n // `@requence/helpers/protocol` for the full argument, and this file's\n // spec, which pins it. The republish reaches the operator's error\n // consumer, which already counts attempts, delays and fails the node.\n if (error instanceof UnsupportedCapabilityError) {\n if (!silent) {\n logger.error(error.message)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n // The dispatch verbatim: a reroute re-dispatches these bytes, and\n // this build never decoded them.\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n [CAPABILITY_HEADER_KEYS.mismatch]: true,\n index: publishIndex++,\n 'error-message': error.message,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish capability mismatch message:',\n publishError,\n )\n }\n })\n\n return\n }\n\n if (error instanceof AbortError && error.message.length > 0) {\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', //back to operator\n error.message,\n {\n ...message.properties,\n contentType: 'text/plain',\n headers: {\n ...message.properties.headers,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error('Failed to publish abort message:', publishError)\n }\n })\n\n return\n }\n\n // Native AbortError thrown when context.terminated.signal fires\n // (e.g. node:timers/promises setTimeout with { signal: context.terminated.signal }).\n // Only suppress when actually in a terminated state — otherwise a\n // different AbortSignal caused the error and it should propagate.\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n if (!acked) {\n safeAck(channel, message)\n }\n return\n }\n\n if (error instanceof Error) {\n if (!silent) {\n logger.error('Encountered an error inside service handler:')\n logger.error(error)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n exception: true,\n index: publishIndex++,\n 'error-message': error.message || 'error in service handler',\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish exception message:',\n publishError,\n )\n }\n })\n\n return\n }\n } finally {\n if (messageIdForCleanup) {\n generatorTerminators.delete(messageIdForCleanup)\n // Bounded with the delivery rather than left to accumulate. A publish\n // that outlives the handler — a deferred message's later send — then\n // falls back to JSON, which the operator decodes correctly off the\n // header. It loses the size win for that one message and nothing else:\n // degrading to JSON is always safe, which is why the fallback is JSON\n // and not \"the last codec we saw\".\n messageCodecs.delete(messageIdForCleanup)\n }\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n resolveActiveMessage()\n }\n })\n })\n\n const activeMessageKeys = new Set<string>()\n const api: ConnectionApi<V> = {\n close: async () => {\n stopUIWatch?.()\n await callbackChannelWrapper.close()\n await handlerChannelWrapper.close()\n await channelWrapper.close()\n await connection.close()\n },\n open: () => connectedPromise.then(() => api),\n\n async act(messageKey, actor) {\n if (activeMessageKeys.has(messageKey)) {\n throw new Error('a defer key can only be used once')\n }\n\n activeMessageKeys.add(messageKey)\n\n let publishIndex = 0\n const { taskId, messageId, ...options } =\n messageKeySchema.parse(messageKey)\n\n const activeMessage = async () => {\n if (activeMessages.has(messageId)) {\n await activeMessages.get(messageId)\n }\n }\n\n const registeredCallbackIds = new Set<string>()\n // The deferred path's own outbound boundary: its ledger replaces the\n // old donePromises/uploadErrors pair — errors are caught at\n // registration time (nothing sits unhandled during long generator\n // iteration) and surfaced by settle() after the loop.\n const outbound = createOutboundBoundary(options)\n // The same growth warning as the main path (#151): an `act()` call holds\n // its own registry and may iterate a generator of its own, so it can grow\n // one the same way.\n const growth = callbackGrowth.forDelivery({ taskId })\n const registerCallback = (\n callback: (...args: any[]) => void,\n path: ReadonlyArray<string | number>,\n ) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n growth.record(path)\n return { sourceId: connectionId, callbackId }\n }\n\n // Deferred-path analogue of the main path's dispatchInvocation: chained\n // invocations of callbacks registered here egress through this deferred\n // message's context (no epoch, matching its other publishes).\n const dispatchInvocation = (\n invocation: CallbackObject & { arg: unknown },\n ) => {\n outbound.track(\n outbound\n .send(invocation.arg, {\n outputName: invocation.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data: invocationPayload(invocation, data),\n outputName: invocation.outputName,\n propertyPath: invocation.propertyPath,\n ...invocationHeaders(invocation, options.nodeId),\n }),\n ),\n )\n }\n\n // This act() call's publish context: its own index counter, its own\n // callback registry, its own active-message gate, and no attempt headers —\n // an acting process is not a consume attempt. Both the send API and the\n // render read it, so the two cannot disagree about which message they\n // publish for.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n gate: activeMessage,\n }\n\n const renderSurface = buildRender(publishDeps)\n\n const sendApi = {\n ...buildSendApi(publishDeps),\n // The live window a deferred node gets (#70): the same render as the\n // main path, publishing into the same last-write-wins surface — so a\n // re-attach after a restart replaces the stale one, with fresh callbacks\n // registered here rather than in a message context that no longer\n // exists. The lock against a second instance doing this concurrently is\n // the author's (D9); see `ConnectionApi.act`.\n render(\n ui: RequenceUI,\n props: unknown,\n renderOptions?: { surfaceId?: string },\n ) {\n // The default mirrors `context.render` in helpers.ts — the public\n // shape of a render is the same on both paths.\n renderSurface({\n ui,\n props,\n surfaceId: renderOptions?.surfaceId ?? DEFAULT_SURFACE_ID,\n })\n },\n async abort(error: string | Error) {\n await activeMessage()\n channelWrapper.publish(\n `${exchange}-retry`,\n 'operator',\n error instanceof Error ? error.message : error,\n {\n persistent: true,\n correlationId: messageId,\n expiration: 0,\n priority: 0,\n contentType: 'text/plain',\n headers: {\n taskId,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n },\n }\n\n const result = await actor(sendApi as ActorApi<V>)\n\n if (\n result != null &&\n typeof result === 'object' &&\n (Symbol.asyncIterator in result || Symbol.iterator in result)\n ) {\n // Generator: iterate and send each yielded value\n const iterable = result as AsyncIterable<unknown> | Iterable<unknown>\n for await (const value of iterable) {\n if (value !== undefined) {\n await sendApi.send(value)\n }\n }\n } else if (result !== undefined) {\n await sendApi.send(result)\n }\n\n await new Promise((resolve) => setImmediate(resolve))\n await activeMessage()\n\n try {\n // Settle gate: waits while sends enqueue more sends, then throws an\n // AggregateError on any failed background upload or publish.\n await outbound.settle()\n } catch (error) {\n // Do not mark the message done with a dangling reference. Signal\n // failure over the deferred-path error channel (abort -> operator\n // fails the node) and throw so act()'s caller sees it too.\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n const first =\n error instanceof AggregateError && error.errors[0] instanceof Error\n ? error.errors[0]\n : error instanceof Error\n ? error\n : new Error(String(error))\n await sendApi.abort(first)\n activeMessageKeys.delete(messageKey)\n throw error\n }\n\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n done: true,\n })\n\n activeMessageKeys.delete(messageKey)\n },\n }\n\n return api\n}\n",
|
|
18
|
+
"import { createHash } from 'node:crypto'\n\nimport type { CallbackIngressContext } from '@requence/callbacks'\nimport {\n type CallbackObject,\n DEFAULT_AMQP_HEARTBEAT_SECONDS,\n DEFAULT_SURFACE_ID,\n DURABLE_CALLBACK_QUEUE_ARGUMENTS,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n type MaybePromise,\n SURFACE_HANDLER_QUEUE_ARGUMENTS,\n SURFACE_HANDLER_TAG,\n SURFACE_INTERACTION_ERROR_HEADER,\n type SurfaceHandlerObject,\n UI_REBUILD_HEADER,\n type UiRebuild,\n deobfuscate,\n durableCallbackInvocationSchema,\n getByPath,\n obfuscate,\n serviceCallbackQueueName,\n serviceHandlerQueueName,\n surfaceHandlerInvocationSchema,\n} from '@requence/helpers'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport {\n decodeWireBody,\n encodeWireBody,\n wireCodecFromContentType,\n} from '@requence/helpers/msgpack'\nimport {\n CAPABILITY_HEADER_KEYS,\n buildServiceClientProperties,\n buildServiceIdentityHeaders,\n readRequiredCapabilities,\n unsupportedCapabilities,\n} from '@requence/helpers/protocol'\nimport logger from '@requence/logger/simple'\nimport { type Options, connect } from 'amqp-connection-manager'\nimport type { ConfirmChannel, ConsumeMessage } from 'amqplib'\nimport { z } from 'zod/v4'\n\nimport {\n type OutboundBoundary,\n createInboundBoundary,\n createOutboundBoundary,\n} from './boundary.ts'\nimport { createCallbackGrowthWatch } from './callbackGrowth.ts'\nimport {\n durableCallbackContext,\n findDurableCallback,\n} from './durableCallback.ts'\nimport {\n PayloadTooLargeError,\n RequenceConnectionError,\n UnsupportedCapabilityError,\n} from './errors.ts'\nimport createContextHelper, {\n AbortError,\n type ContextHelper,\n type JSONValue,\n RetryError,\n SkipError,\n handlerStorage,\n unwrapOutputValue,\n} from './helpers.ts'\nimport { libVersion } from './macro.ts' with { type: 'macro' }\nimport { createStore } from './store.ts'\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\nimport {\n type MutableRequenceUI,\n findUIById,\n watchUIRebuilds,\n} from './uiWatch.ts'\n\ntype InternalNamedOutput = '__internal_named_output__'\n\n/**\n * A thrown value as a sentence a viewer can read — the text a recorded\n * interaction failure quotes (#107).\n *\n * The message and not the stack: the stack goes to this process's stderr, where\n * the author is, while the row is served to whoever is looking at the surface.\n */\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\ntype Input<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['input']\ntype Configuration<V extends keyof RequenceService.Version> =\n RequenceService.Version[V]['configuration']\ntype OutputName<\n V extends keyof RequenceService.Version,\n K = keyof RequenceService.Version[V]['outputs'],\n> = K extends '__default__' ? null : K\n\ntype OutputValue<\n V extends keyof RequenceService.Version,\n O extends OutputName<V>,\n ON = O extends null ? '__default__' : O,\n> = ON extends keyof RequenceService.Version[V]['outputs']\n ? RequenceService.Version[V]['outputs'][ON]\n : never\n\ninterface ServiceContextHelper<\n V extends keyof RequenceService.Version,\n> extends Omit<\n ContextHelper,\n 'input' | 'configuration' | 'getData' | 'getConfiguration' | 'toOutput'\n> {\n input: Input<V>\n configuration: Configuration<V>\n\n toOutput<O extends OutputName<V>>(\n name: O,\n value: OutputValue<V, O>,\n ): InternalNamedOutput\n}\n\ntype ApiOutputName<V> = V extends keyof RequenceService.Version\n ? OutputName<V>\n : string | null\ntype ApiOutputValue<V, O> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O>\n : unknown\n : unknown\n\ninterface ActorApi<V> {\n sendToOutput<O extends ApiOutputName<V>>(\n outputName: O,\n data: ApiOutputValue<V, O>,\n options?: { overwrite?: boolean },\n ): void\n send(data: ApiOutputValue<V, null>, options?: { overwrite?: boolean }): void\n /**\n * Renders a UI component on the deferred node, for as long as this `act()`\n * call runs — the `act()` re-attach of\n * `knowledge/service-ui-surfaces.md`.\n *\n * Identical in contract to `context.render`: `props` is a plain object, and\n * functions inside it arrive in the component as invokable callbacks. The\n * difference is *whose* they are — they register in this `act()` call's own\n * registry, so they live exactly as long as the call. A deferring LINEAR\n * handler cannot hold one at all (its callbacks die when it returns), which is\n * why a live surface on a deferred node has to be rendered from here.\n *\n * That is also what makes it survive a restart: reload the pending keys,\n * `act()` again, and this render — fresh connection, fresh callbacks —\n * replaces the stale surface through the last-write-wins surface row. Nothing\n * about the component or the browser has to know it happened.\n *\n * **You own the double-attach lock.** See {@link ConnectionApi.act}: two\n * replicas that both load the same pending key will both render, and the\n * second one silently takes the surface over. Requence cannot hold that lock\n * for you — it warns loudly instead.\n *\n * A render is a patch here exactly as on the main path (#102), which is what\n * makes a re-attach cheap: restate what this process knows and let the fold\n * keep the rest.\n *\n * A function written *here* is connection-bound: it closes over this `act()`\n * call, so it dies with it. A function in the UI's own defaults is durable\n * whoever renders it (#103) — which is what an actor should reach for when it\n * wants a control to keep working after it has gone.\n */\n render<Props>(\n ui: RequenceUI<Props>,\n props: RenderProps<Props>,\n options?: { surfaceId?: string },\n ): void\n abort(error: string | Error): void\n}\n\nexport interface ConnectionApi<V> {\n close(): Promise<void>\n open(): Promise<ConnectionApi<V>>\n /**\n * Deliver the result of a deferred message, later and from anywhere: pass the\n * key `context.defer()` returned and the actor runs with a send API for that\n * message. It is also the only live window a deferred node has — see\n * {@link ActorApi.render}.\n *\n * **Double-attach is YOUR lock to hold.** You own the pending-key storage, so\n * you own the exclusivity. This connection refuses a key it is already acting\n * on, but that check is per-connection and in memory: two replicas that both\n * load the pending keys on boot will both `act()` the same key, both register\n * callbacks, and both render — and the second render replaces the first one's\n * surface, so clicks silently go to whichever instance rendered last. Requence\n * does not arbitrate this (that would need cross-replica holder state plus a\n * takeover path so a dead holder cannot block a key forever); it makes the\n * symptom loud instead, by warning when a render replaces a surface that is\n * still live on another connection.\n *\n * Take a lease on the key in your own store before acting, and only act on\n * keys you hold.\n */\n act(\n messageKey: string,\n actor: (\n api: ActorApi<V>,\n ) =>\n | ApiOutputValue<V, null>\n | Promise<ApiOutputValue<V, null>>\n | void\n | Promise<void>\n | AsyncGenerator<ApiOutputValue<V, null>>\n | Generator<ApiOutputValue<V, null>>,\n ): Promise<void>\n}\n\nexport const messageKeySchema = z\n .string()\n .transform((str) => deobfuscate(str))\n .pipe(z.tuple([z.uuid(), z.uuid()]).rest(z.string()))\n .transform((arr) => ({\n taskId: arr[0],\n messageId: arr[1],\n uploadUrl: arr[2] || undefined,\n streamUrl: arr[3] || undefined,\n // Byte limits appended to the defer key alongside the transport URLs.\n // Old 4-part keys (pre-limits) parse with both absent → consumer defaults.\n maxPayloadSize:\n arr[4] && Number.isFinite(Number(arr[4])) ? Number(arr[4]) : undefined,\n maxFileSize:\n arr[5] && Number.isFinite(Number(arr[5])) ? Number(arr[5]) : undefined,\n // Appended for #150, so an `act()` call can emit a durable callback\n // reference: the node is the reference's whole address, and an acting process\n // has no dispatch to read it off. Absent in a key minted before this, which\n // then behaves exactly as it did — that path could not emit one either.\n nodeId: arr[6] || undefined,\n }))\n\nconst headerSchema = z\n .object({\n properties: z.object({\n correlationId: z.uuid(),\n headers: z.object({\n taskId: z.uuid(),\n mode: z.enum(['LINEAR', 'CONTINUOUS']).default('LINEAR'),\n }),\n }),\n })\n .transform((msg) => ({\n messageId: msg.properties.correlationId,\n taskId: msg.properties.headers.taskId,\n mode: msg.properties.headers.mode,\n }))\n\nconst payloadSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({ contentType: z.string().optional() }),\n })\n // The dispatch codec is whatever the operator declared, never an assumption:\n // `ui/backend` bakes the choice per service node, so two nodes of one task can\n // legitimately arrive under different codecs, and a replica that has just been\n // rolled forward still receives JSON for tasks created before it attached.\n .transform((msg) => decodeWireBody(msg.content, msg.properties.contentType))\n .pipe(\n z.object({\n // Optional because a dispatch may carry no input at all, and the JSON\n // codec drops an `undefined` value rather than encoding one — under zod 4\n // that absence would throw here and fail the node with a message about the\n // envelope. The msgpack codec keeps the key (as nil), so this only ever\n // shows on the JSON wire.\n input: z.unknown().optional(),\n configuration: z.unknown().optional(),\n // Which node of the graph this dispatch is for — the address a durable\n // callback reference carries out with it (#150). Optional like the rest of\n // this envelope: a dispatch minted before it existed simply cannot emit\n // one, and the callback handler says exactly that.\n nodeId: z.string().optional(),\n // Set only when this dispatch is a configuration-function evaluation\n // (#224). `nodeId` is then the HOST node's — the node being configured —\n // and the store composes `private` slots into that node's configuration\n // box rather than into the host service's own.\n //\n // Not spelled `configuration`: that key is already this envelope's\n // configuration VALUE. The operator's own word for the phase is the\n // config eval, so that is the name on the wire.\n configurationEval: z.boolean().optional(),\n options: z.object({\n uploadUrl: z.url().optional(),\n streamUrl: z.url().optional(),\n maxPayloadSize: z.number().optional(),\n maxFileSize: z.number().optional(),\n // The store capability (#210), copied onto every dispatch by the\n // operator, which reads neither field. `z.string()` rather than\n // `z.url()` deliberately: it must accept exactly what\n // `taskOptionsSchema` accepts, or a dispatch the protocol calls valid\n // fails the whole envelope here.\n storeUrl: z.string().optional(),\n storeSignature: z.string().optional(),\n }),\n }),\n )\n\nconst backchannelMessageSchema = z\n .object({\n content: z.instanceof(Buffer),\n properties: z.object({\n correlationId: z.string(),\n contentType: z.string().optional(),\n // The task, for the failure report below. Every backchannel publish stamps\n // it (the operator needs it to hash the unroutable copy onto the task's own\n // shard), so it is here rather than in the payload.\n //\n // `catch` so this can never reject a delivery: the headers are a *reporting*\n // input, and a malformed one must cost the report, not the invocation the\n // message was carrying.\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n })\n // Header-driven like every other decoder on these wires. The backchannel itself\n // stays JSON — it is a low-volume control wire — but reading the header means it\n // is not the one consumer a later codec change has to remember to visit.\n .transform((message) => ({\n ...message,\n content: decodeWireBody(message.content, message.properties.contentType),\n }))\n .pipe(\n z.object({\n content: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('stop'),\n }),\n z.object({\n type: z.literal('callback'),\n callbackId: z.uuid(),\n /**\n * `.optional()` is load-bearing, and it is not decoration: under zod 4\n * an `any` field is NOT optional, so a body with no `arg` key fails to\n * parse — and the parse failure here is a bare `return`, the one path\n * on this consumer that says nothing at all.\n *\n * A body without the key is ordinary: the wire is JSON, and a handler\n * invoked with no argument (`onInject(): void`) serializes to a key\n * `JSON.stringify` deletes. The publisher normalises to `null` now, so\n * this covers a publisher that has not been rolled forward rather than\n * the everyday case.\n */\n arg: z.any().optional(),\n /**\n * Present exactly when this callback IS a connection-bound surface\n * handler invocation (#107): the surface row it came from, so a\n * failure can be stated on the surface the viewer is looking at.\n *\n * A peer callback carries none, and must not: it belongs to a live\n * message that can fail in the ordinary way.\n */\n surface: z.uuid().optional(),\n }),\n ]),\n properties: z.object({\n correlationId: z.string(),\n headers: z\n .object({ taskId: z.uuid().optional() })\n .optional()\n .catch(undefined),\n }),\n }),\n )\n .transform((message) => ({\n payload: message.content,\n messageId: message.properties.correlationId,\n taskId: message.properties.headers?.taskId,\n }))\n\nconst abortSymbol = Symbol()\n\nexport const connectionOptionsSchema = z.object({\n url: z.union([\n z\n .string()\n .regex(/^amqps?:\\/\\/(.+):(.+)@(.+)$/)\n .transform((str) => new URL(str)),\n z\n .instanceof(URL)\n .refine((url) => url.protocol.match(/^amqps?:/), 'Wrong protocol'),\n ]),\n version: z.string(),\n // Author-chosen debugging label announced in the AMQP client properties.\n // Not length-validated on purpose — an over-long label is capped, never a\n // startup failure. Nothing keys off it.\n name: z.string().optional(),\n devOverlay: z.string().optional(),\n silent: z.boolean().optional(),\n prefetch: z.number().int().optional(),\n connectionTimeout: z.number().positive().default(3_000),\n heartbeatInterval: z.number().int().positive().optional(),\n connectionOptions: z.any().optional(),\n // Hard cap on the serialized message body. A body above this is rejected with a\n // clear PayloadTooLargeError *before* it reaches the broker — the broker itself\n // only signals oversize by tearing down the connection, which amqplib surfaces\n // as an opaque \"channel closed\". Set to match the broker's max_message_size.\n maxMessageSize: z\n .number()\n .int()\n .positive()\n .default(128 * 1024 * 1024), // RabbitMQ's historical default max_message_size\n // Undocumented (privileged consumers): skip file/stream/callback rehydration\n // on ingress — claim-checks still resolve; byte references reach the handler\n // as raw `__REQUENCE_type` wire objects. See helpers.ts.\n passthroughByteReferences: z.boolean().optional(),\n})\n\nexport type PrivilegedConnectionOptions = z.output<\n typeof connectionOptionsSchema\n>\nexport type ConnectionOptions = Omit<\n PrivilegedConnectionOptions,\n 'passthroughByteReferences'\n>\n\n// Live connection state, surfaced so a caller (e.g. the logic runtime's health\n// probe) can react to loss/recovery instead of trusting a one-shot startup\n// signal. `connected: false` carries the disconnect error when the broker\n// supplied one; `connected: true` fires on the initial connect and on every\n// subsequent auto-reconnect.\nexport interface ConnectionState {\n connected: boolean\n err?: Error\n}\nexport type ConnectionStateListener = (state: ConnectionState) => void\n\ntype MessageHandlerContext<V> = V extends keyof RequenceService.Version\n ? ServiceContextHelper<V>\n : ContextHelper\ntype MessageHandlerReturnValue<\n V,\n O = null,\n> = V extends keyof RequenceService.Version\n ? O extends OutputName<V>\n ? OutputValue<V, O> | InternalNamedOutput\n : void\n : JSONValue\n\ntype MessageHandlerFunction<V> = (\n context: MessageHandlerContext<V>,\n) => MaybePromise<MessageHandlerReturnValue<V> | void>\n\ntype MessageHandlerGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => Generator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\ntype MessageHandlerAsyncGenerator<V> = (\n context: MessageHandlerContext<V>,\n) => AsyncGenerator<\n MessageHandlerReturnValue<V>,\n MessageHandlerReturnValue<V> | void,\n void\n>\n\nexport type MessageHandler<V> = V extends keyof RequenceService.Version\n ? RequenceService.Version[V]['mode'] extends 'LINEAR'\n ? MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n :\n | MessageHandlerAsyncGenerator<V>\n | MessageHandlerGenerator<V>\n | MessageHandlerFunction<V>\n\nfunction isMessageHandlerGenerator<V extends keyof RequenceService.Version>(\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n handler: Function,\n): handler is MessageHandlerGenerator<V> | MessageHandlerAsyncGenerator<V> {\n return (\n handler.constructor.name === 'GeneratorFunction' ||\n handler.constructor.name === 'AsyncGeneratorFunction'\n )\n}\n\nconst activeMessages = new Map<string, Promise<void>>()\n\n/**\n * The codec each in-flight dispatch arrived under, keyed by messageId.\n *\n * **A reply echoes the codec of its dispatch.** That is what keeps this direction\n * of the wire free of any capability logic: the service never chooses, never\n * configures and never negotiates a codec — it answers in the language it was\n * addressed in. The operator's result consumer then reads the content type back\n * off the reply, so the round trip needs no field anywhere in the protocol.\n *\n * A messageId absent from this map means JSON, which is both the pre-migration\n * status quo and the right answer for an operator loopback that never went\n * through a dispatch.\n */\nconst messageCodecs = new Map<string, WireCodec>()\n\n// A delivery tag belongs to the exact channel that delivered the message. When\n// that channel closes (e.g. the connection dropped mid-processing), amqplib\n// turns ack/nack into a synchronous `IllegalOperationError: Channel closed`.\n// The broker has already requeued the delivery for redelivery, so there is\n// nothing left to acknowledge — and we must NOT route this through the\n// reconnecting channelWrapper, which would send the stale tag on the new\n// channel and trip a 406 PRECONDITION_FAILED that kills the fresh channel.\nfunction isChannelClosedError(error: unknown): boolean {\n return error instanceof Error && error.name === 'IllegalOperationError'\n}\n\nfunction safeAck(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.ack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\n/**\n * The addressing half of an invocation, as the *headers* of the publish that\n * carries it to the operator — which is what differs between the two lifetimes\n * and the whole of what differs.\n *\n * A service publishes an invocation onto its own results stream either way: it\n * cannot reach a backchannel or a callbacks queue itself, and it should not try.\n * The operator is the party that knows where each arm goes — one live\n * connection's backchannel, or the emitting node's *version* (#150) — so both are\n * stated in a form it can route and neither is dropped here.\n */\nfunction invocationHeaders(\n payload: CallbackObject,\n // The node this invocation is published FROM — the graph node whose message is\n // running right now. On both arms, and not part of the address: the operator\n // needs it only to name the invoking node in the record, and it says so here\n // because the record it used to be looked up in can already be gone. An\n // invocation carries no publish index (by design — `done` must not wait on its\n // slot), so nothing serialises it against the `done` of this very node, and a\n // bookkeeping miss used to discard the invocation itself (#147).\n //\n // Absent where the publisher genuinely cannot know it: a defer key minted\n // before #150 carries no node, and that path behaves exactly as it did.\n invokingNodeId: string | undefined,\n): {\n connectionId?: string\n callbackId?: string\n callbackName?: string\n callbackNodeId?: string\n invokingNodeId?: string\n} {\n return {\n ...(invokingNodeId ? { invokingNodeId } : {}),\n ...(payload.lifetime === 'connection'\n ? // The EMITTER's connection, not this one: on this arm the header names the\n // backchannel to deliver to.\n { connectionId: payload.sourceId, callbackId: payload.callbackId }\n : { callbackName: payload.name, callbackNodeId: payload.nodeId }),\n }\n}\n\n/**\n * The body of that publish: the consumer's argument, and — on the durable arm —\n * the data the emitting service bound to this reference beside it.\n *\n * `bound` makes the round trip through the invoking service because that is the\n * only place it exists: the operator never held it (a claim-checked emission is\n * opaque to it) and the emitting version is where it is going. It travels\n * VERBATIM, exactly as the emitter minted it — only `arg` goes through this\n * boundary, since only `arg` was written here.\n */\nfunction invocationPayload(payload: CallbackObject, arg: unknown): unknown {\n return payload.lifetime === 'connection' ? arg : { arg, bound: payload.bound }\n}\n\nfunction safeNack(channel: ConfirmChannel, message: ConsumeMessage) {\n try {\n channel.nack(message)\n } catch (error) {\n if (!isChannelClosedError(error)) {\n throw error\n }\n }\n}\n\nexport default function createConnection<V>(\n {\n url,\n version,\n prefetch = 1,\n silent = false,\n connectionTimeout,\n // Without a default this is `undefined` and amqp-connection-manager falls\n // back to 5s, which makes any event-loop stall >10s fatal to the connection.\n // Defaulted here rather than per service so every deployed service converges\n // on the same interval on its next release.\n heartbeatInterval = DEFAULT_AMQP_HEARTBEAT_SECONDS,\n connectionOptions,\n name,\n devOverlay = '',\n maxMessageSize,\n onConnectionStateChange,\n ...rest\n }: ConnectionOptions & { onConnectionStateChange?: ConnectionStateListener },\n messageHandler: MessageHandler<V>,\n) {\n const passthroughByteReferences =\n (rest as PrivilegedConnectionOptions).passthroughByteReferences ?? false\n // A non-generator handler's result path already refuses callbacks: its\n // registry entries are deleted the moment the message settles, which for a\n // returning handler is immediately. Same rule for render props — this is the\n // one place it is decided, and it is a property of the handler, not of a\n // message. (Kept separate from the narrowing call in the consume loop, whose\n // job is to type the handler.)\n const canRegisterCallbacks = isMessageHandlerGenerator(messageHandler)\n const baseQueue = `${url.username}@${version}`\n const queue = devOverlay\n ? `${baseQueue}-dev-overlay-${devOverlay}`\n : baseQueue\n const exchange = url.username\n const connection = connect(url.toString(), {\n connectionOptions: {\n ...connectionOptions,\n // Who we are, what we run, what we can decode — declared in the AMQP\n // connection frame so `ui/backend` knows it BEFORE the first dispatch.\n // amqp-connection-manager reuses these options on every reconnect, so\n // the announcement re-lands automatically. Merged LAST: the requence_*\n // keys are the contract and a caller may not shadow them.\n clientProperties: {\n ...connectionOptions?.clientProperties,\n ...buildServiceClientProperties({\n libVersion: libVersion(),\n serviceVersion: version,\n name,\n devOverlay: Boolean(devOverlay),\n }),\n },\n },\n heartbeatIntervalInSeconds: heartbeatInterval,\n })\n\n // amqp-connection-manager auto-reconnects, but without a listener a mid-\n // processing disconnect is completely silent: the raw amqplib channel that an\n // in-flight handler closed over is torn down, and the broker requeues every\n // unacked delivery. Surface it so the drop is at least observable.\n connection.on('disconnect', ({ err }: { err?: Error }) => {\n if (!silent && err) {\n logger.error('Requence AMQP connection lost:', err.message)\n }\n onConnectionStateChange?.({ connected: false, err })\n })\n\n // A reconnect fires 'connect' again, but the connectedPromise's listener has\n // already unsubscribed, so recovery was previously invisible. Track whether\n // we have connected before to distinguish the initial connect from a\n // reconnect: log the recovery (mirroring the loss above) and surface it so\n // the caller can flip its state back. Fires for the initial connect too;\n // callers treat `connected: true` idempotently.\n let hasConnected = false\n connection.on('connect', () => {\n if (hasConnected && !silent) {\n logger.info('Requence AMQP reconnected')\n }\n hasConnected = true\n onConnectionStateChange?.({ connected: true })\n })\n\n const connectedPromise = new Promise<void>((resolve, reject) => {\n const unsubscribe = () => {\n clearTimeout(timeout)\n connection.removeListener('connect', handleConnect)\n connection.removeListener('connectFailed', handleConnectFailed)\n }\n\n const timeout = setTimeout(() => {\n handleConnectFailed({\n err: new RequenceConnectionError('Requence connection timeout'),\n })\n }, connectionTimeout)\n\n const handleConnect = () => {\n unsubscribe()\n resolve()\n }\n\n const handleConnectFailed = ({ err }: { err: Error }) => {\n unsubscribe()\n if (\n err.message.startsWith(\n 'Handshake terminated by server: 403 (ACCESS-REFUSED)',\n )\n ) {\n reject(new RequenceConnectionError('Invalid service credentials'))\n } else {\n reject(err)\n }\n }\n\n connection.addListener('connect', handleConnect)\n connection.addListener('connectFailed', handleConnectFailed)\n })\n\n const connectionId = crypto.randomUUID()\n // The dev session this connection belongs to (#108), or `''` outside dev mode.\n //\n // What every surface this connection draws is stamped with, and what a rebuild\n // names to find them again. Scoped to the **session** rather than the\n // connection precisely so it survives the dev process being restarted: the\n // service, the version it overlays and the developer's token are all still the\n // same afterwards, so the surfaces drawn a moment before the restart are still\n // this session's.\n //\n // The token is hashed rather than carried, because this id comes to rest in\n // ui/backend's `task_surface` and a dev overlay key is a personal access token.\n // The service and version stay readable, which is what makes a stored session\n // id diagnosable at all.\n const devSession = devOverlay\n ? `${baseQueue}#${createHash('sha256').update(devOverlay).digest('hex').slice(0, 16)}`\n : ''\n // Derived from the queue this connection actually consumes, overlay suffix\n // included — NOT from the base name. The operator builds the routing key as\n // `service-<node.name>@<node.version>-backchannel-<connectionId>`, and in a\n // dev session ui/backend has rewritten that node's version to\n // `<version>-dev-overlay-<devKey>` (which is how the dispatch reaches this\n // worker in the first place). Anchoring to the base name instead made every\n // inbound backchannel message of a dev-mode service unroutable — the `stop`\n // that terminates a CONTINUOUS generator and, since surfaces, every callback\n // invocation. The unroutable publish then came back through the alternate\n // exchange and was read as a dead connection, so a click on a perfectly live\n // surface killed it (D5's detect-on-interaction, on a false premise).\n const backchannelQueue = `${queue}-backchannel-${connectionId}`\n // Components whose source has already left this connection, keyed\n // `<taskId>:<hash>`. ui/backend stores bundles hash-addressed and that row\n // outlives every render, so only the first render of a component **into a\n // given task** carries the ≤1 MiB source; later ones carry the hash alone.\n // There is no channel to ask ui/backend what it already has (D16: an unknown\n // hash-only render is an error state), so this set is the whole answer.\n //\n // The task is in the key, and not just the hash, because bundle retention is\n // per-task (D19): the last-referent sweep removes a bundle once NO task\n // references it, and a worker that stays connected for days can outlive every\n // task that referenced its component. Keyed by hash alone, every later render\n // from that connection would carry the hash of a bundle nobody stores —\n // permanently, self-healing only on reconnect, with nothing in the retention\n // path able to fix it (at the moment of the sweep the bundle genuinely has no\n // referents). Keyed by task, the first render into any task always carries the\n // source, so the state the sweep can produce is exactly the state a fresh key\n // repairs. It costs one ≤1 MiB transfer per task per component rather than one\n // per connection.\n //\n // Residual, accepted with D16: this records that the source was *published*,\n // not that it was ingested. If the operator discards that render (a\n // superseded epoch after a re-dispatch), a later render of the same component\n // into the same task carries no source and its surface stays an error state\n // until the process reconnects.\n const sentComponents = new Set<string>()\n const generatorTerminators = new Map<string, (reason: string) => void>()\n // Each registry entry keeps the invocation dispatcher of the message that\n // registered the callback. Entries are deleted when that message settles,\n // so a stored dispatcher is live exactly as long as its callback is — this\n // is what lets a nested function in a callback argument reconstruct as\n // invokable (chaining): its invocations egress through the registering\n // message's context (results stream → operator → peer backchannel).\n const callbacks = new Map<\n string,\n {\n callback: (...args: any[]) => void\n onCallbackInvoke: CallbackIngressContext['onCallbackInvoke']\n }\n >()\n\n // What tells an author their registry is growing, and which `yield` is doing\n // it (#151). Connection-scoped because one of its two counters is: a worker\n // holding fifty tasks at nine hundred callbacks each is the case no single\n // delivery can see. `callbacks.size` rather than a count of its own, so\n // rendered handler props — the same registry, the same growth — are in it.\n const callbackGrowth = createCallbackGrowthWatch({\n service: baseQueue,\n devOverlay: Boolean(devOverlay),\n connectionCount: () => callbacks.size,\n // The service's own log, like every other author mistake in this file. Not a\n // task update: the only person who can fix this is the one writing the\n // service, and they are reading this process's output.\n warn: (text) => logger.warn(text),\n })\n\n // Backchannel ingress (concept invariant 2): a callback argument was\n // egress-transformed by the invoking side (files/streams → references,\n // oversized values → claim-checks), so it must rehydrate here before\n // reaching user code. Connection-scoped: the callback owner is typically a\n // CONTINUOUS service whose lifetime differs from any single message, so no\n // per-message signal applies. `onCallbackInvoke` is supplied per call from\n // the registry entry, so nested functions reconstruct invokable.\n // Passthrough consumers (the logic runtime's guest channel) keep byte/callback\n // references raw here too — claim-checks still resolve, but files/streams/\n // callbacks reach the registered callback as their JSON-safe wire objects so\n // they can cross the guest's process boundary.\n const backchannelInbound = createInboundBoundary(\n passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {},\n )\n\n const channelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n if (devOverlay) {\n await channel.assertQueue(queue)\n await channel.bindQueue(queue, 'service', queue)\n }\n await channel.checkExchange(exchange)\n await channel.checkExchange(`${exchange}-retry`)\n await channel.checkQueue(queue)\n await channel.prefetch(prefetch)\n\n await channel.assertQueue(backchannelQueue, {\n exclusive: true,\n })\n\n await channel.bindQueue(backchannelQueue, 'service', backchannelQueue)\n\n await channel.consume(\n backchannelQueue,\n async (message) => {\n const result = backchannelMessageSchema.safeParse(message)\n\n if (!result.success) {\n return\n }\n\n const backchannelMessage = result.data\n\n switch (backchannelMessage.payload.type) {\n case 'stop': {\n generatorTerminators.get(backchannelMessage.messageId)?.(\n 'task stopped',\n )\n break\n }\n case 'callback': {\n const { surface } = backchannelMessage.payload\n const { taskId } = backchannelMessage\n // Reportable only when both halves are here: an interaction names\n // the surface it came from, and a report needs the task to be\n // routed. A peer callback names neither, and its failures belong to\n // its own live message.\n const report =\n surface && taskId\n ? (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n : () => {}\n\n const entry = callbacks.get(backchannelMessage.payload.callbackId)\n if (!entry) {\n // Said out loud rather than dropped (#106). This is where a\n // connection-bound surface handler lands, and an entry that is\n // gone means the message that registered it has settled — so the\n // click behind it did nothing and nobody was told. Unconditional\n // for the reason the durable arm's misses are: `silent`\n // suppresses connection noise, not a lost interaction. There is\n // no request left to fail (the mutation returned *accepted* long\n // before) and no failure channel here — the backchannel consumes\n // with noAck, outside any message context. For an *interaction*\n // there is now one more place to put it (#107): the surface.\n logger.warn(\n `Requence: dropped an invocation of callback |${backchannelMessage.payload.callbackId}| — nothing is registered under it, so the message that registered it has settled`,\n )\n report(\n 'the process that drew this surface has finished with it, so nothing ran the handler',\n )\n break\n }\n let arg: unknown\n try {\n arg = await backchannelInbound(backchannelMessage.payload.arg, {\n onCallbackInvoke: entry.onCallbackInvoke,\n })\n } catch (error) {\n // The backchannel consumes with noAck and outside any message\n // context, so a failed rehydration has no failure channel.\n // Never hand user code a raw reference — log and drop the\n // invocation instead.\n logger.warn(\n `dropped callback invocation |${backchannelMessage.payload.callbackId}|: argument rehydration failed`,\n error instanceof Error ? error.message : error,\n )\n report(\n 'the interaction could not be delivered: its argument could not be read',\n )\n break\n }\n try {\n // Awaited so an async handler's rejection is caught here rather\n // than becoming an unhandled rejection in the consume callback —\n // which, `noAck` and outside any message context, was the one way\n // a thrown handler could take the whole process down.\n await entry.callback(arg)\n } catch (error) {\n logger.error(\n `Requence: callback |${backchannelMessage.payload.callbackId}| threw:`,\n error instanceof Error\n ? (error.stack ?? error.message)\n : error,\n )\n report(`the handler failed: ${errorText(error)}`)\n }\n break\n }\n }\n },\n {\n noAck: true,\n },\n )\n },\n })\n\n // ChannelWrapper is an EventEmitter; an unhandled 'error' would otherwise\n // propagate. Observe it rather than letting it surface as an uncaught error.\n channelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP channel error:', err.message)\n }\n })\n\n /**\n * Say on the surface that this process could not run an interaction (#107).\n *\n * The only feedback channel an interaction has once it has been accepted. The\n * mutation behind a click returns *accepted* long before the invocation reaches\n * here — for a durable handler, possibly a redeploy before — so there is no\n * request to fail, no message to abort, and for a durable handler no connection\n * the viewer ever had. What is left is the surface itself, which the viewer is\n * still looking at.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id or index: a handler invocation is not a dispatch of the\n * operator's, so it has no message to be a result FOR, which is exactly why the\n * operator answers this header before everything else on that path.\n *\n * Fire-and-forget, and never fatal: this is the report of a failure, and a\n * failure to report it must not become a second one. Unconditional, `silent`\n * included, for the reason every miss here is logged unconditionally — `silent`\n * suppresses connection noise, not a lost interaction.\n */\n const reportInteractionFailure = (params: {\n taskId: string\n surface: string\n message: string\n }) => {\n void channelWrapper\n .publish(\n exchange,\n '',\n Buffer.from(\n JSON.stringify({\n surface: params.surface,\n // Truncated at the source as well as in the update schema: what keeps\n // this publish bounded is the cut made before it, and a thrown error's\n // message is author text of no bounded length.\n message: params.message.slice(\n 0,\n MAX_SURFACE_INTERACTION_ERROR_CHARS,\n ),\n }),\n ),\n {\n contentType: 'application/json',\n persistent: true,\n headers: {\n taskId: params.taskId,\n [SURFACE_INTERACTION_ERROR_HEADER]: true,\n },\n },\n )\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not report a failed surface interaction on |${params.surface}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n /**\n * The dev loop (#108): a rebuilt component is a **bundle swap**, not a render.\n *\n * A rebuild changes which bytes the frame imports and nothing else, so nothing\n * about the render that drew a surface is an input here — not its props, not\n * its handlers, not whether the message that published it is still unsettled.\n * That last one is what the re-issue this replaced could never get past: a\n * deferring handler returns at the defer, taking its callback registry with it,\n * so a deferred form could not be iterated on without starting a new task for\n * every edit. Now the notice names the session and the component, ui/backend\n * repoints the rows, and every surface — a live panel, a deferred form, one\n * on a task that finished last week — swaps identically.\n *\n * Published on the ordinary result exchange with a marker header and **no**\n * correlation id, index or task: a rebuild is not a result for any dispatch of\n * the operator's, which is why the operator answers this header before it looks\n * for either.\n *\n * Fire-and-forget and never fatal, like the failure report above: the dev loop\n * is an addition to a running service, not a reason for one to fall over.\n */\n const publishBundleSwap = (ui: MutableRequenceUI) => {\n const swap: UiRebuild = {\n devSession,\n uiId: ui.id,\n hash: ui.hash,\n // Always, unlike a render's: this hash is new to everyone by definition,\n // and the surfaces this repoints are exactly the ones that would otherwise\n // name a bundle nobody stored.\n source: ui.source,\n }\n\n void channelWrapper\n .publish(exchange, '', Buffer.from(JSON.stringify(swap)), {\n contentType: 'application/json',\n persistent: true,\n headers: { [UI_REBUILD_HEADER]: true },\n })\n .then(() => {\n if (!silent) {\n logger.info(\n `Requence: component |${ui.id}| rebuilt (${ui.hash.slice(0, 12)}) — swapped on every surface of this dev session`,\n )\n }\n })\n .catch((error: unknown) => {\n logger.error(\n `Requence: could not publish the rebuild of |${ui.id}|:`,\n error instanceof Error ? error.message : error,\n )\n })\n }\n\n // Only a dev-mode connection turns the watch on; `createUI` itself registers\n // unconditionally and starts nothing.\n const stopUIWatch = devSession\n ? watchUIRebuilds({\n onRebuild: publishBundleSwap,\n // The watch is process-global; `silent` is this connection's. It\n // reports, we decide.\n onWarning: (warning) => {\n if (!silent) {\n logger.warn(warning)\n }\n },\n })\n : undefined\n\n /**\n * Runs one durable handler invocation (#103): resolve `(uiId, path)` against\n * the components this process registered at module scope, and call the\n * function sitting there in that UI's default props.\n *\n * No context is injected, deliberately — a durable handler reaches whatever it\n * needs (`service.act()`, its own stores) through its own closure, which is\n * the same closure a module-scope function has in any other process of this\n * version. That is what \"durable\" means here.\n *\n * Every miss is **said out loud** rather than dropped: the click that produced\n * it is long gone, the mutation behind it returned *accepted*, and this\n * process is the only party that can tell an author their component named\n * something that does not exist. Unconditional, `silent` included: `silent`\n * suppresses connection noise, not a lost interaction.\n *\n * And every miss that can name a surface is also **recorded on it** (#107),\n * which is the half a viewer can see: this process's stderr is nowhere near the\n * person who pressed the button, least of all for the case that motivated it — a\n * durable handler running minutes later, in an instance the viewer never had a\n * connection to. A malformed payload is the one exception, and necessarily: it\n * is the only miss that cannot say which surface it was for.\n */\n const runHandlerInvocation = async (raw: unknown) => {\n const parsed = surfaceHandlerInvocationSchema.safeParse(raw)\n if (!parsed.success) {\n logger.error(\n 'Requence: dropped a malformed surface handler invocation:',\n parsed.error.message,\n )\n return\n }\n const { taskId, surface, uiId, path, arg } = parsed.data\n const where = `UI |${uiId}| prop |${path.join('.') || '<root>'}| (task |${taskId}|)`\n const report = (message: string) =>\n reportInteractionFailure({ taskId, surface, message })\n\n const ui = findUIById(uiId)\n if (!ui) {\n logger.error(\n `Requence: no component registered as |${uiId}| — dropped a handler invocation for ${where}`,\n )\n report(\n `the service has no component registered as \"${uiId}\", so nothing ran the handler`,\n )\n return\n }\n\n // Resolved against the DEFAULTS, because that is the only place a durable\n // handler can have been written: a function in a render's own props closes\n // over that render's process and never gets a durable reference. An empty\n // path would name the defaults object itself, which is never a function.\n const handler: unknown = getByPath(\n ui.defaults as Record<string, unknown> | undefined,\n path,\n )\n if (typeof handler !== 'function') {\n logger.error(\n `Requence: no handler at ${where} — the component's defaults have ${\n handler === undefined ? 'nothing' : typeof handler\n } there`,\n )\n report(\n `this component has no handler at \"${path.join('.') || '<root>'}\", so nothing ran`,\n )\n return\n }\n\n try {\n await (handler as (value: unknown) => unknown)(arg)\n } catch (error) {\n // Caught here rather than left to the consumer's own catch, which is one\n // frame too far out to know which surface this was: the *report* needs the\n // parsed invocation. Rethrown so that frame still logs the stack and acks.\n report(`the handler failed: ${errorText(error)}`)\n throw error\n }\n }\n\n // The per-version handler queue, consumed alongside the dispatch queue and on\n // a channel of its own: a durable invocation is not a dispatch, and sharing\n // the dispatch channel would put it behind that channel's prefetch — so one\n // long-running LINEAR message would stall every click on the version.\n //\n // Competing consumers by design: a durable handler belongs to the service\n // VERSION, so whichever instance is free serves it, and an invocation with no\n // instance running waits in the queue instead of being lost.\n const handlerQueue = serviceHandlerQueueName(queue)\n const handlerChannelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n // Asserted rather than checked, unlike the dispatch queue: ui/backend's\n // provisioner asserts it too (which is what makes it exist BEFORE any\n // instance runs, so an invocation can wait out a redeploy), but a service\n // must not fail to start against a broker whose version assert has not\n // caught up. Both sides declare the same shared literal, because a\n // mismatch is a 406 that kills this channel. In a dev session the queue is\n // this overlay's own, so nobody else asserts it at all, and these\n // arguments are the only ones it ever gets.\n //\n // The TTL is what stops the queue being a mailbox (#116): an invocation\n // nobody consumes expires instead of running whenever someone next\n // deploys, and dead-letters back to the operator so the viewer is told.\n await channel.assertQueue(handlerQueue, SURFACE_HANDLER_QUEUE_ARGUMENTS)\n await channel.bindQueue(handlerQueue, 'service', handlerQueue)\n await channel.prefetch(prefetch)\n await channel.consume(handlerQueue, async (message) => {\n if (!message) {\n return\n }\n try {\n await runHandlerInvocation(JSON.parse(message.content.toString()))\n } catch (error) {\n // A throwing handler is the author's bug and there is no request left\n // to fail (#107 puts it back on the surface). Reported and acked: a\n // requeue would rerun a side-effecting handler forever.\n logger.error(\n 'Requence: surface handler threw:',\n error instanceof Error ? (error.stack ?? error.message) : error,\n )\n }\n safeAck(channel, message)\n })\n },\n })\n\n /**\n * Runs the callback a durable invocation names (#147).\n *\n * It is given the bound data, the graph's argument and the node's static\n * configuration, and nothing else — no message, no connection, no task\n * context. That is the whole of what makes it durable: this instance may have\n * been started long after the one that emitted the reference exited.\n */\n async function runDurableCallbackInvocation(payload: unknown) {\n const parsed = durableCallbackInvocationSchema.safeParse(payload)\n if (!parsed.success) {\n // Unconditional, like the misses below: `silent` suppresses connection\n // noise, not an invocation nobody will ever hear about again.\n logger.error(\n 'Requence: dropped a malformed durable callback invocation — it does not name a callback this build can run',\n )\n return\n }\n\n const { name, bound, arg, configuration, taskId, nodeId } = parsed.data\n const registration = findDurableCallback(name)\n if (!registration) {\n // Loud, and it says which run is affected: there is no request left to\n // fail — the graph called the callback and moved on — so the only way this\n // is ever seen is if somebody says it. A name that resolves to nothing is\n // a deployed version that no longer declares what an emitted reference\n // names, which is exactly the case worth hearing about.\n throw new Error(\n `no durable callback registered as \"${name}\" — a reference naming it was emitted by node ${nodeId} of task ${taskId}, and this version declares none`,\n )\n }\n\n await registration.handler(\n arg,\n durableCallbackContext(name, bound, configuration),\n )\n }\n\n // The per-version callbacks queue, alongside the handler queue and for the\n // same reasons (#147): its own channel, so a durable invocation never queues\n // behind a long-running LINEAR dispatch; competing consumers, so whichever\n // instance of the version is free serves it; and a queue rather than a live\n // connection, so an invocation waits out a redeploy instead of dying with the\n // process that emitted the reference.\n const callbackQueue = serviceCallbackQueueName(queue)\n const callbackChannelWrapper = connection.createChannel({\n async setup(channel: ConfirmChannel) {\n // Asserted, not checked, and from the literal both parties share — see the\n // handler queue above: the provisioner's assert is what makes the queue\n // exist before any instance runs, this one is what keeps a service\n // startable against a broker that assert has not reached, and a mismatch\n // between the two is a 406 that kills this channel.\n await channel.assertQueue(callbackQueue, DURABLE_CALLBACK_QUEUE_ARGUMENTS)\n await channel.bindQueue(callbackQueue, 'service', callbackQueue)\n await channel.prefetch(prefetch)\n await channel.consume(callbackQueue, async (message) => {\n if (!message) {\n return\n }\n try {\n await runDurableCallbackInvocation(\n JSON.parse(message.content.toString()),\n )\n } catch (error) {\n // Acked either way: a requeue would rerun a side-effecting callback\n // forever, and a callback is the one thing a graph asked for\n // explicitly.\n logger.error(\n 'Requence: durable callback threw:',\n error instanceof Error ? (error.stack ?? error.message) : error,\n )\n }\n safeAck(channel, message)\n })\n },\n })\n\n callbackChannelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP callback channel error:', err.message)\n }\n })\n\n handlerChannelWrapper.on('error', (err: Error) => {\n if (!silent) {\n logger.error('Requence AMQP handler channel error:', err.message)\n }\n })\n\n const publish = ({\n data,\n outputName,\n messageId,\n priority,\n ...headers\n }: {\n index: number\n data?: unknown\n outputName?: string | null\n messageId: string\n taskId: string\n priority?: number\n version: string\n debugMethod?: 'log' | 'warn' | 'info' | 'error'\n debug?: boolean\n // Marks a `context.render` payload (component + props + surface). Like\n // `debug`, it is a side-channel the operator forwards as a task update\n // rather than graph output — but it rides the ordered dispatch buffer, so\n // two renders of one surface can never be re-ordered into a stale one.\n render?: boolean\n connectionId?: string\n callbackId?: string\n // The durable arm's address (#150): the declared name and the node whose\n // version serves it, in place of the connection pair above. The operator\n // routes on which of the two is present.\n callbackName?: string\n callbackNodeId?: string\n // Which node published an invocation — see `invocationHeaders`. Not an\n // address: it is what lets the operator name the invoking node without a\n // message record that may already be gone.\n invokingNodeId?: string\n propertyPath?: (string | number)[]\n begin?: boolean\n deferred?: boolean\n done?: boolean\n // Privileged result protocol: `overwrite` marks a data message whose\n // value replaces (instead of merges into) downstream aggregation. The\n // operator honors it only for privileged nodes. Flows through via\n // `...headers`.\n overwrite?: boolean\n // Per-attempt id: identifies this consume-handler invocation so the\n // operator can fence a superseded attempt's stragglers on the same\n // messageId. Flows through via `...headers`.\n epoch?: string\n // Who ran this node, stamped on the `begin` publish ONLY (see\n // `buildServiceIdentityHeaders`). The operator freezes these into the\n // NODE_START update; they are display-only and nothing branches on them.\n libVersion?: string\n serviceName?: string\n capabilities?: string\n }) => {\n const { body, contentType } = encodeWireBody(\n data ?? null,\n messageCodecs.get(messageId) ?? 'json',\n )\n\n // Guard the body size before it hits the broker. An oversized publish makes\n // RabbitMQ drop the whole connection, which amqplib reports as a generic\n // \"channel closed\" for every in-flight message — impossible to attribute to\n // size after the fact. Rejecting here yields a precise, catchable error and\n // leaves the connection intact for other messages.\n if (body.byteLength > maxMessageSize) {\n return Promise.reject(\n new PayloadTooLargeError(body.byteLength, maxMessageSize),\n )\n }\n\n return channelWrapper.publish(exchange, '', body, {\n correlationId: messageId,\n contentType,\n persistent: true,\n priority,\n headers: {\n outputName: outputName ?? null,\n connectionId,\n ...headers,\n },\n })\n }\n\n /**\n * Everything a publish on behalf of one message needs, and the whole of what\n * differs between the two publish paths — the main path's consume handler and an\n * `act()` call. Shared by {@link buildSendApi} and {@link buildRender} so the\n * two cannot drift apart: they publish for the same message, through the same\n * boundary, on the same index counter.\n *\n * `epoch`/`priority` are main-path-only (an `act()` call is not a consume\n * attempt) and are omitted from the published headers when absent, keeping the\n * deferred path's output byte-identical to what it always was.\n */\n type PublishDeps = {\n outbound: OutboundBoundary\n registerCallback: (\n callback: (...args: any[]) => void,\n // Where the function was written, for the growth warning (#151) — the\n // walk's path for a callback, the payload path for a handler prop.\n path: ReadonlyArray<string | number>,\n ) => {\n sourceId: string\n callbackId: string\n }\n taskId: string\n messageId: string\n nextIndex: () => number\n epoch?: string\n priority?: number\n // act() only: wait for the deferring message's own processing to finish.\n gate?: () => Promise<void>\n }\n\n // The privileged send API (unit 05 headers), shared by the main-path handler\n // context and act()'s ActorApi: imperative data publishes through the\n // caller's outbound boundary, enrolled in its ledger so `settle()` gates the\n // done marker on them — a final emission mechanically flushes before `done`.\n const buildSendApi = (deps: PublishDeps) => {\n const base = {\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n ...(deps.priority === undefined ? {} : { priority: deps.priority }),\n }\n return {\n async sendToOutput(\n outputName: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: outputName as string | null,\n onCallback: deps.registerCallback,\n }),\n outputName: outputName as string | null,\n // only set when requested — omitted publishes stay identical\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n async send(data: unknown, options?: { overwrite?: boolean }) {\n await deps.gate?.()\n deps.outbound.track(\n publish({\n index: deps.nextIndex(),\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data: await deps.outbound.send(data, {\n outputName: null,\n onCallback: deps.registerCallback,\n }),\n ...(options?.overwrite ? { overwrite: true } : {}),\n ...base,\n }),\n )\n },\n }\n }\n\n // The render publish, shared by `context.render` on the main path and\n // `send.render` inside `act()` (#70). Everything that differs between the two\n // paths is a dep — the index counter, the callback registrar, the attempt\n // headers, and act()'s gate on the deferring message's own processing — so a\n // surface behaves identically whoever published it, which is what makes the\n // dev loop, the hash bookkeeping and the liveness rule path-agnostic.\n const buildRender = (deps: PublishDeps) => {\n /**\n * One function prop → one handler reference (#103). The **path decides the\n * lifetime**, because the path is where the function was written:\n *\n * - `defaults.*` — module scope. Any instance of this version can run it,\n * now or after a redeploy, so the reference names only the UI and the prop\n * and the invocation goes to the version's handler queue. Nothing is\n * registered here: there is nothing to keep alive, and that is the point.\n * - `props.*` — written at this render call, closing over the running\n * handler. Only this process can run it, so it registers in the publishing\n * message's own registry and dies with it, exactly as a callback does —\n * including the refusal on a LINEAR handler, whose registry entries are\n * gone the moment it returns.\n *\n * The path the reference carries is relative to the **props the component\n * receives**, not to the payload: the two layers fold into one object at\n * ingestion (#102), and the browser names a path in what it was served.\n */\n const registerSurfaceHandler = (\n ui: RequenceUI,\n handler: (...args: unknown[]) => void,\n payloadPath: ReadonlyArray<string | number>,\n ): SurfaceHandlerObject => {\n const [layer, ...path] = payloadPath\n if (layer === 'defaults') {\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'durable',\n uiId: ui.id,\n path,\n }\n }\n if (layer !== 'props') {\n // Only the two author-supplied layers can hold a function; anything\n // else is the SDK's own payload and a function there is a bug here.\n throw new Error(\n `a function in a render payload is only a handler under props or defaults (found at \"${payloadPath.join('.')}\")`,\n )\n }\n // Counted like a callback, under its full payload path: it is the same\n // registry and the same growth, and a render in a loop is the same mistake.\n // The `props.` prefix is what tells the author it was a handler prop (#151).\n const { sourceId, callbackId } = deps.registerCallback(\n handler,\n payloadPath,\n )\n return {\n __REQUENCE_type: SURFACE_HANDLER_TAG,\n lifetime: 'connection',\n uiId: ui.id,\n path,\n connectionId: sourceId,\n handlerId: callbackId,\n }\n }\n\n const renderSurface = (params: {\n ui: RequenceUI\n props: unknown\n surfaceId: string\n }): void => {\n // The index is taken NOW, not when the serialization resolves: the\n // operator dispatches a message's results in index order, so\n // allocating here is what makes two renders of one surface arrive\n // in call order. The cost is a hole in the buffer if the\n // serialization fails — moot for a message that settles: the publish is\n // tracked, so the same failure fails the node at the caller's settle gate.\n const index = deps.nextIndex()\n // Per (task, component), never per component: see `sentComponents`. The\n // hash is read at call time, not at registration, because the dev loop\n // rewrites it in place (D10).\n const sentKey = `${deps.taskId}:${params.ui.hash}`\n const withSource = !sentComponents.has(sentKey)\n if (withSource) {\n sentComponents.add(sentKey)\n }\n\n const issue = () =>\n deps.outbound\n .send(\n {\n // `id` rides along on every render, source-carrying or not: it is\n // what a dev-loop bundle swap addresses the surface by (#108), and\n // the surface row it lands on is last-write-wins.\n component: withSource\n ? {\n id: params.ui.id,\n hash: params.ui.hash,\n source: params.ui.source,\n }\n : { id: params.ui.id, hash: params.ui.hash },\n props: params.props,\n // Restated on every render, and deliberately NOT merged into the\n // props above (#102): the receiver folds them *under* the surface's\n // stored props, so a default is overridden by anything any render\n // of that surface ever said, while this render's props override\n // everything. Merging here — what #101 did — would collapse the two\n // ranks into one and let a default clobber an earlier override.\n //\n // Read off the handle at call time, like the hash, so the next\n // render after a rebuild carries whatever it changed them to.\n // Omitted entirely when the component declared none, keeping that\n // payload byte-identical to what it always was.\n ...(params.ui.defaults === undefined\n ? {}\n : { defaults: params.ui.defaults }),\n surfaceId: params.surfaceId,\n // Stamped on every surface this connection draws, so a rebuild can\n // find them again and repoint them (#108) — and find only them: a\n // developer's edit must never reach a production surface of the\n // same component. `null` outside a dev overlay, which is every\n // render a deployed service makes.\n devSession: devSession || null,\n },\n {\n outputName: null,\n // The claim-check may offload an oversized render — but\n // never the bundle: the operator parses `component.hash`\n // out of the body, so a reference there is unreadable.\n // Pinned rather than left to the sizes falling the right\n // way (props larger than the ≤1 MiB source), which only\n // holds while the task's threshold is the 4 MiB default.\n //\n // `defaults` is pinned because it is the base layer of the\n // surface's fold — offloaded, it would silently take every prop\n // the service never restates out of the surface, and every\n // durable handler with them. `props` stays the only candidate,\n // which is what makes an oversized render a named error state\n // rather than a broken surface.\n inlineKeys: ['component', 'defaults'],\n // Switches this send onto the render egress chain, where a\n // function is a surface handler rather than a peer callback\n // (#103). Which of the two lifetimes it gets is decided by where\n // it was written, which the walk reports as the path.\n onSurfaceHandler: (handler, path) =>\n registerSurfaceHandler(params.ui, handler, path),\n },\n )\n .then((data) =>\n publish({\n index,\n version,\n messageId: deps.messageId,\n taskId: deps.taskId,\n data,\n render: true,\n // Omitted rather than passed as `undefined` when absent, so\n // act()'s publishes keep the header set they always had.\n ...(deps.priority === undefined\n ? {}\n : { priority: deps.priority }),\n ...(deps.epoch === undefined ? {} : { epoch: deps.epoch }),\n }),\n )\n\n // The gate is awaited before the payload is built, never before the index\n // is taken — the slot has to be reserved in call order even when the\n // publish itself has to wait.\n const gated = deps.gate?.()\n deps.outbound.track(\n (gated ? gated.then(issue) : issue()).catch((error: unknown) => {\n // The source never left, so the next render of this component into\n // this task must carry it again — otherwise ui/backend would receive a\n // hash it has never seen and show an error state.\n if (withSource) {\n sentComponents.delete(sentKey)\n }\n throw error\n }),\n )\n }\n\n return renderSurface\n }\n\n channelWrapper.addSetup(async (channel: ConfirmChannel) => {\n channel.consume(queue, async (message) => {\n if (!message) {\n return\n }\n\n let publishIndex = 0\n let acked = false\n let terminated = false\n const registeredCallbackIds = new Set<string>()\n let resolveActiveMessage = () => {}\n // Captured for the finally block; header parsing now happens inside the\n // try so a malformed header goes through the error handling below instead\n // of throwing out of this async consumer as an unhandled rejection.\n let messageIdForCleanup: string | undefined\n // One epoch per consume-handler invocation (declared out here so the\n // catch-branch republishes can stamp it too). On redelivery/reconnect a\n // second invocation gets a fresh epoch, letting the operator tell the\n // attempts apart and fence the superseded one.\n const epoch = crypto.randomUUID()\n\n try {\n const { messageId, taskId, mode } = headerSchema.parse(message)\n messageIdForCleanup = messageId\n\n // The capability gate, ahead of everything the dispatch could ask of\n // this build — including its own decoding. A requirement stated in the\n // body would be unreadable exactly when it matters, so it rides in the\n // headers and is checked here, before `payloadSchema` touches the bytes.\n //\n // An empty requirement (every message published before this existed)\n // passes untouched.\n const unsupported = unsupportedCapabilities(\n readRequiredCapabilities(message.properties.headers),\n )\n if (unsupported.length > 0) {\n throw new UnsupportedCapabilityError(unsupported)\n }\n\n // Recorded before anything can publish, so every reply on this message —\n // including one from an error path — echoes the codec it arrived under.\n const dispatchCodec = wireCodecFromContentType(\n message.properties.contentType,\n )\n messageCodecs.set(messageId, dispatchCodec)\n\n let deferred = false\n let deferredReason: string | null = null\n\n const messageExecution = Promise.withResolvers<void>()\n activeMessages.set(messageId, messageExecution.promise)\n messageExecution.promise.then(() => {\n activeMessages.delete(messageId)\n })\n resolveActiveMessage = () => {\n messageExecution.resolve()\n }\n\n const payload = payloadSchema.parse(message)\n\n // The per-message abort controller is hoisted out of\n // createContextHelper so the outbound boundary can share its signal.\n const abortController = new AbortController()\n\n // Names the run in the warning (#151), so an author with several tasks\n // open knows which one to go and look at.\n const growth = callbackGrowth.forDelivery({ taskId })\n\n // One callback registrar for every egress sub-path (result, deferred\n // send, callback arg). Registered callbacks carry this message's\n // dispatcher so nested functions in their invocation arguments\n // reconstruct invokable (chaining).\n const registerCallback = (\n callback: (...args: any[]) => void,\n path: ReadonlyArray<string | number>,\n ) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n // After the entry is in, so the connection count the warning states is\n // the number this process is holding. Never refuses and never evicts:\n // a cap kills a legitimate long-lived handle at an arbitrary number\n // that nobody can set correctly.\n growth.record(path)\n return { sourceId: connectionId, callbackId }\n }\n\n // The component's single outbound boundary: owns ctx construction,\n // the background-upload ledger (done-gate) and the fail policy.\n // Fail-hard sends surface via outbound.settle() before the done\n // marker + ack; best-effort (log) sends degrade to warnings.\n const outbound = createOutboundBoundary({\n uploadUrl: payload.options.uploadUrl,\n streamUrl: payload.options.streamUrl,\n maxPayloadSize: payload.options.maxPayloadSize,\n maxFileSize: payload.options.maxFileSize,\n // What a durable callback reference emitted on this message is\n // addressed by (#150).\n nodeId: payload.nodeId,\n // Replies echo the dispatch codec, so the claim-check must measure\n // with it too — measured size == published size.\n wireCodec: dispatchCodec,\n signal: abortController.signal,\n warn: (msg, error) =>\n logger.warn(\n `${msg} (task ${taskId})`,\n error instanceof Error ? error.message : (error ?? ''),\n ),\n })\n\n // This message's single invocation egress: callback arguments are\n // real node output (they carry an outputName), so they go through the\n // same boundary as results — nested files offload, nested functions\n // become callbacks. The send + publish are tracked in the boundary's\n // ledger, so a failure fails the task at the settle gate. Used both\n // for callbacks arriving in this message's input (via\n // createContextHelper) and for callbacks this message registers\n // (chained invocations dispatched from the backchannel).\n const dispatchInvocation = (\n invocation: CallbackObject & { arg: unknown },\n ) => {\n outbound.track(\n outbound\n .send(invocation.arg, {\n outputName: invocation.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data: invocationPayload(invocation, data),\n outputName: invocation.outputName,\n propertyPath: invocation.propertyPath,\n ...invocationHeaders(invocation, payload.nodeId),\n epoch,\n }),\n ),\n )\n }\n\n // This message's publish context: one index counter, one boundary, one\n // attempt. Shared by the privileged send API below and by the render.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n epoch,\n priority: message.properties.priority,\n }\n\n const onRender = buildRender({\n ...publishDeps,\n // The one deliberate difference on this path: a function written at\n // the render call becomes a reference to THIS message's registry, so\n // it is live exactly as long as the message — and a non-generator\n // handler cannot hold one at all, because its registry entries go the\n // moment it returns.\n //\n // A function in the UI's DEFAULTS never reaches here: it is durable,\n // registers nothing, and is therefore the one handler a LINEAR\n // handler can publish — which is exactly what lets a form outlive the\n // process that drew it (#103).\n //\n // Worded for the surface author rather than reusing the result path's\n // callback wording: what this catches is a function in RENDER PROPS,\n // and naming the fix matters more than naming the rule. The tempting\n // shape is a promise the render's own handler resolves — which would\n // hold the message open for a human-speed wait, on an unacked\n // delivery a redeploy hands to another instance. `defer` plus a\n // durable default is that same form, written so it survives.\n registerCallback: canRegisterCallbacks\n ? registerCallback\n : () => {\n throw new Error(\n 'A LINEAR version handler may not register function props — the registration dies when the handler returns. To wait for a viewer, call context.defer() and declare the handler in the UI defaults instead: a durable handler outlives this process.',\n )\n },\n })\n\n const [extendedContext, terminatePromise] = (await createContextHelper({\n taskId,\n // Rehydration (FileObject/StreamObject -> RequenceFile/RequenceStream)\n // happens inside createContextHelper via its inbound boundary — the\n // signal-aware pass whose instances reach the handler.\n input: payload.input,\n configuration: payload.configuration,\n abortController,\n passthroughByteReferences,\n // The whole of what a node needs to address a slot (#210): the two\n // opaque fields ui/backend minted for this tree, plus the two ids the\n // dispatch already carries. The service composes no address and holds\n // no store password — the store builds the address from the\n // capability.\n store: createStore({\n url: payload.options.storeUrl,\n signature: payload.options.storeSignature,\n taskId,\n nodeId: payload.nodeId,\n configuration: payload.configurationEval,\n }),\n // Privileged send API on the handler ctx (runtime-only, hidden from\n // the ContextHelper type): shares this message's outbound boundary,\n // publishIndex counter, epoch and priority.\n sends: {\n ...buildSendApi(publishDeps),\n // Passthrough consumers hold raw callback wire refs — this is\n // their invocation egress, routed through the same\n // dispatchInvocation as a rehydrated callback call (fire-and-\n // forget; the outbound ledger settles the publish).\n invokeCallback: (ref, arg) => dispatchInvocation({ ...ref, arg }),\n options: payload.options,\n },\n onLog(debugMethod, data) {\n // Best-effort: a debug log must never fail the task. The boundary\n // sanitizes the payload (functions/opaque instances → labels),\n // degrades offload failures to warnings, and keeps the done-gate\n // waiting for the upload without letting it fail the task. On a\n // transform error it resolves `undefined` and nothing is published.\n void outbound.send(data, { bestEffort: true }).then((mapped) => {\n if (mapped === undefined) {\n return\n }\n publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: mapped,\n debugMethod,\n priority: message.properties.priority,\n debug: true,\n epoch,\n })\n })\n },\n onRender,\n onDefer(reason) {\n deferred = true\n deferredReason = reason || null\n\n return obfuscate(\n taskId,\n messageId,\n payload.options.uploadUrl ?? '',\n payload.options.streamUrl ?? '',\n payload.options.maxPayloadSize?.toString() ?? '',\n payload.options.maxFileSize?.toString() ?? '',\n payload.nodeId ?? '',\n )\n },\n onCallback: dispatchInvocation,\n })) as unknown as [\n MessageHandlerContext<V>,\n PromiseWithResolvers<string>,\n ]\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n priority: message.properties.priority,\n begin: true,\n epoch,\n // The one stamp per node execution: this build, this box. It becomes\n // the NODE_START update's `service`, which is written once and never\n // re-derived — so anything absent here is lost for that run.\n ...buildServiceIdentityHeaders({\n libVersion: libVersion(),\n name,\n }),\n })\n\n if (isMessageHandlerGenerator(messageHandler)) {\n if (mode === 'CONTINUOUS') {\n // CONTINUOUS: ACK immediately, operator watchdog supervises. A\n // LINEAR message stays unacked until done — prefetch keeps\n // bounding concurrent work and the broker redelivers on a crash.\n safeAck(channel, message)\n acked = true\n }\n\n const generator = messageHandler(extendedContext)\n const terminationPromise = Promise.withResolvers<typeof abortSymbol>()\n generatorTerminators.set(messageId, (reason) => {\n terminated = true\n // Suppress native AbortError that may reject generator.return() when\n // context.terminated.signal fires and cancels a pending await inside\n // the generator (e.g. node:timers/promises setTimeout with { signal }).\n ;(generator.return() as Promise<unknown>).catch(\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return\n }\n throw error\n },\n )\n terminationPromise.resolve(abortSymbol)\n terminatePromise.resolve(reason)\n })\n\n await handlerStorage.run(\n extendedContext as ContextHelper,\n async () => {\n while (true) {\n type IterResult = IteratorResult<\n MessageHandlerReturnValue<V, null>,\n void | MessageHandlerReturnValue<V, null>\n >\n // Catch native AbortError from context.terminated.signal so\n // generator implementations don't need their own try/catch.\n const nextPromise = Promise.resolve(generator.next()).then(\n (r) => r,\n (error: unknown) => {\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n return { value: undefined, done: true } as IterResult\n }\n throw error\n },\n )\n const next = await Promise.race([\n terminationPromise.promise,\n nextPromise,\n ])\n if (next === abortSymbol) {\n break\n }\n\n const { value: result, done } = next\n\n if (deferred) {\n deferred = false\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n }\n\n const { value: rawValue, outputName } =\n unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: registerCallback,\n })\n\n if (!done || typeof value !== 'undefined') {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n\n if (done) {\n break\n }\n }\n },\n )\n } else {\n const result = await handlerStorage.run(\n extendedContext as ContextHelper,\n () => messageHandler(extendedContext),\n )\n const { value: rawValue, outputName } = unwrapOutputValue(result)\n const value = await outbound.send(rawValue, {\n outputName,\n onCallback: () => {\n throw new Error(\n 'callbacks can only be used in generator functions',\n )\n },\n })\n if (deferred && value) {\n logger.warn(\n 'returning a value in a deferred message resets the deferred status',\n )\n deferred = false\n }\n\n if (!deferred || value) {\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: value,\n priority: message.properties.priority,\n outputName,\n epoch,\n })\n }\n }\n\n await new Promise<void>((resolve, reject) => {\n setImmediate(async () => {\n try {\n // The boundary's settle gate: waits for every tracked background\n // upload/publish, then throws an AggregateError on any fail-hard\n // failure — which surfaces here and reaches the outer catch ->\n // exception republish -> throwServiceError -> failNode. The done\n // marker + ack only happen once every upload succeeded.\n if (!deferred) {\n await outbound.settle()\n }\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n data: deferredReason,\n priority: message.properties.priority,\n deferred,\n done: !deferred,\n epoch,\n })\n\n if (!acked) {\n safeAck(channel, message)\n }\n resolve()\n } catch (error) {\n reject(error)\n }\n })\n })\n } catch (error) {\n if (error instanceof SkipError) {\n if (!acked) {\n safeNack(channel, message)\n }\n return\n }\n if (error instanceof RetryError) {\n if (!acked) {\n safeAck(channel, message)\n }\n const properties: Options.Publish = {\n ...message.properties,\n expiration: error.delay || 1_000, // 1s\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n version, // to other services\n message.content,\n properties,\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to republish message for retry:',\n publishError,\n )\n }\n })\n\n return\n }\n\n // A refusal, not a failure: this box is the wrong one, the message is\n // fine. It goes back by REPUBLISHING to `<exchange>-retry`, never by\n // nacking, because a nack can carry no rejection count and a classic\n // queue offers none either — see `CAPABILITY_HEADER_KEYS.mismatch` in\n // `@requence/helpers/protocol` for the full argument, and this file's\n // spec, which pins it. The republish reaches the operator's error\n // consumer, which already counts attempts, delays and fails the node.\n if (error instanceof UnsupportedCapabilityError) {\n if (!silent) {\n logger.error(error.message)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n // The dispatch verbatim: a reroute re-dispatches these bytes, and\n // this build never decoded them.\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n [CAPABILITY_HEADER_KEYS.mismatch]: true,\n index: publishIndex++,\n 'error-message': error.message,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish capability mismatch message:',\n publishError,\n )\n }\n })\n\n return\n }\n\n if (error instanceof AbortError && error.message.length > 0) {\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', //back to operator\n error.message,\n {\n ...message.properties,\n contentType: 'text/plain',\n headers: {\n ...message.properties.headers,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error('Failed to publish abort message:', publishError)\n }\n })\n\n return\n }\n\n // Native AbortError thrown when context.terminated.signal fires\n // (e.g. node:timers/promises setTimeout with { signal: context.terminated.signal }).\n // Only suppress when actually in a terminated state — otherwise a\n // different AbortSignal caused the error and it should propagate.\n if (\n terminated &&\n error instanceof Error &&\n error.name === 'AbortError' &&\n !(error instanceof AbortError)\n ) {\n if (!acked) {\n safeAck(channel, message)\n }\n return\n }\n\n if (error instanceof Error) {\n if (!silent) {\n logger.error('Encountered an error inside service handler:')\n logger.error(error)\n }\n\n if (!acked) {\n safeAck(channel, message)\n }\n channelWrapper\n .publish(\n `${exchange}-retry`,\n 'operator', // back to operator\n message.content,\n {\n ...message.properties,\n headers: {\n ...message.properties.headers,\n version,\n exception: true,\n index: publishIndex++,\n 'error-message': error.message || 'error in service handler',\n },\n },\n )\n .catch((publishError: unknown) => {\n if (!silent) {\n logger.error(\n 'Failed to publish exception message:',\n publishError,\n )\n }\n })\n\n return\n }\n } finally {\n if (messageIdForCleanup) {\n generatorTerminators.delete(messageIdForCleanup)\n // Bounded with the delivery rather than left to accumulate. A publish\n // that outlives the handler — a deferred message's later send — then\n // falls back to JSON, which the operator decodes correctly off the\n // header. It loses the size win for that one message and nothing else:\n // degrading to JSON is always safe, which is why the fallback is JSON\n // and not \"the last codec we saw\".\n messageCodecs.delete(messageIdForCleanup)\n }\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n resolveActiveMessage()\n }\n })\n })\n\n const activeMessageKeys = new Set<string>()\n const api: ConnectionApi<V> = {\n close: async () => {\n stopUIWatch?.()\n await callbackChannelWrapper.close()\n await handlerChannelWrapper.close()\n await channelWrapper.close()\n await connection.close()\n },\n open: () => connectedPromise.then(() => api),\n\n async act(messageKey, actor) {\n if (activeMessageKeys.has(messageKey)) {\n throw new Error('a defer key can only be used once')\n }\n\n activeMessageKeys.add(messageKey)\n\n let publishIndex = 0\n const { taskId, messageId, ...options } =\n messageKeySchema.parse(messageKey)\n\n const activeMessage = async () => {\n if (activeMessages.has(messageId)) {\n await activeMessages.get(messageId)\n }\n }\n\n const registeredCallbackIds = new Set<string>()\n // The deferred path's own outbound boundary: its ledger replaces the\n // old donePromises/uploadErrors pair — errors are caught at\n // registration time (nothing sits unhandled during long generator\n // iteration) and surfaced by settle() after the loop.\n const outbound = createOutboundBoundary(options)\n // The same growth warning as the main path (#151): an `act()` call holds\n // its own registry and may iterate a generator of its own, so it can grow\n // one the same way.\n const growth = callbackGrowth.forDelivery({ taskId })\n const registerCallback = (\n callback: (...args: any[]) => void,\n path: ReadonlyArray<string | number>,\n ) => {\n const callbackId = crypto.randomUUID()\n registeredCallbackIds.add(callbackId)\n callbacks.set(callbackId, {\n callback,\n onCallbackInvoke: dispatchInvocation,\n })\n growth.record(path)\n return { sourceId: connectionId, callbackId }\n }\n\n // Deferred-path analogue of the main path's dispatchInvocation: chained\n // invocations of callbacks registered here egress through this deferred\n // message's context (no epoch, matching its other publishes).\n const dispatchInvocation = (\n invocation: CallbackObject & { arg: unknown },\n ) => {\n outbound.track(\n outbound\n .send(invocation.arg, {\n outputName: invocation.outputName,\n onCallback: registerCallback,\n })\n .then((data) =>\n publish({\n index: 0,\n version,\n taskId,\n messageId,\n data: invocationPayload(invocation, data),\n outputName: invocation.outputName,\n propertyPath: invocation.propertyPath,\n ...invocationHeaders(invocation, options.nodeId),\n }),\n ),\n )\n }\n\n // This act() call's publish context: its own index counter, its own\n // callback registry, its own active-message gate, and no attempt headers —\n // an acting process is not a consume attempt. Both the send API and the\n // render read it, so the two cannot disagree about which message they\n // publish for.\n const publishDeps: PublishDeps = {\n outbound,\n registerCallback,\n taskId,\n messageId,\n nextIndex: () => publishIndex++,\n gate: activeMessage,\n }\n\n const renderSurface = buildRender(publishDeps)\n\n const sendApi = {\n ...buildSendApi(publishDeps),\n // The live window a deferred node gets (#70): the same render as the\n // main path, publishing into the same last-write-wins surface — so a\n // re-attach after a restart replaces the stale one, with fresh callbacks\n // registered here rather than in a message context that no longer\n // exists. The lock against a second instance doing this concurrently is\n // the author's (D9); see `ConnectionApi.act`.\n render(\n ui: RequenceUI,\n props: unknown,\n renderOptions?: { surfaceId?: string },\n ) {\n // The default mirrors `context.render` in helpers.ts — the public\n // shape of a render is the same on both paths.\n renderSurface({\n ui,\n props,\n surfaceId: renderOptions?.surfaceId ?? DEFAULT_SURFACE_ID,\n })\n },\n async abort(error: string | Error) {\n await activeMessage()\n channelWrapper.publish(\n `${exchange}-retry`,\n 'operator',\n error instanceof Error ? error.message : error,\n {\n persistent: true,\n correlationId: messageId,\n expiration: 0,\n priority: 0,\n contentType: 'text/plain',\n headers: {\n taskId,\n index: publishIndex++,\n abort: true,\n },\n },\n )\n },\n }\n\n const result = await actor(sendApi as ActorApi<V>)\n\n if (\n result != null &&\n typeof result === 'object' &&\n (Symbol.asyncIterator in result || Symbol.iterator in result)\n ) {\n // Generator: iterate and send each yielded value\n const iterable = result as AsyncIterable<unknown> | Iterable<unknown>\n for await (const value of iterable) {\n if (value !== undefined) {\n await sendApi.send(value)\n }\n }\n } else if (result !== undefined) {\n await sendApi.send(result)\n }\n\n await new Promise((resolve) => setImmediate(resolve))\n await activeMessage()\n\n try {\n // Settle gate: waits while sends enqueue more sends, then throws an\n // AggregateError on any failed background upload or publish.\n await outbound.settle()\n } catch (error) {\n // Do not mark the message done with a dangling reference. Signal\n // failure over the deferred-path error channel (abort -> operator\n // fails the node) and throw so act()'s caller sees it too.\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n const first =\n error instanceof AggregateError && error.errors[0] instanceof Error\n ? error.errors[0]\n : error instanceof Error\n ? error\n : new Error(String(error))\n await sendApi.abort(first)\n activeMessageKeys.delete(messageKey)\n throw error\n }\n\n registeredCallbackIds.forEach((id) => callbacks.delete(id))\n\n await publish({\n index: publishIndex++,\n version,\n messageId,\n taskId,\n done: true,\n })\n\n activeMessageKeys.delete(messageKey)\n },\n }\n\n return api\n}\n",
|
|
19
19
|
"import { Buffer } from 'node:buffer'\n\nimport { Packr, addExtension } from 'msgpackr'\n\n/**\n * THE SHARED MSGPACK LAYER.\n *\n * Three things live here, and only these three:\n *\n * 1. `MSGPACK_EXTENSION_IDS` — the ONE allocation table for msgpack extension\n * type ids used anywhere in this repo.\n * 2. `packCommand` / `unpackCommand` — the AMQP task-command codec, shared by its\n * two parties: `@requence/task-builder` publishes, `@requence/operator`\n * consumes.\n * 3. `packWire` / `unpackWire` / `wireByteLength` — the high-volume AMQP wire\n * codec (service dispatch, service results, task updates). Its parties span\n * two languages, so unlike (2) it is a deliberately narrow, portable subset.\n *\n * It is its own subpath export (`@requence/helpers/msgpack`) so the msgpackr\n * dependency reaches only the packages that actually encode. Twelve packages\n * depend on `@requence/helpers`; most of them do not touch either codec and must\n * not carry a msgpack library into their bundle.\n *\n * Both codecs live in ONE module because `addExtension` is process-global (see\n * `MSGPACK_EXTENSION_IDS`). Splitting them would put the allocation table out of\n * sight of one of its two users, which is exactly the failure the table exists\n * to prevent.\n */\n\n/**\n * Extension type ids, allocated ONCE for the whole repo.\n *\n * **`addExtension` is process-global, not per-`Packr`.** Every instance in a\n * process shares one registry, so two codecs that pick the same id do not get two\n * namespaces — the second registration WINS and the first class silently decodes\n * as the second one. No error, no warning: a `NodeTree` comes back as a\n * `ReferenceCounter` and fails much later, somewhere unrelated. That is why the\n * numbers live in one table instead of next to each `addExtension` call.\n *\n * Ids 1 and 2 are also part of the stored Redis snapshot format, so renumbering\n * either one invalidates every live snapshot (a fleet-wide loud discard and\n * restart — there is no migration path, per the repo no-legacy-support policy).\n * Treat all of these as frozen; allocate a NEW number for anything new.\n */\nexport const MSGPACK_EXTENSION_IDS = {\n /** `@requence/operator`'s `ReferenceCounter` — snapshot path only. */\n referenceCounter: 1,\n /** `NodeTree` — snapshot path only; a command carries a `treeList`. */\n nodeTree: 2,\n /**\n * `URL` — registered below, because BOTH paths need it, and they need OPPOSITE\n * behaviour. See the registration for how one id serves both.\n */\n url: 3,\n} as const\n\n/**\n * Set for the duration of a `packWire` call, so the process-global `URL` extension\n * below can tell which codec is asking. `pack` is synchronous, so this cannot\n * interleave with another encode.\n *\n * Declared above the registration because `addExtension` reads `type` immediately.\n */\nlet packingForWire = false\n\n// THIS EXTENSION BELONGS TO THE SNAPSHOT AND COMMAND CODECS, NOT TO THE WIRE CODEC.\n// It exists because those two replaced superjson, which carried a `URL`;\n// structured-clone mode does not, so without this a `URL` in task input silently\n// becomes a string in transit — the same defect the `Date` handling prevents.\n//\n// The wire codec replaced `JSON.stringify`, which HAS no concept of a `URL` and\n// renders one as its href string. So it wants the opposite answer — and it cannot\n// simply decline this extension, because `addExtension` writes into module-level\n// arrays that every `Packr` in the process reads. There is no per-instance registry.\n//\n// Hence the getter, which is the wire codec's ONLY intrusion here. msgpackr's two\n// halves read `type` differently, and that is what lets one registration serve both:\n//\n// - `pack` reads it on EVERY call — `if (extension.type)` decides whether the ext\n// tag is written. `undefined` skips the tag, so `write`'s return value is encoded\n// as an ordinary string: exactly `JSON.stringify`'s output, with no pre-pack walk.\n// - `unpack` reads it ONCE, at registration (`currentExtensions[type] = …`), so the\n// decoder always knows id 3 and a command still round-trips to a real `URL`.\n//\n// Nothing about the snapshot or command format changes. `index.spec.ts` pins that:\n// a command still emits `d40300` and decodes to a `URL`, `packWire` never latches the\n// flag, and no ext tag reaches the wire — so a msgpackr release that started caching\n// `type` fails there rather than shipping undecodable bytes to a Python service.\naddExtension({\n Class: URL,\n get type() {\n return packingForWire ? undefined : MSGPACK_EXTENSION_IDS.url\n },\n write: (v: URL) => v.href,\n read: (href: string) => new URL(href),\n} as Parameters<typeof addExtension>[0])\n\n// `structuredClone: true` carries `Map`, `Set`, `Date`, `RegExp`, `Error`,\n// `BigInt`, typed arrays and `undefined` in the format itself, so there is no\n// annotation pass — which is the whole reason this beats superjson. `Map`\n// insertion order survives.\n//\n// Known and accepted difference from superjson: msgpack has no signed zero, so\n// `-0` arrives as `0`. No extension can fix it — the format has one zero.\nconst packr = new Packr({ structuredClone: true })\n\n/**\n * Encodes a task command (`CREATE` / `ABORT`) for the AMQP command queue.\n *\n * **Both parties must agree, and there is no negotiation on this queue.** A\n * command encoded by one codec and read by another does not degrade — it fails to\n * parse, and `consumers/tasks.ts` terminally fails that task. So a deploy that\n * changes this format has to move `task-builder` and the operator together;\n * anything in flight across the cutover is lost. That is the repo's\n * no-legacy-support policy applied deliberately: no dual-read, no format sniffing,\n * no version byte.\n */\nexport function packCommand(value: unknown) {\n return packr.pack(value)\n}\n\n/**\n * Decodes a task command off the AMQP command queue.\n *\n * Throws on anything that is not this codec's output — including a\n * superjson-shaped command from a pre-msgpack build, whose leading `{` decodes as\n * a positive fixint and whose trailing JSON text trips msgpack's end-of-buffer\n * check. The caller turns that into a terminal task failure; see `packCommand`\n * on why there is no fallback path.\n */\nexport function unpackCommand<T = unknown>(buffer: Buffer) {\n return packr.unpack(buffer) as T\n}\n\n/**\n * THE HIGH-VOLUME WIRE CODEC — a drop-in replacement for `JSON.stringify` /\n * `JSON.parse` on the three hot AMQP wires (service dispatch, service results,\n * task updates).\n *\n * **It is a codec swap, not a richer data model.** These wires are a\n * cross-language contract (TS service SDK, Python service SDK, `task-builder`),\n * so the format is a portable msgpack subset that any language's msgpack library\n * decodes — NOT the msgpackr dialect `packCommand` uses. Concretely:\n *\n * - `useRecords: false` — record structures are a msgpackr extension. They are\n * the single largest size win on the wide uniform arrays ETL moves (measured\n * -53% vs -17% without), and giving them up is the price of Python being able\n * to read the bytes at all.\n * - `structuredClone: false` — no reference/cycle extension, and no ext-type-0\n * `undefined`.\n * - `encodeUndefinedAsNil` — msgpackr's default `undefined` is ext type 0, which\n * is msgpackr-only. See `packWire` on why nil is still not free.\n * - `mapAsEmptyObject` / `setAsEmptyObject` — `JSON.stringify` renders a `Map` and\n * a `Set` as `{}`; without these msgpack would encode their contents and\n * silently start carrying data the JSON wire never did.\n * - `int64AsType: 'number'` — JSON has one number type, so a 64-bit integer from\n * the Python side must arrive as a `number`, not a `bigint`.\n *\n * A `URL` degrades to its href string, exactly as `JSON.stringify` does — see the\n * `URL` extension above for how it declines its own ext tag on this path.\n */\nconst wirePackr = new Packr({\n useRecords: false,\n structuredClone: false,\n encodeUndefinedAsNil: true,\n mapAsEmptyObject: true,\n setAsEmptyObject: true,\n int64AsType: 'number',\n})\n\n/**\n * **THE CONTRACT: this wire carries the JSON data model, and nothing else.**\n *\n * It replaced `JSON.stringify`, so by construction every value that reaches it is\n * already JSON-representable — task input arrives as JSON over HTTP, a node's output\n * arrives back over this same wire, and the envelope fields the operator adds are\n * strings and numbers. Nothing here has to carry a class.\n *\n * That is what makes the encoding usable from any language: it emits only msgpack's\n * CORE types, so a decoder needs no extension registered and no configuration.\n * `index.spec.ts` enforces this structurally — it walks the emitted bytes and fails\n * on any `ext` marker, over the JSON data model, real dispatch bodies, update\n * envelopes and `__REQUENCE_type` references.\n *\n * Two things to know about the encoding itself:\n *\n * 1. **`undefined` in a record becomes `null` instead of vanishing.** JSON drops the\n * key; msgpack has no way to express \"absent\" for a key it is already writing.\n * This is the one difference that can break a receiver: a Zod `.optional()`\n * accepts an absent key and rejects `null`. Envelope objects assembled on the\n * encode side must therefore omit undefined keys rather than assign them —\n * `omitUndefined` below is the shared way to do it. Values that came through JSON\n * cannot contain `undefined`, so only envelopes need the treatment.\n * 2. **`Uint8Array` becomes msgpack `bin`.** `bin` is a core type, not an extension,\n * so this costs nothing in portability — and it is the one place the wire is\n * denser than the JSON it replaced, which had to base64 (a 1.33x inflation).\n *\n * OUT OF CONTRACT, and deliberately not engineered around: `Date`, `RegExp`, `Error`\n * and any class registered via `addExtension` are not JSON, so they must not be put\n * on this wire. A `Date` in particular would emit msgpack's timestamp ext (-1) —\n * standard, but still an ext, which forfeits the \"decodes anywhere with no setup\"\n * guarantee above. The structural scan in the spec is what catches it if one ever\n * does slip in.\n */\nexport function packWire(value: unknown) {\n packingForWire = true\n try {\n return wirePackr.pack(value)\n } finally {\n packingForWire = false\n }\n}\n\n/** Decodes a body off one of the three high-volume wires. */\nexport function unpackWire<T = unknown>(buffer: Uint8Array) {\n return wirePackr.unpack(buffer) as T\n}\n\n/**\n * The encoded size of `value` under this codec, in bytes.\n *\n * The claim-check decides what to offload by measuring the serialized body, so\n * the codec and the size measurement are coupled: the invariant is **measured\n * size == published size**. A measurement taken with the wrong codec does not\n * fail loudly — it offloads too eagerly (a needless S3 round-trip on the hot\n * path) or too late (`PayloadTooLarge` at the broker). This is the only sanctioned\n * way to measure a body destined for this codec.\n *\n * Which is why it measures THROUGH `packWire` rather than reaching for the same\n * `Packr` itself: `packingForWire` is what makes the process-global `URL`\n * extension stand down, so a bare `wirePackr.pack` here would measure a `URL` as\n * an ext-tagged value and then publish it as a bare href string — the two numbers\n * this function exists to keep equal, unequal. `packCommand` deliberately carries\n * real `URL`s, so task input can put one in a body that is measured here.\n */\nexport function wireByteLength(value: unknown) {\n return packWire(value).length\n}\n\n/**\n * Drops keys whose value is `undefined`, so a record survives `packWire`\n * byte-equivalently to `JSON.stringify`.\n *\n * Needed only for envelope objects assembled right at an encode site (a dispatch\n * body's `options`, an update's optional fields): those are the only places an\n * `undefined` can still be present, per divergence (1) on `packWire`.\n */\nexport function omitUndefined<T extends Record<string, unknown>>(value: T): T {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(value)) {\n if (value[key] !== undefined) {\n out[key] = value[key]\n }\n }\n return out as T\n}\n\n/**\n * Which codec a body on one of the three high-volume wires is encoded with.\n *\n * `json` is the floor and never goes away: it is what an SDK that has not claimed\n * the `wire:msgpack1` capability speaks, and what every task keeps until it is\n * recreated. A rolling deploy therefore has both live at once, by design.\n */\nexport type WireCodec = 'json' | 'msgpack'\n\nexport const WIRE_CONTENT_TYPES = {\n json: 'application/json',\n msgpack: 'application/msgpack',\n} as const satisfies Record<WireCodec, string>\n\n/**\n * Maps an AMQP `content-type` to the codec that wrote the body.\n *\n * **Every decoder on these wires must go through here rather than assume.** An\n * absent or unrecognised content type is treated as `json`: that is the status\n * quo for anything published before this codec existed, and for any hop that\n * forwards a body without restating the header.\n */\nexport function wireCodecFromContentType(\n contentType: string | undefined,\n): WireCodec {\n return contentType === WIRE_CONTENT_TYPES.msgpack ? 'msgpack' : 'json'\n}\n\n/** Encodes a body for one of the three high-volume wires, with its content type. */\nexport function encodeWireBody(value: unknown, codec: WireCodec) {\n return {\n body:\n codec === 'msgpack'\n ? packWire(value)\n : Buffer.from(JSON.stringify(value ?? null)),\n contentType: WIRE_CONTENT_TYPES[codec],\n }\n}\n\n/**\n * Decodes a body off one of the three high-volume wires, switching on the codec\n * the publisher declared.\n *\n * This is what makes the migration rolling instead of a synchronised cutover: a\n * message already in flight when a deploy lands decodes under whichever codec\n * wrote it, so no queue has to be drained.\n */\nexport function decodeWireBody<T = unknown>(\n content: Uint8Array,\n contentType: string | undefined,\n): T {\n return wireCodecFromContentType(contentType) === 'msgpack'\n ? unpackWire<T>(content)\n : (JSON.parse(Buffer.from(content).toString()) as T)\n}\n\n/**\n * The encoded size of `value` under `codec`, in bytes — the claim-check's sizer.\n *\n * Both codecs are live at once (the choice is baked per service node), so the\n * threshold has to be measured with whichever codec this particular dispatch\n * uses. See `wireByteLength` on why a drifting measurement fails quietly.\n */\nexport function wireBodyByteLength(value: unknown, codec: WireCodec) {\n if (codec === 'msgpack') {\n return wireByteLength(value)\n }\n const json = JSON.stringify(value)\n return json === undefined ? 0 : Buffer.byteLength(json)\n}\n",
|
|
20
20
|
"/**\n * Thrown by a `RequenceStream` remote read when the producer terminated\n * abnormally (or vanished) mid-stream — the explicit alternative to the\n * clean-looking EOF a truncated live relay used to produce. Surfaced through\n * the framed consumer-GET protocol (see `streamFraming.ts`): a TRUNCATED\n * terminal frame, or an EOF with no terminal frame at all.\n */\nexport class RequenceStreamTruncatedError extends Error {\n constructor(message = 'stream truncated') {\n super(message)\n this.name = 'RequenceStreamTruncatedError'\n }\n}\n",
|
|
21
21
|
"import { RequenceStreamTruncatedError } from './errors.ts'\n\n/**\n * Opt-in framed protocol for the consumer stream GET, closing the\n * silent-truncation gap: the server *decides* complete-vs-truncated (Redis\n * EOS/ERR markers) but a plain HTTP body cannot state it — a mid-stream\n * producer abort and a clean end both look like EOF. A client that sends\n * `x-requence-stream-protocol: framed` receives length-prefixed frames ending\n * in an explicit terminal frame; the server echoes the header only when it\n * actually frames. Clients that don't send the header (Python SDK, older TS)\n * get today's raw bytes — compatible in both directions.\n *\n * Frame layout: `type u8 | length u32 BE | payload[length]`.\n */\nexport const STREAM_PROTOCOL_HEADER = 'x-requence-stream-protocol'\nexport const STREAM_PROTOCOL_FRAMED = 'framed'\n\nconst DATA = 0x00\n/** Terminal: the stream is complete. Nothing may follow. */\nconst END = 0x01\n/** Terminal: the producer aborted / vanished. Payload = UTF-8 reason. */\nconst TRUNCATED = 0x02\n\nconst HEADER_BYTES = 5\n\n/** 5-byte DATA frame header; write it, then the chunk itself (no copy). */\nexport function dataFrameHeader(byteLength: number): Uint8Array {\n const header = new Uint8Array(HEADER_BYTES)\n new DataView(header.buffer).setUint32(1, byteLength, false)\n header[0] = DATA\n return header\n}\n\nexport const END_FRAME: Uint8Array = new Uint8Array([END, 0, 0, 0, 0])\n\nexport function truncatedFrame(reason: string): Uint8Array {\n const payload = new TextEncoder().encode(reason)\n const frame = new Uint8Array(HEADER_BYTES + payload.byteLength)\n new DataView(frame.buffer).setUint32(1, payload.byteLength, false)\n frame[0] = TRUNCATED\n frame.set(payload, HEADER_BYTES)\n return frame\n}\n\n/**\n * Decode a framed body back into raw chunks. DATA payloads are re-emitted;\n * END terminates cleanly; TRUNCATED — and an EOF without any terminal frame\n * (transport drop, proxy cut) — error the stream with a typed\n * `RequenceStreamTruncatedError`. Frames may be split across chunk boundaries.\n */\nexport function createFrameDecoder(): TransformStream<Uint8Array, Uint8Array> {\n let buffer: Uint8Array = new Uint8Array(0)\n let terminal = false\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n if (terminal) {\n if (chunk.byteLength > 0) {\n throw new Error('stream protocol error: bytes after terminal frame')\n }\n return\n }\n\n if (buffer.byteLength === 0) {\n buffer = chunk\n } else {\n const merged = new Uint8Array(buffer.byteLength + chunk.byteLength)\n merged.set(buffer, 0)\n merged.set(chunk, buffer.byteLength)\n buffer = merged\n }\n\n while (buffer.byteLength >= HEADER_BYTES) {\n const type = buffer[0]\n const length = new DataView(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength,\n ).getUint32(1, false)\n if (buffer.byteLength < HEADER_BYTES + length) {\n break\n }\n // slice (copy): the emitted chunk must not pin the merge buffer\n const payload = buffer.slice(HEADER_BYTES, HEADER_BYTES + length)\n buffer = buffer.subarray(HEADER_BYTES + length)\n\n switch (type) {\n case DATA: {\n if (payload.byteLength > 0) {\n controller.enqueue(payload)\n }\n break\n }\n case END: {\n terminal = true\n if (buffer.byteLength > 0) {\n throw new Error(\n 'stream protocol error: bytes after terminal frame',\n )\n }\n controller.terminate()\n return\n }\n case TRUNCATED: {\n terminal = true\n controller.error(\n new RequenceStreamTruncatedError(\n new TextDecoder().decode(payload) || undefined,\n ),\n )\n return\n }\n default: {\n throw new Error(`stream protocol error: unknown frame type ${type}`)\n }\n }\n }\n },\n flush(controller) {\n if (!terminal) {\n controller.error(\n new RequenceStreamTruncatedError(\n 'connection closed before terminal frame',\n ),\n )\n }\n },\n })\n}\n",
|
|
@@ -38,12 +38,17 @@
|
|
|
38
38
|
"import type {\n CallbackEgressContext,\n CallbackIngressContext,\n} from '@requence/callbacks'\nimport { sanitizeLogData, withRequenceStreams } from '@requence/files'\nimport type { WireCodec } from '@requence/helpers/msgpack'\nimport { wireBodyByteLength } from '@requence/helpers/msgpack'\nimport logger from '@requence/logger/simple'\n\nimport type { SurfaceHandlerEgressContext } from './surfaceHandler.ts'\nimport { renderTransformer, transformer } from './transformer.ts'\n\n/**\n * The service runtime's two serialization chokepoints (issue 07): one\n * outbound boundary and one inbound boundary, both delegating to the\n * runtime's composed transformer instance (`transformer.ts`). Every sub-path\n * (main result, deferred send, log, callback arg) routes through them. The\n * boundary owns ctx construction, the background-upload done-gate, and the\n * fail policy — this is *service policy*, which is why it lives here and not\n * in a shared package; call sites only say *what* to send and on which\n * emission.\n */\n\ntype OutboundCtx = Parameters<typeof transformer.outbound>[1]\ntype InboundCtx = Parameters<typeof transformer.inbound>[1]\n\nexport interface OutboundBoundaryOptions {\n uploadUrl?: string\n streamUrl?: string\n /** Claim-check offload threshold in bytes, transmitted via task options. */\n maxPayloadSize?: number\n /** Upload/stream cap in bytes, transmitted via task options. */\n maxFileSize?: number\n /**\n * The codec this boundary's publishes will use — the codec of the dispatch\n * being replied to, since a reply echoes it.\n *\n * The claim-check offloads on the SERIALIZED size, so the threshold has to be\n * measured with the codec the body actually goes out under. Both are live at\n * once (the choice is baked per service node), so the boundary cannot assume\n * either. Defaults to `json`: the pre-migration status quo, and the right\n * answer for the deferred path, which has no dispatch to echo.\n */\n wireCodec?: WireCodec\n /**\n * The node this boundary emits for, as the operator dispatched it\n * (`options.nodeId`, and the defer key on the `act()` path).\n *\n * Constant for the whole message, which is why it sits here rather than in\n * `OutboundSendOptions`: it is the address a **durable** callback reference is\n * routed and configured by (#150), not something one emission decides.\n */\n nodeId?: string\n signal?: AbortSignal\n fetch?: typeof globalThis.fetch\n /** Sink for best-effort degradation notices. Defaults to `logger.warn`. */\n warn?(message: string, error?: unknown): void\n}\n\nexport interface OutboundSendOptions {\n /** The emission this value belongs to (embedded in callback references). */\n outputName?: string | null\n /** Callback registrar for this emission; absent ⇒ functions fail loud. */\n onCallback?: CallbackEgressContext['onCallback']\n /**\n * Surface-handler registrar (#103). Supplying it switches this send to the\n * **render** egress chain, on which a function is a handler prop rather than\n * a peer callback — the render payload is the only place that is true, and\n * this option is what says so.\n */\n onSurfaceHandler?: SurfaceHandlerEgressContext['onSurfaceHandler']\n /**\n * Top-level keys of a record payload the claim-check must leave inline (the\n * render payload's `component`, whose hash the operator parses).\n */\n inlineKeys?: readonly string[]\n /**\n * Log policy: sanitize the payload first (functions/opaque instances become\n * labels), degrade offload failures to warnings, and never reject — a log\n * line must not fail the task. On a transform error resolves to `undefined`\n * (callers skip publishing).\n */\n bestEffort?: boolean\n}\n\nexport interface OutboundBoundary {\n /**\n * Serialize a value through the composed transformer inside a\n * `withRequenceStreams` scope. The returned promise resolves with the\n * serialized value as soon as references exist (stream bodies may still be\n * uploading); background completion is tracked in the boundary's ledger and\n * surfaced by `settle()`.\n */\n send(data: unknown, opts?: OutboundSendOptions): Promise<unknown>\n /** Enroll an external promise (e.g. a publish) in the done-gate. */\n track(promise: Promise<unknown>): void\n /**\n * The done-gate: wait until the ledger stops growing (sends may enqueue\n * more sends), then throw an `AggregateError` if any fail-hard work failed.\n * Ledger entries are pre-caught at registration time, so nothing ever\n * rejects unhandled while the gate is not yet attached.\n */\n settle(): Promise<void>\n}\n\nexport function createOutboundBoundary(\n base: OutboundBoundaryOptions,\n): OutboundBoundary {\n const warn =\n base.warn ??\n ((message: string, error?: unknown) =>\n error === undefined ? logger.warn(message) : logger.warn(message, error))\n\n const ledger: Array<Promise<void>> = []\n const errors: Error[] = []\n\n // Bound once: a JSON measurement of a msgpack body offloads at the wrong\n // point, and it fails quietly either way — too eager is a needless S3\n // round-trip on the hot path, too late is a rejection at the broker.\n const codec = base.wireCodec ?? 'json'\n const measure = (value: unknown) => wireBodyByteLength(value, codec)\n\n const track = (promise: Promise<unknown>) => {\n ledger.push(\n promise.then(\n () => {},\n (error: unknown) => {\n errors.push(error instanceof Error ? error : new Error(String(error)))\n },\n ),\n )\n }\n\n return {\n track,\n\n async send(data, opts = {}) {\n const ctx: OutboundCtx = {\n fetch: base.fetch ?? globalThis.fetch,\n signal: base.signal,\n uploadUrl: base.uploadUrl,\n streamUrl: base.streamUrl,\n maxPayloadSize: base.maxPayloadSize,\n maxFileSize: base.maxFileSize,\n measure,\n outputName: opts.outputName ?? null,\n nodeId: base.nodeId,\n onCallback: opts.onCallback,\n inlineKeys: opts.inlineKeys,\n ...(opts.bestEffort\n ? {\n onOffloadFail: (error: Error) =>\n warn('offload failed (best-effort log path):', error),\n onOffloadSkip: () =>\n warn('offload skipped: no upload transport configured'),\n }\n : {}),\n }\n\n if (opts.bestEffort) {\n try {\n const { value, done } = await withRequenceStreams(() =>\n transformer.outbound(sanitizeLogData(data), ctx),\n )\n // resolve-only: the gate waits for the upload but cannot fail on it\n ledger.push(\n done.then(\n () => {},\n (error: unknown) => warn('log stream upload failed:', error),\n ),\n )\n return value\n } catch (error) {\n warn('log offload errored:', error)\n return undefined\n }\n }\n\n // A render goes down the chain where a function is a handler prop, and it\n // is the only send that can supply the capability that chain needs — so\n // the option and the instance are chosen together, and the plain chain\n // never has to carry a registrar it has no handler for.\n const { value, done } = await withRequenceStreams(() =>\n opts.onSurfaceHandler\n ? renderTransformer.outbound(data, {\n ...ctx,\n onSurfaceHandler: opts.onSurfaceHandler,\n })\n : transformer.outbound(data, ctx),\n )\n track(done)\n return value\n },\n\n async settle() {\n for (;;) {\n const count = ledger.length\n await Promise.all(ledger)\n if (count === ledger.length) {\n break\n }\n }\n if (errors.length > 0) {\n const failed = errors.splice(0)\n throw new AggregateError(failed, failed[0].message)\n }\n },\n }\n}\n\nexport interface InboundBoundaryOptions {\n fetch?: typeof globalThis.fetch\n /** Cancellation for lazy remote reads of reconstructed values. */\n signal?: AbortSignal\n /** Per-boundary rehydration timeout; composed with `signal` per call. */\n timeoutMs?: number\n /** Default invocation dispatch for reconstructed callbacks. */\n onCallbackInvoke?: CallbackIngressContext['onCallbackInvoke']\n /**\n * Transformer override for this boundary; defaults to the full composed\n * chain. Passthrough consumers substitute the claim-check-only instance\n * (`transformer.ts`) so byte references stay raw wire objects.\n */\n transformer?: { inbound(data: unknown, ctx: InboundCtx): Promise<unknown> }\n}\n\nexport interface InboundReceiveOptions {\n onCallbackInvoke?: CallbackIngressContext['onCallbackInvoke']\n}\n\n/**\n * The single place the service's ingress cancellation/timeout policy lives:\n * every inbound transform of the runtime goes through one of these.\n */\nexport function createInboundBoundary(base: InboundBoundaryOptions = {}) {\n return (\n data: unknown,\n opts: InboundReceiveOptions = {},\n ): Promise<unknown> => {\n const timeout =\n base.timeoutMs && base.timeoutMs > 0\n ? AbortSignal.timeout(base.timeoutMs)\n : undefined\n const signal =\n base.signal && timeout\n ? AbortSignal.any([base.signal, timeout])\n : (timeout ?? base.signal)\n\n const ctx: InboundCtx = {\n fetch: base.fetch ?? globalThis.fetch,\n signal,\n onCallbackInvoke: opts.onCallbackInvoke ?? base.onCallbackInvoke,\n }\n return (base.transformer ?? transformer).inbound(data, ctx)\n }\n}\n",
|
|
39
39
|
"import type { TransformPath } from '@requence/transformer'\nimport { formatPath } from '@requence/transformer'\n\n/**\n * Where the first warning lands under a **dev overlay**.\n *\n * Deliberately low, and that is the point of the whole feature (#151): a hundred\n * emissions in a `bun run dev` session already means a generator is minting\n * closures in a loop, and catching it there is worth far more than catching it in\n * production. A one-shot fan-out never reaches it.\n */\nexport const DEV_OVERLAY_FIRST_WARNING = 100\n\n/**\n * Where the first warning lands for a **deployed** version.\n *\n * A thousand entries is ~200 KB of registry — well below any real concern, and\n * far above any legitimate one-shot fan-out. It is the step count, not this\n * number, that makes the growth visible.\n */\nexport const DEPLOYED_FIRST_WARNING = 1_000\n\n/** How many offending positions a warning names. */\nconst TOP_PATHS = 3\n\nexport interface CallbackGrowthOptions {\n /**\n * How this service names itself in a log line — `<service>@<version>`, the\n * dispatch queue's own name, so the line matches what the deployment calls it.\n */\n readonly service: string\n /** A dev overlay warns ten times earlier. See {@link DEV_OVERLAY_FIRST_WARNING}. */\n readonly devOverlay: boolean\n /**\n * The live size of the **connection's** registry.\n *\n * Read rather than counted, so it includes everything the connection holds —\n * other deliveries' callbacks and rendered handler props alike — and shrinks\n * when a delivery settles. Read *after* the registration that prompted it, so\n * the number in the warning is the number the process is holding.\n */\n readonly connectionCount: () => number\n /**\n * Where a crossing goes: the running service's own log, and nothing else.\n *\n * This warning is for the person writing the service, in the terminal they are\n * writing it in. It is not a task event — nobody watching a run can act on it,\n * and the author is the only one who can.\n */\n readonly warn: (message: string) => void\n}\n\nexport interface DeliveryGrowthOptions {\n /** The task this delivery belongs to, so the warning can be traced to a run. */\n readonly taskId: string\n}\n\nexport interface DeliveryGrowth {\n /**\n * One **connection-bound** registration, at the position it was written.\n * Called after the entry is in the registry, so the connection count a warning\n * states is the number the process is holding.\n *\n * A durable reference never reaches it: it registers nothing, so there is\n * nothing to count and nothing to warn about.\n */\n record(path: TransformPath): void\n}\n\nexport interface CallbackGrowthWatch {\n /** A recorder for one delivery, whose counter is its own. */\n forDelivery(options: DeliveryGrowthOptions): DeliveryGrowth\n}\n\n/** The next power of ten strictly above `count`, walking up from `from`. */\nfunction advance(from: number, count: number): number {\n let next = from\n while (next <= count) {\n next *= 10\n }\n return next\n}\n\n/**\n * The line the author reads, written for someone who has never heard of a\n * registry, a delivery or a lifetime.\n *\n * It has to do three things, in this order, because an author who stops reading\n * after the first line still has to have learnt something:\n *\n * 1. **what is happening** — functions are piling up and nothing frees them;\n * 2. **why that is bad** — the consequence, in memory the service will run out\n * of, not the mechanism that gets it there;\n * 3. **what to write instead** — the actual two lines, because \"declare it once\n * with createDurableCallback\" is only a fix to someone who already knows the\n * API.\n *\n * The numbers and the positions come after the sentence, not before it: they say\n * which `yield` to go and look at, which is useless until the reader knows what\n * they are looking for.\n */\nfunction formatWarning(params: {\n service: string\n taskId: string\n delivery: number\n connection: number\n perPath: Map<string, number>\n}): string {\n const worst = [...params.perPath.entries()]\n .sort(([, a], [, b]) => b - a)\n .slice(0, TOP_PATHS)\n .map(([path, count]) => `${path} (${count})`)\n .join(', ')\n\n return [\n `Requence: the functions you yield are piling up in memory and nothing frees them.`,\n ``,\n `Each one is kept for as long as the task runs, and it holds on to everything it`,\n `used from the code around it — including the whole value you were handling at`,\n `the time. On a task that runs for days, this service runs out of memory.`,\n ``,\n `If a function only needs data, and not a live connection or an open stream,`,\n `write it once at the top of your file and hand it the data each time:`,\n ``,\n ` const removeItem = createDurableCallback('removeItem', (arg, { id }) => ...)`,\n ``,\n ` yield { remove: removeItem.for({ id: item.id }) }`,\n ``,\n `Then there is one function, however many times you yield.`,\n ``,\n ` service: ${params.service}`,\n ` task: ${params.taskId}`,\n ` holding: ${params.delivery} from this task, ${params.connection} in this service`,\n ` worst: ${worst}`,\n ].join('\\n')\n}\n\n/**\n * Tells the author of a service whose inline closures are piling up — and tells\n * them **which `yield`** is doing it (#151).\n *\n * Shipping `createDurableCallback` does not stop anyone writing an inline closure\n * in a generator, and that is still the easier thing to write. This warning is\n * therefore also the migration path: it is what moves existing services over,\n * with no deprecation and no dual code path.\n *\n * It goes to the **service's own log** and nowhere else. It is not a task event:\n * the only person who can act on it is the one writing the service, and putting\n * it on a run would show it to everyone who cannot.\n *\n * **Two counters**, because they answer different questions and both are O(1):\n *\n * - **per delivery** — identifies the one generator doing it. This is the\n * teaching signal, and it is what the property paths belong to.\n * - **per connection** — what actually threatens the process: a worker holding\n * fifty concurrent tasks at nine hundred callbacks each is at forty-five\n * thousand without any single delivery tripping its own threshold.\n *\n * Both are stated in one warning, and a registration that crosses both emits it\n * **once** — a fresh connection running one generator crosses them on the same\n * registration, and two near-identical warnings would read as a bug in the\n * warning rather than as a bug in the service.\n *\n * **Steps, not a line per registration**, which would be a line per email: the\n * crossing, then each power of ten above it. A threshold jumps straight past a\n * count it is already below, so a connection that arrives at forty-five thousand\n * says so once rather than climbing there one decade per registration.\n *\n * **No cap and no eviction.** A hard cap is the rejected bounded-registry\n * alternative wearing a different hat: it kills a legitimate long-lived handle at\n * an arbitrary number, the author cannot exempt one, and it becomes a tuning knob\n * nobody can set correctly. Loud and degrading beats silent and truncating — so\n * nothing here refuses a registration or returns anything a caller could act on.\n */\nexport function createCallbackGrowthWatch({\n service,\n devOverlay,\n connectionCount,\n warn,\n}: CallbackGrowthOptions): CallbackGrowthWatch {\n const first = devOverlay ? DEV_OVERLAY_FIRST_WARNING : DEPLOYED_FIRST_WARNING\n // Connection-scoped, so it survives every delivery that comes and goes — the\n // whole point of the second counter is that no single delivery sees this.\n let nextConnection = first\n\n return {\n forDelivery({ taskId }) {\n let delivery = 0\n let nextDelivery = first\n // One entry per distinct position, which for a fixed set of `yield`\n // properties is the size of the source rather than of the traffic. An index\n // in a growing array is a position of its own, so this can grow — but never\n // faster than the registry it is reporting on, since every new position\n // came with a registry entry of its own.\n const perPath = new Map<string, number>()\n\n return {\n record(path) {\n delivery += 1\n const key = formatPath(path)\n perPath.set(key, (perPath.get(key) ?? 0) + 1)\n\n const connection = connectionCount()\n const crossedDelivery = delivery >= nextDelivery\n const crossedConnection = connection >= nextConnection\n if (!crossedDelivery && !crossedConnection) {\n return\n }\n if (crossedDelivery) {\n nextDelivery = advance(nextDelivery, delivery)\n }\n if (crossedConnection) {\n nextConnection = advance(nextConnection, connection)\n }\n\n warn(\n formatWarning({ service, taskId, delivery, connection, perPath }),\n )\n },\n }\n },\n }\n}\n",
|
|
40
40
|
"import type { RequenceCallback } from '@requence/helpers'\nimport { createDurableCallbackReference } from '@requence/helpers'\n\n/**\n * The node configuration a durable callback is handed, named **either way**:\n * write the type, or write the name of the service **version** it belongs to\n * and have it looked up.\n *\n * ```ts\n * ConfigurationOf<ImapOptions> // → ImapOptions\n * ConfigurationOf<'receiver'> // → the `receiver` version's configuration\n * ```\n *\n * The version-name form is the one to prefer: the type is generated into\n * `requence-env.d.ts` beside the version it belongs to, so naming the version\n * is the only form that cannot drift from what the node actually sends.\n *\n * A name that matches no version resolves to **itself**, which is deliberate\n * rather than an oversight: a typo then fails at the first use with the\n * misspelling quoted in the error (`Property 'host' does not exist on type\n * '\"recevier\"'`), which says more than a `never` would — and it leaves a\n * service whose configuration genuinely is a string alone.\n *\n * `Versions` exists only so this is testable. The SDK's own `global.d.ts`\n * declares `RequenceService.Version` **empty** — a generated\n * `requence-env.d.ts` is what fills it in a service's package — and merging a\n * version into it from inside this package breaks the SDK's own generics, which\n * only compile because the table has no keys. So the table is a defaulted\n * parameter rather than a hard reference, and nobody passes it.\n */\nexport type ConfigurationOf<\n T,\n Versions = RequenceService.Version,\n> = T extends keyof Versions\n ? Versions[T] extends { configuration: infer C }\n ? C\n : unknown\n : T\n\n/**\n * The one key a durable callback may not bind, because the context already has\n * it.\n *\n * There is exactly one, and it is checked rather than worked around: a\n * precedence rule (\"configuration wins\", \"bound wins\") would mean an author's\n * data silently disappearing or a node's credentials silently replaced, and\n * neither is something a reader of the handler could see.\n */\nconst RESERVED_CONTEXT_KEY = 'configuration'\n\n/**\n * Refuses a binding a spread cannot carry — at `.for(…)`, where the author\n * wrote it, and again where an invocation is unpacked, because that one arrives\n * off the wire and may come from another SDK that has not been through the\n * first check.\n *\n * Two ways to be unspreadable, and the second is why the first is not the only\n * check: a scalar has no keys, so spreading a string would quietly become\n * `{ 0: 'd', 1: 'e', … }`. Nothing may reach the handler having silently changed\n * shape.\n */\nfunction assertBindable(name: string, bound: unknown): void {\n if (bound === undefined || bound === null) {\n return\n }\n if (typeof bound !== 'object') {\n throw new Error(\n `durable callback \"${name}\" bound a ${typeof bound} — the bound data IS the callback's context, so it has to be an object`,\n )\n }\n if (Object.hasOwn(bound, RESERVED_CONTEXT_KEY)) {\n throw new Error(\n `durable callback \"${name}\" bound a \"${RESERVED_CONTEXT_KEY}\" key — the bound data IS the callback's context, and that name is taken by the node's configuration`,\n )\n }\n}\n\n/**\n * What a durable callback is told about the invocation it is running — and\n * deliberately all of it (#147).\n *\n * There is no message here, no task, no connection. That is exactly what makes\n * a durable callback durable: it may run in an instance that never saw the\n * emission, started after the emitting process died. What it does get is the\n * two things that survive that:\n *\n * - the bound data itself, spread across the context — what the emitting\n * handler attached at `.for(…)` in place of capturing it.\n * - `configuration` — the node's **static** configuration, so the callback can\n * rebuild whatever the emitting handler had open (an IMAP connection, an API\n * client) rather than hold it.\n *\n * The bound data is spread rather than parked under a field of its own, so\n * there is no second word to keep consistent with `.for(…)`:\n * `deleteMail.for({ uid })` is read as `{ uid }`. The cost is the one reserved\n * key above, and it is a compile error and a throw rather than a shadow.\n *\n * Computed configuration (`configurationFunctions`, evaluated per dispatch) is\n * not available: it is a property of one dispatch, and this call belongs to\n * none.\n */\nexport type DurableCallbackContext<Bound, Configuration> = Bound extends object\n ? Bound & { readonly configuration: Configuration }\n : { readonly configuration: Configuration }\n\n/**\n * The bound data as `.for(…)` takes it: the declared shape, minus the one key\n * the context has already spent.\n *\n * A `void` binding passes through untouched rather than intersected, which is\n * what keeps `notify.for()` callable with no argument at all.\n */\nexport type Bindable<Bound> = Bound extends object\n ? Bound & { [K in typeof RESERVED_CONTEXT_KEY]?: never }\n : Bound\n\n/**\n * The author's function.\n *\n * `arg` comes first because it is the *consumer's* half — what a downstream\n * node passed when it called `context.input.delete(…)`, and the only parameter\n * the emitted `RequenceCallback<Arg>` declares. Everything the emitting service\n * put there is the context, because from the running callback's point of view\n * the bound data and the node's configuration are the same kind of thing: what\n * this invocation was given, none of it written here.\n */\nexport type DurableCallbackHandler<Arg, Bound, Configuration> = (\n arg: Arg,\n context: DurableCallbackContext<Bound, Configuration>,\n) => unknown\n\n/**\n * A callback declared once at module scope, and what to do with it.\n */\nexport interface DurableCallbackHandle<Arg, Bound> {\n /** The stable address this was declared under. */\n readonly name: string\n /**\n * Binds this emission's data and returns the value to emit — a reference\n * naming the declaration and carrying the data, not a closure over it.\n *\n * Typed as the `RequenceCallback<Arg>` a consumer receives, because that is\n * what the position in the node's output schema declares and what a downstream\n * logic node holds. The value is not callable here: a durable callback runs\n * where its invocation is delivered.\n */\n for(bound: Bindable<Bound>): RequenceCallback<Arg>\n}\n\n/**\n * What {@link createDurableCallback} hands back.\n *\n * With nothing to bind (`Bound` at its `void` default) the declaration **is**\n * the value to emit, so `.for()` can be left off entirely:\n *\n * ```ts\n * yield { subject: mail.subject, acknowledge } // no binding\n * yield { delete: deleteMail.for({ uid: mail.uid }) } // a binding\n * ```\n *\n * That is not a special case at runtime — the handle is a reference that bound\n * nothing, which is exactly what `.for()` would have produced. It is the type\n * that is careful: the call signature appears **only** when `Bound` is `void`,\n * so a callback that needs a binding cannot be emitted without one. Without\n * that gate the omission would compile and the handler would destructure\n * `undefined` off a context that was never given its data.\n */\nexport type DurableCallback<Arg, Bound> = Bound extends void\n ? DurableCallbackHandle<Arg, Bound> & RequenceCallback<Arg>\n : DurableCallbackHandle<Arg, Bound>\n\ninterface Registration {\n handler: DurableCallbackHandler<any, any, any>\n}\n\n/**\n * Process-global, exactly like the UI registry (`uiWatch.ts`) and for the same\n * reason: a durable callback belongs to the service **version**, not to a\n * connection, so whichever connection consumed the invocation resolves it\n * against the set of callbacks the process declared at module scope.\n */\nconst durableCallbacks = new Map<string, Registration>()\n\n/**\n * Declares a callback **once**, so what a service emits per message is a\n * reference rather than a closure (#147).\n *\n * ```ts\n * const deleteMail = createDurableCallback<void, { uid: string }, 'receiver'>(\n * 'deleteMail',\n * async (_arg, { uid, configuration }) => {\n * const client = await connect(configuration) // rebuilt, never captured\n * await client.messageDelete(uid)\n * client.close()\n * },\n * )\n *\n * createService('receiver', async function* () {\n * for await (const mail of mails) {\n * yield { subject: mail.subject, delete: deleteMail.for({ uid: mail.uid }) }\n * }\n * })\n * ```\n *\n * A callback with nothing to bind is emitted as itself — see\n * {@link DurableCallback}:\n *\n * ```ts\n * const acknowledge = createDurableCallback('acknowledge', async () => …)\n *\n * yield { subject: mail.subject, acknowledge }\n * ```\n *\n * **Where you write the function decides how long it lives** — the rule surfaces\n * established for handler props (#59). A function written inline in the handler\n * closes over the running message: only that process can serve it, it dies when\n * the delivery settles, and until then it is held in the connection's registry\n * along with everything it captured. For a CONTINUOUS handler that is one\n * delivery holding a generator for the life of the task, so the registry grows\n * by one entry per emitted function per emission and nothing frees it for weeks.\n * Declared here instead, there is one entry per declaration however many\n * messages go by, and an invocation can be served by an instance started after\n * the emitting one died.\n *\n * Write it inline when it genuinely needs the live process — a handle on an open\n * stream, a client the handler is mid-conversation with. Declare it here when it\n * needs only data, and bind that data with `.for(…)`.\n *\n * The three type arguments are the three things the two sides disagree about,\n * in the order the *reader* meets them:\n *\n * 1. `Arg` — what a consumer passes. This is the emitted\n * `RequenceCallback<Arg>`, so it is what the node's output schema declares.\n * Defaults to `void`: a callback the graph calls with nothing.\n * 2. `Bound` — what `.for(…)` attaches per emission, and what the handler's\n * context is made of. An object (it is spread) or `void`, which lets the\n * declaration be emitted with no `.for()` at all. A scalar is refused,\n * because a spread has nowhere to put one.\n * 3. `Configuration` — the node's configuration, given as a type **or** as the\n * name of the version to look it up from ({@link ConfigurationOf}).\n *\n * `Configuration` does not infer from an annotated handler, because it is\n * resolved through a conditional type. Naming the version is both shorter and\n * the only form that cannot drift, so state all three.\n *\n * A second declaration under the same name **throws**, for the reason a\n * duplicate `createUI` id does: the name is the whole address, so an ambiguous\n * one is an invocation reaching the *wrong* handler — which reads like a bug in\n * the handler — and that is worse than a service that refuses to start.\n */\nexport function createDurableCallback<\n Arg = void,\n Bound extends object | void = void,\n Configuration = unknown,\n>(\n name: string,\n handler: DurableCallbackHandler<Arg, Bound, ConfigurationOf<Configuration>>,\n): DurableCallback<Arg, Bound> {\n if (durableCallbacks.has(name)) {\n throw new Error(\n `two durable callbacks share the name \"${name}\" — the name is the whole address of a durable callback, so pick a distinct one`,\n )\n }\n durableCallbacks.set(name, { handler })\n\n // The handle IS a reference that bound nothing, which is what lets a callback\n // with nothing to bind be emitted as-is. `.for(…)` hangs off it and mints a\n // fresh one per emission; the handle's own `name` came from the reference\n // (see `createDurableCallbackReference`), so nothing has to set it here.\n const handle = createDurableCallbackReference<Arg>({ name, bound: undefined })\n\n return Object.assign(handle, {\n for: (bound: Bindable<Bound>) => {\n // Checked here as well as at the type level, because a service may be\n // JavaScript and a binding may be built rather than written — and this is\n // the earliest the collision can be named, in the process that caused it,\n // before the reference is ever emitted.\n assertBindable(name, bound)\n return createDurableCallbackReference<Arg>({ name, bound })\n },\n }) as DurableCallback<Arg, Bound>\n}\n\n/**\n * The callback a durable invocation names, or `undefined` when this process\n * declared none under that name.\n */\nexport function findDurableCallback(name: string): Registration | undefined {\n return durableCallbacks.get(name)\n}\n\n/**\n * The context an invocation runs against: its bound data, with the node's\n * configuration beside it.\n *\n * Built here rather than at the consume site so the reserved-key check and the\n * spread stay in one place — `bound` comes off the wire as `unknown`, so this is\n * the second party that has to enforce what {@link DurableCallback.for} enforced\n * on the way out. Another SDK, or a hand-published invocation, has not been\n * through that.\n */\nexport function durableCallbackContext(\n name: string,\n bound: unknown,\n configuration: unknown,\n): Record<string, unknown> {\n assertBindable(name, bound)\n return { ...(bound as object | undefined), configuration }\n}\n\n/**\n * How many callbacks this process has declared.\n *\n * Not exported from the package: it exists so the invariant the feature is for —\n * one entry per declaration, whatever the emission count — is assertable.\n */\nexport function durableCallbackCount(): number {\n return durableCallbacks.size\n}\n",
|
|
41
|
-
"import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { CallbackObject } from '@requence/helpers'\nimport { DEFAULT_SURFACE_ID } from '@requence/helpers'\n\nimport { createInboundBoundary } from './boundary.ts'\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\n\nexport type JSONValue =\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | Array<JSONValue>\n | null\n | undefined\n\nexport class RetryError extends Error {\n constructor(public delay?: number) {\n super()\n }\n}\n\nexport class SkipError extends Error {}\n\nexport class AbortError extends Error {}\n\nconst OUTPUT_VALUE = Symbol('output_value')\n\ntype OutputValue = {\n [OUTPUT_VALUE]: string | null\n value: any\n}\n\nfunction isOutputValue(value: unknown): value is OutputValue {\n return value !== null && typeof value === 'object' && OUTPUT_VALUE in value\n}\n\n/**\n * Unwrap the `context.toOutput(...)` symbol wrapper into its raw value and\n * output name. Pure — serialization happens at the component's outbound\n * boundary (`createOutboundBoundary`), not here.\n */\nexport function unwrapOutputValue(result: unknown): {\n value: unknown\n outputName: string | null\n} {\n if (isOutputValue(result)) {\n return { value: result.value, outputName: result[OUTPUT_VALUE] }\n }\n return { value: result, outputName: null }\n}\n\n// The privileged send API (unit 05 headers, main-path variant). Runtime-attached\n// to every handler context but deliberately absent from the inferred\n// `ContextHelper` type — ordinary services must not discover it via typing.\n// Privileged consumers (the reserved requence-logic runtime) cast their context\n// to `PrivilegedContext`.\nexport interface PrivilegedSends {\n send(data: unknown, options?: { overwrite?: boolean }): void\n sendToOutput(\n name: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ): void\n
|
|
41
|
+
"import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { CallbackObject } from '@requence/helpers'\nimport { DEFAULT_SURFACE_ID } from '@requence/helpers'\n\nimport { createInboundBoundary } from './boundary.ts'\nimport type { RequenceStore } from './store.ts'\nimport { passthroughInboundTransformer } from './transformer.ts'\nimport type { RenderProps, RequenceUI } from './ui.ts'\n\nexport type JSONValue =\n | string\n | number\n | boolean\n | { [x: string]: JSONValue }\n | Array<JSONValue>\n | null\n | undefined\n\nexport class RetryError extends Error {\n constructor(public delay?: number) {\n super()\n }\n}\n\nexport class SkipError extends Error {}\n\nexport class AbortError extends Error {}\n\nconst OUTPUT_VALUE = Symbol('output_value')\n\ntype OutputValue = {\n [OUTPUT_VALUE]: string | null\n value: any\n}\n\nfunction isOutputValue(value: unknown): value is OutputValue {\n return value !== null && typeof value === 'object' && OUTPUT_VALUE in value\n}\n\n/**\n * Unwrap the `context.toOutput(...)` symbol wrapper into its raw value and\n * output name. Pure — serialization happens at the component's outbound\n * boundary (`createOutboundBoundary`), not here.\n */\nexport function unwrapOutputValue(result: unknown): {\n value: unknown\n outputName: string | null\n} {\n if (isOutputValue(result)) {\n return { value: result.value, outputName: result[OUTPUT_VALUE] }\n }\n return { value: result, outputName: null }\n}\n\n// The privileged send API (unit 05 headers, main-path variant). Runtime-attached\n// to every handler context but deliberately absent from the inferred\n// `ContextHelper` type — ordinary services must not discover it via typing.\n// Privileged consumers (the reserved requence-logic runtime) cast their context\n// to `PrivilegedContext`.\nexport interface PrivilegedSends {\n send(data: unknown, options?: { overwrite?: boolean }): void\n sendToOutput(\n name: string,\n data: unknown,\n options?: { overwrite?: boolean },\n ): void\n // Fire-and-forget invocation of a raw RequenceCallback wire ref (todo/11):\n // passthrough consumers receive callback refs un-rehydrated, so this is\n // their dispatch path. The arg goes through the message's outbound boundary\n // like any callback invocation; failures surface at the settle gate, not\n // here.\n invokeCallback(ref: CallbackObject, arg: unknown): void\n // The dispatch's transport options (payload.options, verbatim) so a\n // privileged consumer can forward upload targets across its own boundary.\n options: {\n uploadUrl?: string\n streamUrl?: string\n maxPayloadSize?: number\n maxFileSize?: number\n }\n}\n\nexport default async function createContextHelper(options: {\n taskId: string\n input: unknown\n configuration: unknown\n // Hoisted per-message controller (shared with the outbound boundary);\n // created here when the caller does not provide one.\n abortController?: AbortController\n // Skip file/stream/callback rehydration on ingress (claim-checks still\n // resolve): byte references reach the handler as their raw JSON-safe\n // `__REQUENCE_type` wire objects. Used by consumers that forward values\n // across a JSON process boundary (the logic runtime's guest channel).\n passthroughByteReferences?: boolean\n onLog: (method: 'log' | 'warn' | 'info' | 'error', data: any[]) => void\n onDefer: (reason?: string) => string\n /**\n * Dispatches an invocation of a callback the handler received in its input.\n * Takes the whole reference — both lifetimes ride the one tag (#147) and only\n * the caller knows how to route each arm.\n */\n onCallback: (payload: CallbackObject & { arg: unknown }) => void\n onRender: (params: {\n ui: RequenceUI\n props: unknown\n surfaceId: string\n }) => void\n /**\n * This dispatch's store (#210), built by the caller because only it holds the\n * capability and the two ids the address is composed from. Always present, so\n * `context.store` is never the thing that is missing — a dispatch that\n * carries no capability says so when a slot is read or written.\n */\n store: RequenceStore\n sends: PrivilegedSends\n}) {\n const terminatePromise = Promise.withResolvers<string>()\n const abortController = options.abortController ?? new AbortController()\n terminatePromise.promise.then(() => abortController.abort())\n\n const terminated = Object.assign(terminatePromise.promise, {\n signal: abortController.signal,\n })\n\n // Rehydration (FileObject/StreamObject → RequenceFile/RequenceStream,\n // RequenceCallback → function) — the component's single signal-aware\n // inbound boundary, called once per inbound sub-path. Passthrough mode swaps\n // in the chain that resolves claim-checks but keeps byte references raw.\n const inbound = createInboundBoundary({\n signal: abortController.signal,\n ...(options.passthroughByteReferences\n ? { transformer: passthroughInboundTransformer }\n : {}),\n })\n const [input, configuration] = await Promise.all([\n inbound(options.input, { onCallbackInvoke: options.onCallback }),\n inbound(options.configuration, {\n onCallbackInvoke: () => {\n throw new Error('configuration may not have callbacks')\n },\n }),\n ])\n\n const context = {\n taskId: options.taskId,\n input,\n configuration,\n\n toOutput(name: string | null, value: unknown): OutputValue {\n return {\n [OUTPUT_VALUE]: name,\n value,\n }\n },\n defer: options.onDefer,\n\n /**\n * What this node remembers past the end of this message, and past the end\n * of this task. `store.private(key)` / `store.shared(key)` is a local\n * handle and makes no call — see `RequenceStore`.\n */\n store: options.store,\n\n /**\n * Renders a UI component on this node in the task canvas. `props` is a\n * plain object and that is the entire contract — functions inside it arrive\n * in the component as invokable handlers, through the same transform a\n * peer service's payload goes through.\n *\n * Fire-and-forget, like a data send: the publish is enrolled in the\n * message's ledger, so a failure fails the node at the settle gate rather\n * than at this call site.\n *\n * **Where you write a function decides how long it can be pressed** (#103).\n * One written here closes over this handler, so it is connection-bound: it\n * needs a generator handler (a non-generator's registry goes the moment it\n * returns) and it dies with the message. One written in the UI's own\n * defaults — `createUI(url, { onSubmit })` — closes over module scope, so\n * any instance of this version can run it, and an invocation waits in the\n * version's handler queue when none is up. That is the honest answer to a\n * wait measured in days: a form's `onSubmit` belongs in the defaults, and\n * the handler that renders it is free to defer and exit.\n *\n * `props` is type-checked against the `ui`'s declared props\n * (`createUI<Props>`) — but every prop is optional, because **a render is a\n * patch** (#102). What the surface shows is the fold of the UI's defaults,\n * everything previously rendered onto that surface, and this render, so a\n * redraw carries only what changed and a prop nobody restates simply stays.\n * The flip side is that TypeScript can no longer tell a patch from a first\n * render that forgot half its props: the fold is the service's to complete.\n */\n render<Props>(\n ui: RequenceUI<Props>,\n props: RenderProps<Props>,\n renderOptions?: { surfaceId?: string },\n ) {\n options.onRender({\n ui,\n props,\n surfaceId: renderOptions?.surfaceId ?? DEFAULT_SURFACE_ID,\n })\n },\n\n debug: {\n log(...data: any[]) {\n options.onLog('log', data)\n },\n info(...data: any[]) {\n options.onLog('info', data)\n },\n warn(...data: any[]) {\n options.onLog('warn', data)\n },\n error(...data: any[]) {\n options.onLog('error', data)\n },\n },\n retry(delay?: number) {\n throw new RetryError(delay)\n },\n abort(reason?: string) {\n throw new AbortError(reason)\n },\n skip() {\n throw new SkipError()\n },\n terminated,\n }\n\n // Attached at runtime only: `context`'s inferred type (and therefore the\n // public `ContextHelper`) must not include the privileged send API.\n Object.assign(context, options.sends)\n\n return [context, terminatePromise] as const\n}\n\nexport type ContextHelper = Awaited<ReturnType<typeof createContextHelper>>[0]\n\n// Undocumented — the context shape privileged consumers (requence-logic) cast\n// to. The send methods are present at runtime on every handler context but\n// hidden from `ContextHelper`; the operator honors their `state`/`overwrite`\n// headers only for privileged nodes.\nexport type PrivilegedContext = ContextHelper & PrivilegedSends\n\nexport const handlerStorage = new AsyncLocalStorage<ContextHelper>()\n",
|
|
42
|
+
"import { z } from 'zod/v4'\n\nimport type { StoreCapability } from './capability.ts'\n\n/**\n * The two bindings — the **lifetime** axis. The author never types an address\n * component: every part is derived from ids the platform already holds.\n *\n * - `task` — a continuous node remembering across its own messages.\n * - `taskTemplate` — the imap cursor. Survives the run.\n */\nexport const STORE_BINDINGS = ['task', 'taskTemplate'] as const\n\nexport type StoreBinding = (typeof STORE_BINDINGS)[number]\n\n/**\n * The **ownership** axis (#225), orthogonal to the binding: who else can read\n * the slot.\n *\n * - `private` — this node only, which is what every slot used to be.\n * - `shared` — every node of the same subject. One writes a value, another's\n * next run reads it: the imap cursor on the canvas rather than inside the\n * service.\n *\n * It is a verb in both SDKs (`store.private(…)` / `store.shared(…)`) rather\n * than a third binding literal, because a wrong string is only caught at call\n * time in Python and in both guests, while a missing method fails in every\n * language.\n */\nexport const STORE_OWNERSHIPS = ['private', 'shared'] as const\n\nexport type StoreOwnership = (typeof STORE_OWNERSHIPS)[number]\n\n/**\n * The literal segment a shared address carries where a private one carries a\n * node id. It cannot collide with a node: a node id is a uuid.\n *\n * It is what keeps both shared forms exactly ONE segment below their prefix\n * root — the position a node id occupies — so every prefix builder, the key\n * index and both teardowns reach a shared address unchanged. A 2-segment\n * `{templateId}:{branchId}` would *be* the template index's root and fall out\n * of it entirely.\n */\nexport const SHARED_STORE_SEGMENT = 'shared'\n\n/**\n * The segment a PRIVATE address grows when the caller is a configuration\n * function rather than the node's own program (#224).\n *\n * A configuration service node's id is minted per task, so\n * `private(key, 'taskTemplate')` from a config body would compose a fresh\n * address on every single run — never read back, one abandoned address per task.\n * The host node's id plus this segment is the address that stays put.\n *\n * Its own segment rather than a `{nodeId}#config` suffix, so it falls INSIDE\n * `taskNodeStorePrefix`/`taskTemplateNodeStorePrefix`: the teardown, #215's\n * cold-start and the view's clear-node then take the config box with the node\n * for free, where a suffix would need a second explicit delete in each of the\n * three.\n *\n * It cannot collide with a node either, for the same reason `shared` cannot: a\n * node id is a uuid.\n */\nexport const CONFIGURATION_STORE_SEGMENT = 'config'\n\n/**\n * Live, written out. A branch id is always present in an address (#184) — the\n * live branch is the nil uuid, never an absent or empty segment, so a\n * `taskTemplate` address has the same shape everywhere.\n */\nexport const LIVE_BRANCH_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * An address and the index SET it belongs to. The owner is what the address\n * dies with (premise 8): a task for `task`, a template for `taskTemplate`.\n */\nexport interface StoreAddress {\n address: string\n ownerId: string\n}\n\n/**\n * Composes the address for a binding from a verified capability. **The store\n * builds and never receives** — that is what closes the hole an opaque\n * caller-supplied address would leave, where a service could spread writes\n * across fabricated addresses and dodge the 64-key cap.\n *\n * Branch sits in the MIDDLE of the `taskTemplate` shape on purpose: it gives\n * the two nested prefixes the deletes need — `{templateId}:{branchId}:` for a\n * branch teardown (merge and discard alike) and the wider `{templateId}:` for\n * a template delete, which is what gives a dead branch's later writes an owner.\n *\n * The separator is `:` and the store **never splits an address** — it composes\n * and prefix-matches — which is why the author's key needs no charset rule.\n *\n * The two axes meet here and nowhere else: ownership decides the LAST segment\n * (this node, or the literal `shared`), the binding decides the ones before it.\n *\n * A configuration function's PRIVATE slot is a third thing the last segment can\n * say (#224): the node's own box and its configuration's box are deliberately\n * different boxes, so a template author's `private('cursor')` cannot clobber the\n * service's own cursor in the same hash and the same 64-key budget. `shared` is\n * unaffected — it is the address the two meet at, and the only bridge between\n * them.\n */\nexport function composeAddress(\n ownership: StoreOwnership,\n binding: StoreBinding,\n capability: StoreCapability,\n): StoreAddress {\n const slot =\n ownership === 'shared'\n ? SHARED_STORE_SEGMENT\n : capability.configuration\n ? `${capability.nodeId}:${CONFIGURATION_STORE_SEGMENT}`\n : capability.nodeId\n\n if (binding === 'task') {\n return {\n address: `${capability.taskId}:${slot}`,\n ownerId: capability.taskId,\n }\n }\n\n return {\n address: `${capability.templateId}:${capability.branchId}:${slot}`,\n ownerId: capability.templateId,\n }\n}\n\n/**\n * The prefix that covers every address a TASK owns — the whole `task` binding\n * for every node of that task.\n *\n * It lives beside `composeAddress` on purpose: the party that composes an\n * address and the party that tears one down must read the shape (#184) off one\n * declaration, for the same reason the capability codec is shared.\n */\nexport function taskStorePrefix(taskId: string) {\n return `${taskId}:`\n}\n\n/**\n * The prefix that covers ONE node's `task` slot — the address the task's store\n * view reads (#206), and the narrow counterpart of\n * {@link taskTemplateNodeStorePrefix}.\n *\n * A prefix rather than the address itself for the same reason as the other\n * three: every reader takes #184's shape off one declaration. The trailing\n * separator is trimmed on both sides of the match, so this covers the address\n * `{taskId}:{nodeId}` exactly and nothing else.\n */\nexport function taskNodeStorePrefix(taskId: string, nodeId: string) {\n return `${taskId}:${nodeId}:`\n}\n\n/**\n * The prefix that covers a TEMPLATE's addresses. With a branch id it is the\n * narrow one a branch teardown takes (merge and discard alike); without one it\n * is the wider one a template delete takes, which covers every branch — and is\n * what gives a dead branch's later writes an owner.\n */\nexport function taskTemplateStorePrefix(templateId: string, branchId?: string) {\n return branchId === undefined\n ? `${templateId}:`\n : `${templateId}:${branchId}:`\n}\n\n/**\n * The prefix that covers ONE node's `taskTemplate` slot in one branch (#215).\n *\n * The narrowest of the three, and the only one that names a node: a store slot\n * belongs to a **program**, so a node whose program is gone or replaced cannot\n * have its predecessor's data assumed to still mean the same thing.\n *\n * It is a prefix rather than the address itself so every teardown reads #184's\n * shape off one declaration and hands `deletePrefix` one kind of string. The\n * trailing separator is trimmed on both sides of the match, so this covers the\n * address `{templateId}:{branchId}:{nodeId}` exactly and nothing else.\n */\nexport function taskTemplateNodeStorePrefix(\n templateId: string,\n branchId: string,\n nodeId: string,\n) {\n return `${templateId}:${branchId}:${nodeId}:`\n}\n\n/**\n * The node an address belongs to — the LAST segment of both shapes (#184), so\n * one reader serves the `task` and the `taskTemplate` form alike.\n *\n * It exists for the party that LISTS a prefix: `admin/list` answers with whole\n * addresses, and the template's store view (#217) groups them per node. The\n * author's key is a hash field rather than an address segment, so there is no\n * author input in here to split on — the same reason {@link ownerOfPrefix} is\n * safe.\n *\n * A shared address (#225) answers {@link SHARED_STORE_SEGMENT}, and that is the\n * point rather than a leak: `shared` is a **pseudo-node id** everywhere above\n * this, so the key index, the counts map, the per-node read and both clears\n * address it with no arm of their own. Nothing here validates a uuid, and\n * nothing above needs one.\n *\n * A configuration address (#224) answers the last TWO segments,\n * `{nodeId}:config`, for exactly the same reason: the last segment alone would\n * file every node's config box into one `config` bucket. As a pseudo-node id it\n * feeds `taskNodeStorePrefix`/`taskTemplateNodeStorePrefix` straight back to the\n * address it came from, so nothing above here grows an arm either.\n */\nexport function nodeOfAddress(address: string): string {\n const segments = address.split(':')\n const last = segments[segments.length - 1] ?? address\n\n if (last === CONFIGURATION_STORE_SEGMENT && segments.length > 1) {\n return `${segments[segments.length - 2]}:${last}`\n }\n\n return last\n}\n\n/**\n * A prefix with its trailing separator taken off, so `{templateId}:` and\n * `{templateId}` are the same prefix. Both spellings are in the tickets, and an\n * address carries **no** trailing separator — a literal `startsWith` on\n * `{templateId}:{branchId}:{nodeId}:` would therefore match nothing at all.\n */\nexport function trimPrefixSeparator(prefix: string) {\n return prefix.endsWith(':') ? prefix.slice(0, -1) : prefix\n}\n\n/**\n * Whether an address sits under a prefix. Matching is per SEGMENT, never per\n * character: `{a}:{b}` covers `{a}:{b}:{c}` and the address `{a}:{b}` itself,\n * and can never half-match a longer id that merely starts the same way.\n */\nexport function isUnderPrefix(address: string, prefix: string) {\n const trimmed = trimPrefixSeparator(prefix)\n return address === trimmed || address.startsWith(`${trimmed}:`)\n}\n\n/**\n * The owner whose index SET holds every address under a prefix — the first\n * segment of both address shapes (#184): a task for `task`, a template for\n * `taskTemplate`. `null` when the prefix does not begin with one, which is what\n * turns a malformed prefix into a `400` instead of a read of some invented\n * index key.\n *\n * This is the one place the store looks INSIDE an address, and it is safe\n * precisely because the author's key is a hash field rather than an address\n * segment — there is no author input in here to split on.\n */\nexport function ownerOfPrefix(prefix: string): string | null {\n const owner = trimPrefixSeparator(prefix).split(':')[0] ?? ''\n return z.uuid().safeParse(owner).success ? owner : null\n}\n",
|
|
43
|
+
"import { createHmac, timingSafeEqual } from 'node:crypto'\n\n/**\n * The capability a `node/*` call carries. **A service holds no store password\n * at all** — it is handed this per dispatch, and it can compose nothing else\n * with it: the store builds the address itself (`address.ts`), so the call\n * sends a binding and a key and no address, and there is nothing to forge.\n *\n * It is in three `.`-joined base64url parts:\n *\n * <claims>.<mac>.<context>\n * └─────────────┘ └───────┘\n * the signature the dispatch's own ids\n *\n * **The signature** (`claims` + `mac`) is minted by ui/backend at `startTask`,\n * one per tree, and rides the dispatch beside `uploadUrl` (#198, #209). It\n * pins `{rootTaskId, templateId, branchId}` — read straight off the task row,\n * where both id columns are `notNull`.\n *\n * **The context** is appended by the SDK from the dispatch it is handling. It\n * is deliberately NOT signed: signing per node would mean minting per dispatch,\n * and #198 traded that away knowingly — within one run the 64-key cap and\n * node-to-node isolation become *stated* rather than *enforced*. The bound that\n * matters is the one that cannot be forged: `rootTaskId` is signed, and the\n * allowed set is checked against it on every call, so a capability can only\n * ever reach its own customer's own running root task.\n */\nexport interface StoreCapabilityClaims {\n /** the run this capability lives for — checked against the allowed set */\n rootTaskId: string\n /** the `taskTemplate` binding's owner */\n templateId: string\n /** the branch, with live written out as the nil uuid */\n branchId: string\n}\n\n/** The ids the SDK reads off the dispatch it is handling. */\nexport interface StoreCapabilityContext {\n /** the `task` binding's owner */\n taskId: string\n /** the node the handler is running for — the last address segment */\n nodeId: string\n /**\n * Set only when this dispatch is a configuration-function evaluation (#224).\n * `nodeId` is then the HOST node — the node being configured — and a `private`\n * address grows a `config` segment behind it, so the configuration's box and\n * the service's own box are different boxes.\n *\n * Unsigned like the rest of the context, so this adds no enforcement and\n * removes none: a service can claim any node id today, and can now claim the\n * flag too. The config box is stated-private, not enforced-private.\n */\n configuration?: boolean\n}\n\nexport type StoreCapability = StoreCapabilityClaims & StoreCapabilityContext\n\nfunction encode(value: object) {\n return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')\n}\n\nfunction mac(claims: string, secret: string) {\n return createHmac('sha256', secret).update(claims).digest('base64url')\n}\n\n/**\n * Mints the signature half — ui/backend's job, once per tree at `startTask`.\n * Lives here rather than in ui/backend so the party that verifies and the party\n * that signs share one implementation and cannot drift apart.\n */\nexport function signStoreCapability(\n claims: StoreCapabilityClaims,\n secret: string,\n) {\n const encoded = encode({\n rootTaskId: claims.rootTaskId,\n templateId: claims.templateId,\n branchId: claims.branchId,\n })\n return `${encoded}.${mac(encoded, secret)}`\n}\n\n/**\n * Completes a signature into a capability with the ids the SDK holds. Pure\n * string work — no I/O, no secret, so a service can do it and a sandboxed\n * logic worker can forward it.\n */\nexport function composeStoreCapability(\n signature: string,\n context: StoreCapabilityContext,\n) {\n return `${signature}.${encode({\n taskId: context.taskId,\n nodeId: context.nodeId,\n // Written only when it is set, so an ordinary dispatch's capability is byte\n // for byte the one it was before #224 — and the Python mirror has one shape\n // fewer to match.\n ...(context.configuration ? { configuration: true } : {}),\n })}`\n}\n\nfunction decode(part: string): unknown {\n try {\n return JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))\n } catch {\n return null\n }\n}\n\nfunction readString(source: Record<string, unknown>, field: string) {\n const value = source[field]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\n/**\n * Verifies a capability and returns its five ids, or `null` when it is\n * malformed or not signed by this store. The caller turns `null` into `401`;\n * whether the run is still allowed is a separate question, answered against\n * the allowed set.\n */\nexport function verifyStoreCapability(\n capability: string,\n secret: string,\n): StoreCapability | null {\n const parts = capability.split('.')\n if (parts.length !== 3) {\n return null\n }\n\n const [encodedClaims, signature, encodedContext] = parts as [\n string,\n string,\n string,\n ]\n\n const expected = Buffer.from(mac(encodedClaims, secret), 'utf8')\n const received = Buffer.from(signature, 'utf8')\n if (\n expected.byteLength !== received.byteLength ||\n !timingSafeEqual(expected, received)\n ) {\n return null\n }\n\n const claims = decode(encodedClaims)\n const context = decode(encodedContext)\n if (\n claims === null ||\n typeof claims !== 'object' ||\n context === null ||\n typeof context !== 'object'\n ) {\n return null\n }\n\n const rootTaskId = readString(claims as Record<string, unknown>, 'rootTaskId')\n const templateId = readString(claims as Record<string, unknown>, 'templateId')\n const branchId = readString(claims as Record<string, unknown>, 'branchId')\n const taskId = readString(context as Record<string, unknown>, 'taskId')\n const nodeId = readString(context as Record<string, unknown>, 'nodeId')\n\n if (!rootTaskId || !templateId || !branchId || !taskId || !nodeId) {\n return null\n }\n\n // Absent is the ordinary dispatch, and anything but `true` is absent: a\n // malformed flag must not be a 401 (the ids are what authorises the call), and\n // it must not silently be believed either.\n const configuration =\n (context as Record<string, unknown>).configuration === true\n\n return { rootTaskId, templateId, branchId, taskId, nodeId, configuration }\n}\n",
|
|
44
|
+
"/**\n * The named store errors. They are exported from `@requence/store` rather than\n * owned by either SDK — the way `packages/files` exports `RequenceFile` beside\n * the service — so the TypeScript service SDK, the logic worker and ui/backend\n * all raise the same class for the same refusal.\n *\n * A store call is an HTTP call and fails like one (#183): it throws at the line\n * that made it, and an uncaught throw escalates as an ordinary node failure —\n * error branch if the node has one, task failure if it does not. There is no\n * retry, no per-call timeout and no store-specific failure path.\n */\nexport class StoreError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'StoreError'\n }\n}\n\n/**\n * The store could not be reached, or answered with something that is not a\n * refusal: a connection failure, a `5xx`, an unparsable body. Deliberately NOT\n * a reuse of `RequenceUnreachableError`, which means ui/backend.\n */\nexport class StoreUnavailableError extends StoreError {\n constructor(message = 'the store is unavailable') {\n super(message)\n this.name = 'StoreUnavailableError'\n }\n}\n\n/** `400` — the request itself is malformed, or the key is over 128 characters. */\nexport class StoreRequestError extends StoreError {\n constructor(message = 'invalid store request') {\n super(message)\n this.name = 'StoreRequestError'\n }\n}\n\n/** `401` — the capability is missing, malformed, or not signed by this store. */\nexport class StoreUnauthorizedError extends StoreError {\n constructor(message = 'the store rejected the capability') {\n super(message)\n this.name = 'StoreUnauthorizedError'\n }\n}\n\n/**\n * `403` — the capability verifies, but its root task is not in the allowed set:\n * the run is over (or never registered). Access is bounded by the root task,\n * not by a clock.\n */\nexport class StoreTaskNotAllowedError extends StoreError {\n constructor(message = 'this task is not allowed to use the store') {\n super(message)\n this.name = 'StoreTaskNotAllowedError'\n }\n}\n\n/** `409` — the address already holds 64 keys and this key is a new one. */\nexport class StoreAddressFullError extends StoreError {\n constructor(message = 'this node already stores 64 keys') {\n super(message)\n this.name = 'StoreAddressFullError'\n }\n}\n\n/** `413` — the value's JSON form is over 64 KiB. */\nexport class StoreValueTooLargeError extends StoreError {\n constructor(message = 'the value is too large') {\n super(message)\n this.name = 'StoreValueTooLargeError'\n }\n}\n\n/**\n * `422` — the value carries a `__REQUENCE_type` key at some depth. Every such\n * object is a *reference* the platform resolves on the way to a service\n * (`RequenceFile`, `RequenceStream`, `ClaimCheck`, `VariableRef`,\n * `RequenceCallback`), and a reference has a lifetime the store cannot honour.\n */\nexport class StoreValueNotStorableError extends StoreError {\n constructor(message = 'the value is not storable') {\n super(message)\n this.name = 'StoreValueNotStorableError'\n }\n}\n\n/**\n * Maps a refusal status onto its class. Every status the store answers with has\n * one, so a caller reads the outcome off the class rather than off a number.\n */\nexport function storeErrorForStatus(status: number, message: string) {\n switch (status) {\n case 400:\n return new StoreRequestError(message)\n case 401:\n return new StoreUnauthorizedError(message)\n case 403:\n return new StoreTaskNotAllowedError(message)\n case 409:\n return new StoreAddressFullError(message)\n case 413:\n return new StoreValueTooLargeError(message)\n case 422:\n return new StoreValueNotStorableError(message)\n default:\n return new StoreUnavailableError(message)\n }\n}\n",
|
|
45
|
+
"import type { StoreBinding, StoreOwnership } from './address.ts'\nimport { composeStoreCapability } from './capability.ts'\nimport { StoreUnavailableError, storeErrorForStatus } from './errors.ts'\nimport type { JSONValue } from './value.ts'\n\n/**\n * The store client both SDKs share, and ONE implementation of the wire — the\n * way `packages/files` exports `RequenceFile` beside the service, so neither\n * SDK owns the protocol.\n *\n * It is deliberately the three raw operations, not the author's API: the\n * `context.store.private(key, binding)` / `.shared(key, binding)` handle is\n * built on top of this by the TypeScript service SDK and by the logic worker,\n * because those verbs return a local handle that does no I/O and there is\n * nothing here for them to do.\n *\n * Both axes are positional here rather than folded into one word (#225):\n * ownership picks the address's last segment, the binding picks the ones before\n * it, and `composeAddress` is the only party that puts them together.\n */\nexport interface StoreClientOptions {\n /**\n * The store's base URL. Told, never derived — a store call carries no URL,\n * unlike a file reference. Services are handed the public one.\n */\n url: string\n /**\n * The signature ui/backend minted for this tree and the operator copied onto\n * the dispatch.\n */\n signature: string\n /** the running task, off the dispatch */\n taskId: string\n /** the node being dispatched, off the dispatch */\n nodeId: string\n /**\n * Set only when this dispatch is a configuration-function evaluation (#224):\n * `nodeId` is then the HOST node and the store composes the config box behind\n * it. Off the dispatch, like the two ids.\n */\n configuration?: boolean\n /** injectable for tests; defaults to the global `fetch` */\n fetch?: typeof globalThis.fetch\n}\n\nexport interface StoreClient {\n get<T extends JSONValue = JSONValue>(\n ownership: StoreOwnership,\n binding: StoreBinding,\n key: string,\n ): Promise<T | null>\n set<T extends JSONValue = JSONValue>(\n ownership: StoreOwnership,\n binding: StoreBinding,\n key: string,\n value: T | null,\n ): Promise<void>\n delete(\n ownership: StoreOwnership,\n binding: StoreBinding,\n key: string,\n ): Promise<void>\n}\n\nasync function refusalMessage(response: Response) {\n try {\n const body = (await response.json()) as { error?: unknown }\n if (typeof body.error === 'string' && body.error.length > 0) {\n return body.error\n }\n } catch {\n // an empty or non-JSON body — fall through to the status line\n }\n\n return `the store answered ${response.status}`\n}\n\nexport function createStoreClient(options: StoreClientOptions): StoreClient {\n const doFetch = options.fetch ?? globalThis.fetch\n const capability = composeStoreCapability(options.signature, {\n taskId: options.taskId,\n nodeId: options.nodeId,\n configuration: options.configuration,\n })\n const base = options.url.endsWith('/')\n ? options.url.slice(0, -1)\n : options.url\n\n async function call(operation: string, body: unknown) {\n let response: Response\n try {\n response = await doFetch(`${base}/node/${operation}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${capability}`,\n },\n body: JSON.stringify(body),\n })\n } catch (error) {\n // Unreachable, DNS failure, connection reset. Thrown at the line that\n // made the call, like any other HTTP call — an uncaught throw fails the\n // node (#183). There is no retry and no timeout here on purpose: three\n // designs for those were built and cut, and `packages/files` has none.\n throw new StoreUnavailableError(\n `the store at ${base} could not be reached: ${\n error instanceof Error ? error.message : String(error)\n }`,\n )\n }\n\n if (!response.ok) {\n throw storeErrorForStatus(response.status, await refusalMessage(response))\n }\n\n return response\n }\n\n return {\n async get(ownership, binding, key) {\n const response = await call('get', { ownership, binding, key })\n const body = (await response.json()) as { value: unknown }\n // Unset and a stored `null` are the same answer, deliberately.\n return (body.value ?? null) as never\n },\n\n async set(ownership, binding, key, value) {\n // `value` is always sent, so an omitted field can never be mistaken for\n // a `null` write. `set` resolves only once the store has confirmed.\n await call('set', { ownership, binding, key, value: value ?? null })\n },\n\n async delete(ownership, binding, key) {\n await call('delete', { ownership, binding, key })\n },\n }\n}\n",
|
|
46
|
+
"import {\n type JSONValue,\n type StoreBinding,\n type StoreClient,\n type StoreOwnership,\n StoreUnavailableError,\n createStoreClient,\n} from '@requence/store'\n\n/**\n * A handle to a single slot — one key under one binding, private to this node or\n * shared with every node of the subject.\n *\n * The value type is a parameter on the verb, not on `get()` (#190), so a held\n * handle types the read and the write once. `get()` answers `T | null` and\n * `set` takes `T | null` because `null` and unset collapse in the store (#181):\n * the type is what forces an author to handle the cold start, and without it\n * `private<number>` would lie on the first run.\n *\n * Every later operation (`increment`, `compareAndSet`) belongs here rather than\n * on `store`, so adding one adds no name anywhere — as `delete` did (#223).\n */\nexport interface StoreSlot<T extends JSONValue = JSONValue> {\n get(): Promise<T | null>\n set(value: T | null): Promise<void>\n /**\n * Frees the key. `set(null)` does NOT — `null` is a value and the key stays\n * occupied — so this is the only escape from the 64-key cap for a node that\n * writes computed keys (#223). Deleting a key that was never written is not\n * an error: there is nothing to report, since unset and `null` collapse.\n */\n delete(): Promise<void>\n}\n\n/**\n * `context.store` — what a node remembers past the end of its message, past the\n * end of its task, and what two nodes remember together.\n *\n * **Two orthogonal axes, each said once** (#225): the VERB carries ownership,\n * the ARGUMENT carries lifetime.\n *\n * ```ts\n * context.store.private('cursor', 'task') // this node, this run\n * context.store.private('cursor', 'taskTemplate') // this node, survives the run\n * context.store.shared('cursor', 'task') // every node, this run\n * context.store.shared('cursor', 'taskTemplate') // every node, survives the run\n * ```\n *\n * The binding **defaults to `task`** — the forgetful option — so the\n * consequential case is always written out and `taskTemplate` can never be\n * mistaken for temporary. `shared('cursor')` therefore states neither axis; the\n * docs say the two axes outright rather than leaving them to be inferred.\n *\n * Ownership is a verb rather than a third binding literal because a wrong string\n * is only caught at call time in Python and in both guests, while a missing\n * method fails in every language.\n *\n * ```ts\n * // held, when a handler touches the slot more than once\n * const cursor = context.store.shared<number>('lastUid', 'taskTemplate')\n * await cursor.set(((await cursor.get()) ?? 0) + 1)\n * ```\n *\n * The author never types an address: every part of one is derived from ids the\n * platform already holds.\n */\nexport interface RequenceStore {\n /** This node only — nothing else can read it. */\n private<T extends JSONValue = JSONValue>(\n key: string,\n binding?: StoreBinding,\n ): StoreSlot<T>\n /**\n * Every node of the same subject: one writes it, another's next run reads it.\n *\n * There is no referee — last write wins, and the Concurrency switch cannot\n * help, because it makes a node wait for ITSELF and is keyed by node id (#225,\n * D5). Two nodes writing one key lose a write.\n */\n shared<T extends JSONValue = JSONValue>(\n key: string,\n binding?: StoreBinding,\n ): StoreSlot<T>\n}\n\nexport interface StoreDispatch {\n /** the public store URL, off the dispatch — told, never derived */\n url?: string\n /** the signature ui/backend minted for this task's tree */\n signature?: string\n /** the running task, off the dispatch */\n taskId: string\n /** the node being dispatched, off the dispatch */\n nodeId?: string\n /**\n * Set only when this dispatch is a configuration-function evaluation (#224).\n * `nodeId` is then the HOST node — the node being configured — and the store\n * composes `private` slots into that node's CONFIGURATION box, which the host\n * service cannot see and which cannot see the host service's own box.\n * `shared` is the bridge between the two, and is unaffected.\n */\n configuration?: boolean\n /** injectable for tests; defaults to the global `fetch` */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Builds the `store` of one dispatch's handler context.\n *\n * **Both verbs are local and do no I/O**, so a handler that never touches a slot\n * makes zero calls — which is also why the client behind it is built on the\n * first operation rather than here: a dispatch that never reads the store pays\n * nothing for carrying a capability.\n *\n * A store call is an HTTP call and fails like one (#183): it throws at the line\n * that made it, and an uncaught throw escalates as an ordinary node failure —\n * the error branch when the node has one, the task when it does not. There is\n * no retry, no timeout and no store-specific path.\n */\nexport function createStore(dispatch: StoreDispatch): RequenceStore {\n let client: StoreClient | undefined\n\n function connect() {\n if (!client) {\n if (!dispatch.url || !dispatch.signature || !dispatch.nodeId) {\n // Not an outage, but it fails the same way and for the same reason: the\n // node asked the store something and no answer is coming. Raised at the\n // operation rather than at `at()` so the handle stays what it claims to\n // be — a local thing that does nothing.\n throw new StoreUnavailableError(\n 'this dispatch carries no store capability, so the store cannot be reached from this node — the task was started before the store existed, or by a Requence instance that has none',\n )\n }\n\n client = createStoreClient({\n url: dispatch.url,\n signature: dispatch.signature,\n taskId: dispatch.taskId,\n nodeId: dispatch.nodeId,\n configuration: dispatch.configuration,\n fetch: dispatch.fetch,\n })\n }\n\n return client\n }\n\n // One slot builder for both verbs: ownership is the only thing that differs,\n // and it differs in exactly one place — the address the store composes.\n function slot<T extends JSONValue>(\n ownership: StoreOwnership,\n key: string,\n binding: StoreBinding,\n ): StoreSlot<T> {\n // `async` rather than a bare return so a store that cannot be reached at\n // all rejects like every other store failure — one shape for the author,\n // whether they `await` or `.catch()`.\n return {\n async get() {\n return connect().get<T>(ownership, binding, key)\n },\n async set(value: T | null) {\n await connect().set<T>(ownership, binding, key, value)\n },\n async delete() {\n await connect().delete(ownership, binding, key)\n },\n }\n }\n\n return {\n private<T extends JSONValue = JSONValue>(\n key: string,\n binding: StoreBinding = 'task',\n ) {\n return slot<T>('private', key, binding)\n },\n shared<T extends JSONValue = JSONValue>(\n key: string,\n binding: StoreBinding = 'task',\n ) {\n return slot<T>('shared', key, binding)\n },\n }\n}\n",
|
|
42
47
|
"import { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { MAX_UI_SOURCE_BYTES } from '@requence/helpers'\n\nimport type { RequenceUI } from './ui.ts'\n\n/**\n * A component handle as the watcher holds it — the object `createUI` returned,\n * with every field writable. Derived from {@link RequenceUI} rather than\n * restated, so a field added there cannot go unwatched. The public type keeps\n * them `readonly`: rewriting them is this module's job and nobody else's.\n *\n * \"Writable\" is wider than \"rewritten\": a rebuild only ever replaces `hash` and\n * `source`, because they are the only fields that come out of the file. The rest\n * (`id`, `defaults`) are mutable here purely because `createUI` builds\n * the handle as this type — `id` in particular is the one field a rebuild must\n * NOT touch (#103).\n *\n * (The import is type-only, so `ui.ts` importing this module back is not a\n * runtime cycle.)\n */\nexport type MutableRequenceUI = {\n -readonly [K in keyof Omit<RequenceUI, '__props'>]: RequenceUI[K]\n}\n\nexport interface UIWatchListener {\n /**\n * A watched component's built file changed content. The handle already\n * carries the new bytes; announcing the swap is the listener's job.\n */\n onRebuild: (ui: MutableRequenceUI) => void\n /**\n * Something the author needs to hear about the watch itself. Reported rather\n * than logged because this module is process-global and `silent` is a\n * per-connection option — only the subscriber knows whether to print. Fanned\n * out to every subscriber; in the normal case that is the one dev connection\n * that turned the loop on.\n */\n onWarning: (message: string) => void\n}\n\n/**\n * Coalescing window for a burst of writes. A build tool rarely produces one\n * write per output file, and a read taken between two of them yields a\n * half-written bundle — which would render, fail, and be replaced a beat later\n * by the good one (D16's error state, flashing). Long enough to swallow an\n * ordinary bundler's burst, short enough to feel immediate.\n */\nconst REBUILD_DEBOUNCE_MS = 100\n\ninterface Registration {\n ui: MutableRequenceUI\n path: string\n /** Present exactly while this registration is being watched. */\n stop?: () => void\n /**\n * The last build refused for breaking the cap. Kept so an author who has to\n * go and shrink their bundle is told once, not once per write anywhere in the\n * directory.\n */\n refusedHash?: string\n}\n\nconst registrations = new Set<Registration>()\nconst listeners = new Set<UIWatchListener>()\nlet watching = false\n\nfunction warn(message: string) {\n listeners.forEach((listener) => listener.onWarning(message))\n}\n\n/**\n * Records a component built by `createUI`, so the dev loop can find it later.\n *\n * Unconditional, in every mode: `createUI` runs at module scope and cannot know\n * whether the service it belongs to will connect with a dev token. Registration\n * costs one object in a set and starts nothing — a watcher exists only once\n * {@link watchUIRebuilds} is called, which only a dev-mode connection does.\n */\nexport function registerUI(ui: MutableRequenceUI, filePath: string) {\n // The id is what a durable handler invocation names (#103), so two handles\n // claiming one makes it ambiguous — and the symptom would be a click running\n // the wrong component's handler, which reads like a bug in the component.\n // Thrown here, at module scope, so it is a startup failure with both paths in\n // it and the fix (`createUI({ url, id })`) named.\n //\n // Registering the SAME file twice is a clash too, not a re-registration: two\n // handles can carry different defaults, so `findUIById` would still have to\n // pick one. There is no id under which a process holds two components.\n const clash = [...registrations].find((existing) => existing.ui.id === ui.id)\n if (clash) {\n throw new Error(\n `two components share the UI id \"${ui.id}\" (${clash.path} and ${filePath}) — pass an explicit id: createUI({ url, id: '…' })`,\n )\n }\n\n const registration: Registration = { ui, path: filePath }\n registrations.add(registration)\n if (watching) {\n startWatching(registration)\n }\n}\n\n/**\n * The UI a durable handler invocation names (#103), or `undefined` when this\n * process has none under that id.\n *\n * Process-global, like the registry itself: a durable handler belongs to the\n * *service version*, not to a connection, so whichever connection consumed the\n * invocation resolves it against the same set of components the process\n * registered at module scope.\n */\nexport function findUIById(id: string): MutableRequenceUI | undefined {\n return [...registrations].find((entry) => entry.ui.id === id)?.ui\n}\n\n/**\n * Turns the dev loop on (D10): watch every registered component's built file\n * and call `onRebuild` whenever one of them changes content.\n *\n * The handle itself is rewritten before the listener runs, so two things follow\n * from one rebuild: every later render carries the new bundle (the render path\n * reads the handle at call time), and the listener announces the swap for every\n * surface already drawn (#108). Neither is a re-render — a rebuild changes which\n * bytes the frame imports and nothing else — which is why the swap reaches a\n * surface whose message has long since settled.\n *\n * Returns an unsubscribe. The last one out stops the watchers.\n */\nexport function watchUIRebuilds(listener: UIWatchListener): () => void {\n listeners.add(listener)\n\n if (!watching) {\n watching = true\n registrations.forEach(startWatching)\n }\n\n return () => {\n listeners.delete(listener)\n if (listeners.size > 0) {\n return\n }\n watching = false\n for (const registration of registrations) {\n registration.stop?.()\n registration.stop = undefined\n }\n }\n}\n\nfunction startWatching(registration: Registration) {\n if (registration.stop) {\n return\n }\n\n // The **directory**, not the file. A build that writes a temp file and\n // renames it over the target replaces the inode, and a watch on the file\n // follows the old one into oblivion — silently: no error, just no more\n // events. The directory sees the rename, and the delete-then-recreate case\n // with it.\n //\n // Unfiltered, deliberately: the reported name cannot carry the filter. Bun's\n // directory watch announces a rename under the *source* name only (verified —\n // a temp file renamed over the target reports the temp name twice, never the\n // target's), so matching on it would drop exactly the case the directory\n // watch exists for. The filter is content-addressing instead: a neighbour's\n // write costs one debounced read and hash, which matches and returns.\n const directory = path.dirname(registration.path)\n\n let timer: ReturnType<typeof setTimeout> | undefined\n let watcher: fs.FSWatcher\n\n try {\n watcher = fs.watch(directory, () => {\n clearTimeout(timer)\n timer = setTimeout(() => reload(registration), REBUILD_DEBOUNCE_MS)\n timer.unref?.()\n })\n } catch (error) {\n // An unwatchable path degrades the dev loop to nothing and must never take\n // the service with it — the author still gets a rebuild on restart.\n warn(\n `Requence: cannot watch ${registration.path} for rebuilds: ${error instanceof Error ? error.message : String(error)}`,\n )\n return\n }\n\n // Never hold the process open, and never crash it: the dev loop is an\n // addition to a running service, not a reason for one to live or die.\n watcher.unref?.()\n watcher.on('error', (error: Error) => {\n warn(`Requence: stopped watching ${registration.path}: ${error.message}`)\n })\n\n registration.stop = () => {\n clearTimeout(timer)\n watcher.close()\n }\n}\n\nfunction reload(registration: Registration) {\n let bundle: Buffer\n try {\n bundle = fs.readFileSync(registration.path)\n } catch {\n // Mid-write, or gone. Nothing to report: the write that follows re-triggers\n // this, and a build that never finishes is the author's own signal.\n return\n }\n\n const hash = createHash('sha256').update(bundle).digest('hex')\n if (hash === registration.ui.hash) {\n // Touched, not changed — a rebuild that produced identical output, an\n // editor's save of an unmodified file, or one of the file's neighbours\n // moving. Re-rendering would remount every surface for nothing.\n return\n }\n\n if (bundle.byteLength > MAX_UI_SOURCE_BYTES) {\n // The cap is `createUI`'s throw at registration (D4), but there is no call\n // site to throw at here — so the rebuild is refused and the previous bundle\n // stays live, which is the only outcome that keeps the surfaces working.\n if (hash !== registration.refusedHash) {\n registration.refusedHash = hash\n warn(\n `Requence: rebuilt component ${registration.path} is ${bundle.byteLength} bytes, over the ${MAX_UI_SOURCE_BYTES} limit — keeping the previous bundle`,\n )\n }\n return\n }\n\n // Mutating the handle in place **is** the mechanism. `context.render` reads\n // `ui.hash`/`ui.source` at call time, so from here on every render the service\n // makes carries the new bundle through the unchanged production path — and the\n // listener below repoints the surfaces that were already drawn.\n registration.ui.hash = hash\n registration.ui.source = bundle.toString('utf-8')\n\n for (const listener of [...listeners]) {\n listener.onRebuild(registration.ui)\n }\n}\n",
|
|
43
48
|
"import { createHash } from 'node:crypto'\nimport fs from 'node:fs'\nimport { basename } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { WrappedRequenceCallback } from '@requence/helpers'\nimport { MAX_UI_SOURCE_BYTES } from '@requence/helpers'\n\nimport { UITooLargeError } from './errors.ts'\nimport { type MutableRequenceUI, registerUI } from './uiWatch.ts'\n\n/**\n * A registered UI component: the built module's source plus its content hash.\n * Opaque to the author at the value level — the only thing to do with it is pass\n * it to `context.render(ui, props)`.\n *\n * `Props` is a phantom type parameter (never present at runtime) carrying the\n * shape the service sends to this component. It is what makes `render(ui, props)`\n * type-check against the service's own TypeScript, and what the component author\n * reads back with {@link PropsOf} to type `mount`. Declare it once, at\n * `createUI<Props>(url)`.\n */\nexport interface RequenceUI<Props = unknown> {\n /**\n * This component's **stable identity** — what a durable handler reference\n * names (#103), and the one thing about a UI that a rebuild must not change.\n *\n * The content hash cannot serve: a rebuild changes it while the module-scope\n * function in the defaults stays the same function, so a durable reference\n * keyed on the hash would stop resolving the moment the component was rebuilt\n * — and would never resolve at all in a process that started after the render.\n * Defaults to the built module's **file name**, which survives both a rebuild\n * and a restart; {@link CreateUIOptions.id} overrides it.\n *\n * Unique per process, enforced at registration: two components sharing an id\n * would make a durable invocation ambiguous, and the failure would be a click\n * reaching the wrong handler rather than anything visible.\n */\n readonly id: string\n /**\n * The bundle's content hash. `readonly` to the author but not immutable: in\n * service dev mode a rebuild of the watched file rewrites this and `source`\n * in place (D10), which is what makes the next ordinary render carry the new\n * bundle. Read it at use, never cache it.\n */\n readonly hash: string\n readonly source: string\n /**\n * The props this component always has, as declared at `createUI` — restated on\n * every render of it, so a service states once what does not change per\n * message and a render carries only what differs.\n *\n * Sent as their own field of the render payload rather than merged into the\n * render's props, because the receiver ranks them **lowest** (#102): a default\n * is what a surface shows until some render says otherwise, and it never\n * overrides what one already did. Merging them here would rank them highest\n * instead, which is the one thing a default must not be.\n *\n * Absent rather than empty when none were declared, so the payload of a\n * component without defaults is exactly what it always was.\n *\n * Deliberately **not** part of the hash: they are what the service sends, not\n * what the browser loads, so two registrations of one built file still dedupe\n * on the same bundle.\n */\n readonly defaults?: Partial<Props>\n /**\n * Phantom carrier for the props type — optional and never assigned, so it\n * adds no runtime surface. Only `render`/{@link PropsOf} read it at the type\n * level.\n */\n readonly __props?: Props\n}\n\n/**\n * What every invokable prop carries in the component, beside being callable.\n *\n * `reachable` is the answer to \"would pressing this do anything\", **per prop**\n * (#106) — because one surface can carry handlers of both lifetimes at once and\n * a surface-wide flag necessarily lies about one of them:\n *\n * ```\n * reachable(durable) = the task is still running\n * reachable(connection) = …and this surface's own connection is alive, with the\n * reference belonging to its current render\n * ```\n *\n * Read it *with* `ctx.canInvoke`, never instead of it: that one is permission,\n * this one is whether there is anything at the other end. A control should be\n * offered when both hold.\n *\n * Calling an unreachable handler **throws** (D32), naming the prop and the reason,\n * and sends nothing. Catch it on `error.name === 'RequenceUnreachableHandlerError'`\n * — the frame and your component share a realm but no module, so the name is the\n * whole contract:\n *\n * ```js\n * try {\n * props.onSubmit(answer)\n * } catch (error) {\n * if (error.name === 'RequenceUnreachableHandlerError') showNotice(error.message)\n * else throw error\n * }\n * ```\n *\n * It used to warn instead, which could not be handled: a component had no signal\n * that the click went nowhere, and `reachable` — readable before the call — races\n * a flip that lands between the render and the press. Reading `reachable` to\n * withhold the control is still right; the throw is what covers the race and the\n * component that does not check.\n *\n * **The viewer is told either way.** The frame also reports the refusal to the\n * canvas, which shows it beneath the surface in the same strip a permission or\n * byte-cap refusal uses. So catching is about saying something *better* in your\n * own words and your own layout — not about whether the failure is visible.\n */\nexport type HandlerReachability = {\n readonly reachable: boolean\n}\n\n/**\n * An invokable prop as the component holds it: the function the service put in\n * the props, plus {@link HandlerReachability}.\n */\nexport type RequenceHandler<Arg> = ((arg: Arg) => void) & HandlerReachability\n\n/**\n * How a single prop value looks to the component.\n *\n * Every function among the props is a **handler** the browser can invoke, so it\n * arrives callable and carrying its own `reachable` flag. A callback sent by the\n * service arrives rehydrated the same way (the browser is one more consumer of\n * the same inbound transform a peer service uses), so the service-only\n * `WrappedRequenceCallback` — its extra `.response()` — is reduced to what the\n * component actually holds. Everything else passes through untouched, so branded\n * values (`RequenceFile`, `RequenceStream`) and plain data keep their type\n * exactly.\n *\n * The parameter list is preserved rather than collapsed to `RequenceHandler`'s\n * single `Arg`, so a prop declared `onClose(): void` stays callable with no\n * argument.\n */\ntype ComponentPropValue<V> =\n V extends WrappedRequenceCallback<infer Arg>\n ? RequenceHandler<Arg>\n : V extends (...args: infer Args) => unknown\n ? ((...args: Args) => void) & HandlerReachability\n : V\n\n/**\n * The props as the component receives them: the service-declared props with\n * every top-level callback presented in its invokable form.\n */\nexport type ComponentProps<Props> = Props extends object\n ? { [K in keyof Props]: ComponentPropValue<Props[K]> }\n : Props\n\n/**\n * Extracts the component-facing props type from a `ui` handle, so a component\n * author can type `mount` straight off the value they imported:\n * `SurfaceContext<PropsOf<typeof ui>>`.\n */\nexport type PropsOf<U> =\n U extends RequenceUI<infer Props> ? ComponentProps<Props> : never\n\n/**\n * The props one render may supply: **any subset** of the component's props.\n *\n * A render is a patch, not a whole value (#102) — what the surface shows is the\n * fold of the UI's defaults, everything previously rendered onto that surface,\n * and this render — so omitting a prop is the normal case and cannot be an\n * error. A handler that redraws one field is the reason the fold exists, and the\n * clearest instance of it is a handler that *cannot* restate the rest: a durable\n * one, running in a process that never saw the original render.\n *\n * The accepted cost, and it is a real one: TypeScript cannot see the accumulated\n * state, so it can no longer tell a legitimate patch from a first render that\n * forgot half its props. `PropsOf` — the component's side — stays whole and\n * required, because the component genuinely does receive the folded object; it\n * is the service's responsibility that the fold covers it.\n */\nexport type RenderProps<Props> = Partial<Props>\n\n/**\n * What a component is handed, re-exported from the one place all three readers\n * share (#113): the SDK, the frame protocol and the shared runtime's\n * `createSurface`. Declared in `@requence/helpers/utils/surfaceComponent.ts`,\n * which is where the documentation lives — an author reads them from here.\n */\nexport type {\n Mount,\n SurfaceContext,\n SurfaceState,\n SurfaceTheme,\n} from '@requence/helpers'\n\nexport interface CreateUIOptions {\n /**\n * Where the built module is — `new URL('./component.js', import.meta.url)`.\n *\n * A URL rather than a path because it is the one form that resolves against\n * the *module that wrote it*: a relative path resolves against the process's\n * working directory, so a service started from anywhere but its own package\n * silently failed to find its own component.\n */\n url: URL\n /**\n * Override this component's stable id ({@link RequenceUI.id}), which defaults\n * to the built module's file name.\n *\n * Three reasons to set it, and the first two are about the default being a\n * file name: two components in different directories that build to `index.js`\n * collide, and renaming a built file silently retires every durable handler\n * reference already sitting in a queue or stored on a surface. The third is\n * registering **one** file twice — two handles with different defaults — which\n * is a collision like any other.\n *\n * A collision throws at registration, at module scope, so it is a startup\n * error rather than a click resolving against the wrong component's defaults.\n */\n id?: string\n}\n\n/**\n * Registers a UI component from an already-built ES module — one default export\n * `mount(element, ctx)`. Requence never bundles: the author builds with their\n * own toolchain, and this only reads the result and hashes it, which is what\n * keeps the contract portable across SDKs.\n *\n * Called at module scope, next to `createService`, so an oversized bundle fails\n * at registration rather than on the first render in production\n * (knowledge/service-ui-surfaces.md D4).\n *\n * ```ts\n * const askUI = createUI<{ question: string }>(\n * new URL('./ask.mount.js', import.meta.url), // or { url, id: 'ask' }\n * )\n * ```\n *\n * Nothing here declares how the bundle was built. A component may leave `react`,\n * `react-dom/client`, `react/jsx-runtime` and `@requence/surface-ui` **external**\n * and let the surface host's shared runtime resolve them — the import map is\n * installed for every surface, so importing the facade is the whole opt-in, and\n * its price is stated where that import is declared\n * (`@requence/service/surface-ui`). A bundle that ships its own framework has no\n * bare specifier left for the map to bind and is unaffected either way.\n *\n * Declare the props the service will send as the `Props` type argument: it is\n * erased at runtime but flows to `render(ui, props)` and back to the component\n * through {@link PropsOf}.\n *\n * `defaults` is any subset of `Props`, restated on every render of this\n * component, so a service declares once what does not change per message:\n *\n * ```ts\n * const panelUI = createUI<{ title: string; dense: boolean }>(\n * new URL('./panel.js', import.meta.url),\n * { dense: true },\n * )\n *\n * context.render(panelUI, { title: 'Processing' }) // dense comes along\n * ```\n *\n * They are the **weakest** layer of the surface's fold (#102): a render that\n * names a defaulted prop overrides it, and it stays overridden for every later\n * render that stays silent about it. A default answers \"what does this surface\n * show until something says otherwise\", not \"what does it show unless this\n * render says otherwise\".\n *\n * A function among them is a **durable** handler (D24): written at module scope, it\n * closes over nothing one message owns, so any instance of the version can run it —\n * including one started after the process that rendered has exited. That is the\n * opposite of a function written inline at `context.render`, which dies with the\n * message that published it. Where you write it is the whole decision.\n */\nexport function createUI<Props = unknown>(\n target: URL | CreateUIOptions,\n defaults?: Partial<Props>,\n): RequenceUI<Props> {\n const options = target instanceof URL ? { url: target } : target\n\n // The one thing `createUI` validates at run time, and it covers every way the\n // argument can be wrong at once: a path string (what it used to take), an\n // options object without a `url`, and a URL that names something other than a\n // file (`http://…` to a hosted bundle — Requence reads the bytes here, it does\n // not fetch them). Said here rather than left to `fileURLToPath`, whose\n // complaint is about an argument the author never wrote.\n if (!(options?.url instanceof URL) || options.url.protocol !== 'file:') {\n throw new Error(\n \"createUI needs a file URL to the built component: new URL('./component.js', import.meta.url)\",\n )\n }\n\n const path = fileURLToPath(options.url)\n const bundle = fs.readFileSync(path)\n\n if (bundle.byteLength > MAX_UI_SOURCE_BYTES) {\n throw new UITooLargeError(path, bundle.byteLength, MAX_UI_SOURCE_BYTES)\n }\n\n const ui: MutableRequenceUI = {\n // The stable half of the identity (#103), and the deliberate opposite of\n // the hash below: taken off the file's NAME, which a rebuild leaves alone.\n id: options.id ?? basename(path),\n // Content-addressed, so identical bundles dedupe across renders, replicas\n // and tasks — and so a rebuild yields a new identity by construction.\n hash: createHash('sha256').update(bundle).digest('hex'),\n source: bundle.toString('utf-8'),\n // Copied, so the object the author passed cannot change what a render sends\n // after registration. One level only — a nested default value stays shared,\n // exactly like any other prop value a service reuses across renders.\n ...(defaults === undefined ? {} : { defaults: { ...defaults } }),\n }\n\n // Recorded in every mode, watched in none of them by itself: this runs at\n // module scope, long before anything knows whether the service will connect\n // with a dev token, so the decision belongs to the connection (D10).\n registerUI(ui, path)\n\n return ui as RequenceUI<Props>\n}\n",
|
|
44
49
|
"import { handlerStorage } from './helpers.ts'\n\nfunction isAsyncIterable<T>(\n iterable: Iterable<T> | AsyncIterable<T>,\n): iterable is AsyncIterable<T> {\n return typeof (iterable as any)[Symbol.asyncIterator] === 'function'\n}\n\nexport function wrapIterable<T extends Iterable<any> | AsyncIterable<any>>(\n iterable: T,\n): T {\n const context = handlerStorage.getStore()\n\n if (!context) {\n return iterable\n }\n\n let terminated = false\n\n context.terminated.then(() => {\n terminated = true\n })\n\n if (isAsyncIterable(iterable)) {\n return {\n [Symbol.asyncIterator]() {\n const iterator = iterable[Symbol.asyncIterator]()\n\n return {\n async next() {\n const result = await Promise.race([\n context.terminated,\n iterator.next(),\n ])\n\n if (terminated) {\n return { done: true, value: undefined }\n }\n\n return result\n },\n }\n },\n } as T\n }\n\n return {\n [Symbol.iterator]() {\n const iterator = iterable[Symbol.iterator]()\n\n return {\n next() {\n if (terminated) {\n return { done: true, value: undefined }\n }\n const result = iterator.next()\n return result\n },\n }\n },\n } as T\n}\n\nexport function asyncEventEmitter<T>(initial: Array<T> = []) {\n const context = handlerStorage.getStore()\n\n let terminated = false\n context?.terminated.then(() => {\n terminated = true\n })\n\n // ONE queue for everything not yet pulled, and a waiter that exists only\n // while `next()` is actually parked on it.\n //\n // Keeping those two apart is the whole of it. The waiter used to be a single\n // slot that was set on the first pull and never cleared, so every later push\n // took the \"hand it over\" branch and called a resolve whose promise had\n // already settled — a silent no-op. Anything arriving while the consumer was\n // between pulls was therefore DROPPED, and a consumer between pulls is the\n // normal state of a CONTINUOUS handler: between two yields it publishes a\n // message and waits for the operator. A producer running at any real rate lost\n // roughly every other value, with no error and nothing in the update log.\n const queue = structuredClone(initial)\n let waiting: ((value: T) => void) | null = null\n\n return {\n push: (value: T) => {\n if (waiting) {\n // Retired in the same breath as it is used, so it can never be called\n // twice — that second call was the drop.\n const resolve = waiting\n waiting = null\n resolve(value)\n return\n }\n queue.push(value)\n },\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next() {\n if (queue.length > 0) {\n return { value: queue.shift()!, done: false }\n }\n const defer = Promise.withResolvers<T>()\n waiting = defer.resolve\n\n if (context) {\n const value = await Promise.race([\n defer.promise,\n context.terminated,\n ])\n\n if (terminated) {\n // Nobody is on this end any more, so leaving the waiter in place\n // would hand the next push to a consumer that has gone.\n waiting = null\n return { done: true, value: undefined }\n }\n\n return { done: false, value: value as Awaited<T> }\n }\n\n return { value: await defer.promise, done: false }\n },\n }\n },\n }\n}\n"
|
|
45
50
|
],
|
|
46
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;EAAA,OAAO,UAAQ,QAAQ,CAAC,GAAE,GAAE,GAAE,GAAE,GAAE;AAAA,IAAC,KAAI,IAAE,EAAE,QAAM,EAAE,MAAM,GAAG,IAAE,GAAE,IAAE,EAAE,IAAE,EAAE,QAAO;AAAA,MAAI,IAAE,IAAE,EAAE,EAAE,MAAI;AAAA,IAAE,OAAO,MAAI,IAAE,IAAE;AAAA;AAAA;;;ACAhH;;;ACAA;AAEA,IAAM,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AAC9C,SAAS,QAAQ,CAAC,MAAgD;AAAA,EACvE,OAAO,aAAa,UAAU,IAAI,EA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