Revert G's mesh-sdk merge (#189): G merged half, and today's validator refuses G's delivery parts
mesh/delivery merged: source.main moved to novox/mesh-sdk@27da949140c6
mesh/check being carried to 8afc3ebdf371 on 93e0a7b50d90 | from 27da949140c6
mesh/delivery merged: source.main moved to novox/mesh-sdk@27da949140c6
mesh/check being carried to 8afc3ebdf371 on 93e0a7b50d90 | from 27da949140c6
The group feat/47-G-join11 merged 3 of 17 members on 2026-11-13; G's mesh-sdk alone on main breaks 25 trunk
modules. The operator chose to put the order right: a reader release first, then G whole. This restores main
to 8fbba810 exactly.
Claude-Session: https://claude.ai/code/session_01NcbgfGKaxw984XyAPfLm4h
This commit is contained in:
@@ -1,214 +0,0 @@
|
||||
// Who called a tool, as the runtime proved it, and who may call a verb (novox/hq issue 365, ADR 0459 §2, ADR 0627 §2;
|
||||
// design 51 *Who may call which verb*). The TypeScript side of the Go `stdio` package's caller.go and callers.go, with
|
||||
// the same rules, so a holder in either language judges a caller alike.
|
||||
//
|
||||
// The runtime names the caller in a `tools/call`'s `_meta`, which a caller cannot write: the bus user that published
|
||||
// the call, taken from the subject it arrived on. It is handed to the tool here, never read from the arguments: a
|
||||
// `caller` argument names nobody.
|
||||
|
||||
import { config } from "../runtime/index.js";
|
||||
|
||||
/** The caller of a call the runtime named no caller for, said as a word so a record shows it was not proven. */
|
||||
export const UNPROVEN = "unproven";
|
||||
|
||||
/** Where in a `tools/call`'s `_meta` the runtime names the caller (the Go side's `stdio.MetaCaller`). */
|
||||
export const META_CALLER = "mesh/caller";
|
||||
|
||||
/** Where in a `tools/call`'s `_meta` the runtime names the id of the call in flight (`buscalls.MetaCall`). */
|
||||
export const META_CALL = "mesh/call";
|
||||
|
||||
// A bus user's name: `<node>.<module>`, `person.<name>`, `controller`; anything else is no caller.
|
||||
const busUser = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
|
||||
// A call's id: one subject-safe token.
|
||||
const callID = /^[A-Za-z0-9_-]{1,128}$/;
|
||||
|
||||
interface InFlight {
|
||||
readonly caller: string;
|
||||
readonly call: string;
|
||||
}
|
||||
|
||||
// The caller and the call's id of every call while its tool runs, by the arguments object that call was handed.
|
||||
const calls = new WeakMap<object, InFlight>();
|
||||
|
||||
/** The caller a `tools/call`'s `_meta` names, or UNPROVEN. */
|
||||
export function callerIn(meta: unknown): string {
|
||||
const s = meta && typeof meta === "object" ? (meta as Record<string, unknown>)[META_CALLER] : undefined;
|
||||
return typeof s === "string" && busUser.test(s) ? s : UNPROVEN;
|
||||
}
|
||||
|
||||
/** The call's id a `tools/call`'s `_meta` names, or empty. */
|
||||
export function callIn(meta: unknown): string {
|
||||
const s = meta && typeof meta === "object" ? (meta as Record<string, unknown>)[META_CALL] : undefined;
|
||||
return typeof s === "string" && callID.test(s) ? s : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `run` with the caller and the call's id `meta` names held for `args` while it runs: the stdio session does this
|
||||
* for every `tools/call`.
|
||||
*/
|
||||
export async function runAs<T>(meta: unknown, args: object, run: () => Promise<T>): Promise<T> {
|
||||
calls.set(args, { caller: callerIn(meta), call: callIn(meta) });
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
calls.delete(args);
|
||||
}
|
||||
}
|
||||
|
||||
/** Who called the tool that was handed `args`, as the runtime proved it, or UNPROVEN. Valid while the tool runs. */
|
||||
export function callerOf(args: object | undefined | null): string {
|
||||
return (args && calls.get(args)?.caller) || UNPROVEN;
|
||||
}
|
||||
|
||||
/** The id of the call that was handed `args`, as the runtime named it, or empty. Valid while the tool runs. */
|
||||
export function callIdOf(args: object | undefined | null): string {
|
||||
return (args && calls.get(args)?.call) || "";
|
||||
}
|
||||
|
||||
/**
|
||||
* A module's trusted list of who may call it (ADR 0459 §2): an entry is a module (on any machine), exactly
|
||||
* `<machine>.<module>`, or exactly `person.<name>`. A wildcard is no entry and an unproven caller never matches.
|
||||
*/
|
||||
export type Callers = readonly string[];
|
||||
|
||||
/** A callers file, `{"callers": [...]}`, and nothing else. */
|
||||
export function parseCallers(raw: string): Callers {
|
||||
let f: unknown;
|
||||
try {
|
||||
f = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
throw new Error(`the callers setting is not a list of callers: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
if (!f || typeof f !== "object" || Array.isArray(f)) throw new Error("the callers setting is not a list of callers: not an object");
|
||||
const extra = Object.keys(f).filter((k) => k !== "callers");
|
||||
if (extra.length) throw new Error(`the callers setting is not a list of callers: unknown field "${extra[0]}"`);
|
||||
const list = (f as { callers?: unknown }).callers ?? [];
|
||||
if (!Array.isArray(list) || list.some((c) => typeof c !== "string")) {
|
||||
throw new Error("the callers setting is not a list of callers: callers is not a list of words");
|
||||
}
|
||||
return list as string[];
|
||||
}
|
||||
|
||||
/** Whether `caller`, as the runtime proved it, is one the list names. */
|
||||
export function allows(callers: Callers, caller: string): boolean {
|
||||
if (!caller || caller === UNPROVEN) return false;
|
||||
for (const entry of callers) {
|
||||
if (!entry || /[*> ]/.test(entry)) continue;
|
||||
if (entry === caller) return true;
|
||||
if (!entry.includes(".") && !caller.startsWith("person.")) {
|
||||
const at = caller.indexOf(".");
|
||||
if (at >= 0 && caller.slice(at + 1) === entry) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A holder's trusted list per verb (ADR 0627 §2): for each verb it serves, the callers that may call it. */
|
||||
export type VerbCallers = Readonly<Record<string, readonly string[]>>;
|
||||
|
||||
/** The entry of a VerbCallers list that lets every proved caller call the verb. */
|
||||
export const ANY_CALLER = "*";
|
||||
/** The entry of a VerbCallers list that lets every operator's session (`person.<name>`) call the verb. */
|
||||
export const ANY_PERSON = "operator";
|
||||
|
||||
/** A holder's config value of verb to callers; empty is `defaults`, and a verb the holder does not serve is refused. */
|
||||
export function parseVerbCallers(raw: string, verbs: readonly string[], defaults: VerbCallers): VerbCallers {
|
||||
if (raw.trim() === "") return defaults;
|
||||
let c: unknown;
|
||||
try {
|
||||
c = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
throw new Error(`callers is not a JSON object of verb to callers: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
if (!c || typeof c !== "object" || Array.isArray(c)) throw new Error("callers is not a JSON object of verb to callers");
|
||||
for (const [verb, list] of Object.entries(c)) {
|
||||
if (!verbs.includes(verb)) throw new Error(`callers names the verb "${verb}", which the holder does not serve`);
|
||||
if (!Array.isArray(list) || list.some((e) => typeof e !== "string")) {
|
||||
throw new Error(`callers is not a JSON object of verb to callers: ${verb} is not a list of words`);
|
||||
}
|
||||
}
|
||||
return c as VerbCallers;
|
||||
}
|
||||
|
||||
/** Undefined when `caller`, as the runtime proved it, may call `verb`; else the refusal naming both. */
|
||||
export function refusal(c: VerbCallers, verb: string, caller: string): Error | undefined {
|
||||
if (!caller || caller === UNPROVEN) {
|
||||
return new Error(`${verb}: refused: the request carries no caller the tool runner proved`);
|
||||
}
|
||||
const person = caller.startsWith("person.");
|
||||
for (const entry of c[verb] ?? []) {
|
||||
if (entry === ANY_CALLER) return undefined;
|
||||
if (entry === ANY_PERSON) {
|
||||
if (person) return undefined;
|
||||
continue;
|
||||
}
|
||||
if (allows([entry], caller)) return undefined;
|
||||
}
|
||||
return new Error(`${verb}: refused for ${caller}: not on the holder's caller list for ${verb}`);
|
||||
}
|
||||
|
||||
/** The module of a proved module caller, which the runtime names `<machine>.<module>`. */
|
||||
export function moduleOf(proved: string): string {
|
||||
const at = proved.indexOf(".");
|
||||
return at >= 0 ? proved.slice(at + 1) : proved;
|
||||
}
|
||||
|
||||
/**
|
||||
* The holder's list as mesh-config resolved its config value `key` for this machine: an object of verb to callers, or
|
||||
* that object written as a string; unset or empty is `defaults`. A value that cannot be read is an error, never the
|
||||
* defaults, so a broken list is said, not widened.
|
||||
*/
|
||||
export async function configuredVerbCallers(key: string, verbs: readonly string[], defaults: VerbCallers): Promise<VerbCallers> {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = await config(key);
|
||||
} catch (err) {
|
||||
throw new Error(`the config value ${key} cannot be read: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
return parseConfiguredVerbCallers(raw, verbs, defaults);
|
||||
}
|
||||
|
||||
/** configuredVerbCallers' reading of a value as the runtime answered it. */
|
||||
export function parseConfiguredVerbCallers(raw: unknown, verbs: readonly string[], defaults: VerbCallers): VerbCallers {
|
||||
if (raw === undefined || raw === null) return defaults;
|
||||
if (typeof raw === "string") return parseVerbCallers(raw, verbs, defaults);
|
||||
return parseVerbCallers(JSON.stringify(raw), verbs, defaults);
|
||||
}
|
||||
|
||||
/** The kinds of name a seat definition's `callers` entry may be besides `seat:<seat>`, `module:<module>` and `holder:<seat>@same-node` (design 47 G §336, §392). */
|
||||
const callerWords = ["operator", "healers", "persons", "sessions", "invokers"];
|
||||
const callerForm = /^(seat:[a-z][a-z0-9-]*|module:[a-z][a-z0-9-]*|holder:[a-z][a-z0-9-]*@same-node)$/;
|
||||
|
||||
/**
|
||||
* The callers a verb that names none takes by its class (design 47 G §391, §456), as the Go reader's DefaultCallers: a
|
||||
* `read` takes invokers, persons and sessions; an `act` the operator and sessions; a `warrant` the operator. A verb that
|
||||
* names no class is a `read`.
|
||||
*/
|
||||
function defaultCallers(cls: string | undefined): readonly string[] {
|
||||
switch (cls) {
|
||||
case "act":
|
||||
return ["operator", "sessions"];
|
||||
case "warrant":
|
||||
return ["operator"];
|
||||
}
|
||||
return ["invokers", "persons", "sessions"];
|
||||
}
|
||||
|
||||
/**
|
||||
* The callers a seat definition names for a verb or an accepted kind (design 47 G §336, §392): a list of entries, each
|
||||
* one of the forms the format knows. Text is refused naming the verb, and so is an entry that is no form (a bare name
|
||||
* among them), as the Go reader does. A verb that names no callers takes the default of its class `cls` (§391).
|
||||
*/
|
||||
export function readDefinitionCallers(verb: string, value: unknown, cls?: string): readonly string[] {
|
||||
if (value === undefined || value === null) return defaultCallers(cls);
|
||||
if (typeof value === "string") {
|
||||
throw new Error(`${verb}: callers are text ("${value}"): a definition gives its callers as a list`);
|
||||
}
|
||||
if (!Array.isArray(value)) throw new Error(`${verb}: callers is not a list of entries`);
|
||||
for (const e of value) {
|
||||
if (typeof e !== "string" || !(callerWords.includes(e) || callerForm.test(e))) {
|
||||
throw new Error(`${verb}: the callers entry ${JSON.stringify(e)} is none of ${callerWords.join(", ")}, seat:<seat>, module:<module> and holder:<seat>@same-node`);
|
||||
}
|
||||
}
|
||||
return value as string[];
|
||||
}
|
||||
@@ -13,6 +13,3 @@ export * as messaging from "./messaging/index.js";
|
||||
export * as events from "./events/index.js";
|
||||
export * as primitives from "./primitives/index.js";
|
||||
export * as state from "./state/index.js";
|
||||
export * as runtime from "./runtime/index.js";
|
||||
export * as callers from "./callers/index.js";
|
||||
export * as views from "./views/index.js";
|
||||
|
||||
+4
-22
@@ -7,18 +7,6 @@ import type { Envelope, EventHeaders } from "../contracts/index.js";
|
||||
|
||||
export type { Envelope, EventHeaders };
|
||||
|
||||
/** How a publish is asked of the runtime. */
|
||||
export interface PublishOptions {
|
||||
/** Resolve once the bus acknowledged the message (the runtime's `mesh/publish` takes `ack: true`). */
|
||||
readonly ack?: boolean;
|
||||
}
|
||||
|
||||
/** How a subscription is asked of the runtime. */
|
||||
export interface SubscribeOptions {
|
||||
/** `new`: only messages published after the subscription (the runtime's `mesh/subscribe` takes `deliver: new`). */
|
||||
readonly deliver?: "new";
|
||||
}
|
||||
|
||||
/** A request/reply call and a publish/subscribe surface over the mesh broker. */
|
||||
export interface Broker {
|
||||
/** Ask one question and await one answer — the client side; the shape mesh-controller's command
|
||||
@@ -27,16 +15,10 @@ export interface Broker {
|
||||
/** Answer a question — the server side of request/reply. A tool runtime serves invocations this
|
||||
* way. Returns an unregister. */
|
||||
handle<Req, Res>(key: string, handler: (body: Req) => Promise<Res>): Promise<() => void>;
|
||||
/**
|
||||
* Emit an event onto the mesh. With `ack: true` a bundle's publish resolves only once the bus acknowledged it and
|
||||
* rejects with the reason where it did not (design 47 G §559).
|
||||
*/
|
||||
publish<T>(env: Envelope<T>, options?: PublishOptions): Promise<void>;
|
||||
/**
|
||||
* React to events matching a routing-key pattern. Returns an unsubscribe. With `deliver: "new"` the handler is given
|
||||
* only the messages published after the subscription is made (design 47 G §559).
|
||||
*/
|
||||
subscribe<T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>, options?: SubscribeOptions): Promise<() => void>;
|
||||
/** Emit an event onto the mesh. */
|
||||
publish<T>(env: Envelope<T>): Promise<void>;
|
||||
/** React to events matching a routing-key pattern. Returns an unsubscribe. */
|
||||
subscribe<T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>): Promise<() => void>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
// The runtime that launched this bundle, as one channel of requests (novox/hq ADR 0193, ADR 0198): what a module's code
|
||||
// asks of its node's tool runner beyond emitting, subscribing and its state, each named by the runtime's method
|
||||
// (`mesh/seat.publish`, `mesh/provision.get`). The stdio session binds it when the runtime launched the process; a
|
||||
// bundle never names a transport.
|
||||
|
||||
/** What the runtime is asked through: the stdio session provides it. */
|
||||
export type RuntimeAsk = (method: string, params: unknown) => Promise<unknown>;
|
||||
|
||||
let bound: RuntimeAsk | undefined;
|
||||
|
||||
/** Bind the channel. The stdio session calls this when the runtime launched the process; a test binds its own. */
|
||||
export function useRuntime(ask: RuntimeAsk | undefined): void {
|
||||
bound = ask;
|
||||
words = undefined;
|
||||
}
|
||||
|
||||
/** The call a bundle reads its tool runner's capability words with: answered with `{words}` (design 47 G §576, §622). */
|
||||
export const CAPABILITIES_CALL = "mesh/capabilities";
|
||||
/** The word of the acknowledged publish and the subscription for new messages the finding writer uses (§559). */
|
||||
export const CAP_FINDING_CALLS = "finding-calls";
|
||||
/** The code of a runtime's answer to a call it does not know (JSON-RPC's method not found). */
|
||||
const CODE_NO_METHOD = -32601;
|
||||
|
||||
// The words the tool runner states, asked once at the first call that needs one and kept for as long as the bundle runs: a
|
||||
// bundle lives no longer than the tool runner that started it (design 47 G §576).
|
||||
let words: Promise<string[]> | undefined;
|
||||
|
||||
async function readWords(): Promise<string[]> {
|
||||
try {
|
||||
const a = (await askRuntime(CAPABILITIES_CALL, {})) as { words?: string[] } | null;
|
||||
return a?.words ?? [];
|
||||
} catch (e) {
|
||||
// a tool runner of before G answers the call as an unknown one, which reads as no word stated
|
||||
if ((e as { code?: number }).code === CODE_NO_METHOD) return [];
|
||||
throw new Error(`reading the tool runner's capability words: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail at once, naming the word and the node (from MESH_NODE), when the tool runner this bundle runs under does not state
|
||||
* `word`; the words are read once (design 47 G §488, §576). A failed read is asked again at the next call.
|
||||
*/
|
||||
export async function requireCapability(word: string): Promise<void> {
|
||||
const reading = (words ??= readWords());
|
||||
let stated: string[];
|
||||
try {
|
||||
stated = await reading;
|
||||
} catch (e) {
|
||||
if (words === reading) words = undefined;
|
||||
throw e;
|
||||
}
|
||||
if (stated.includes(word)) return;
|
||||
throw new Error(`the tool runner of node ${process.env.MESH_NODE || "unknown"} does not state the capability word "${word}": a call of its family is refused until it does`);
|
||||
}
|
||||
|
||||
/** Ask the runtime one of its methods; refused with the reason when no runtime launched this bundle. */
|
||||
export async function askRuntime(method: string, params: unknown): Promise<unknown> {
|
||||
if (!bound) {
|
||||
throw new Error(`no runtime to ask ${method} of: it is reached through the runtime that launched this bundle (novox/hq ADR 0198)`);
|
||||
}
|
||||
return bound(method, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit an accept, or say an event, on a seat (novox/hq ADR 0259 §3): `subject` whole, as the seat's contract names
|
||||
* it (`mesh.seat.<seat>.event.<event>`), de-duplicated by `id` (the same id twice is one message; empty is the
|
||||
* runtime's to make). The runtime does it as this module, only as far as its membership lists, and refuses the rest
|
||||
* with the reason: the Go side's `stdio.SeatPublish`.
|
||||
*/
|
||||
export async function seatPublish(subject: string, body: unknown, id = ""): Promise<void> {
|
||||
await askRuntime("mesh/seat.publish", { subject, body, id });
|
||||
}
|
||||
|
||||
/** This module's config value `key`, as mesh-config resolved it for this machine (the Go side's `stdio.Config`). */
|
||||
export async function config(key: string): Promise<unknown> {
|
||||
return askRuntime("mesh/provision.get", { kind: "config", key });
|
||||
}
|
||||
+2
-15
@@ -122,17 +122,6 @@ function refusedUnannounced(name: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** The size of one chunk of the Go side's put and get sessions, the most a call carries (design 47 G §518, A-21). */
|
||||
export const CHUNK_BYTES = 512 * 1024;
|
||||
|
||||
/** A TypeScript bundle runs no put or get session in G (design 47 G §643): a value over one call's limit fails at once, naming it. */
|
||||
function withinOneCall(key: string, value: unknown): void {
|
||||
const size = Buffer.byteLength(JSON.stringify(value) ?? "");
|
||||
if (size > CHUNK_BYTES) {
|
||||
throw new Error(`the value of "${key}" is ${size} bytes, over the ${CHUNK_BYTES} bytes (512 KiB) one call carries: a TypeScript bundle puts no value larger than that`);
|
||||
}
|
||||
}
|
||||
|
||||
/** A state this module keeps (by its local name) or reads (`<module>.<name>`). */
|
||||
export function state<T = unknown>(name: string): State<T> {
|
||||
const bound = (): StateChannel => {
|
||||
@@ -141,10 +130,8 @@ export function state<T = unknown>(name: string): State<T> {
|
||||
};
|
||||
return {
|
||||
get: async (key) => (await bound().ask("mesh/state.get", { state: name, key })) as StateEntry<T> | null,
|
||||
put: async (key, value) => {
|
||||
withinOneCall(key, value);
|
||||
return ((await bound().ask("mesh/state.put", { state: name, key, value })) as { revision: number }).revision;
|
||||
},
|
||||
put: async (key, value) =>
|
||||
((await bound().ask("mesh/state.put", { state: name, key, value })) as { revision: number }).revision,
|
||||
delete: async (key) => {
|
||||
await bound().ask("mesh/state.delete", { state: name, key });
|
||||
},
|
||||
|
||||
+8
-24
@@ -14,10 +14,8 @@
|
||||
*/
|
||||
import type { ToolDefinition } from "../contracts/index.js";
|
||||
import { collectTools } from "../tools/index.js";
|
||||
import { useBroker, type Broker, type Envelope, type PublishOptions, type SubscribeOptions } from "../messaging/index.js";
|
||||
import { useBroker, type Broker, type Envelope } from "../messaging/index.js";
|
||||
import { useStateChannel, type StateChange } from "../state/index.js";
|
||||
import { useRuntime } from "../runtime/index.js";
|
||||
import { runAs } from "../callers/index.js";
|
||||
|
||||
/** The protocol version this speaks; the runtime says the same. */
|
||||
export const PROTOCOL = "2025-03-26";
|
||||
@@ -97,23 +95,15 @@ function startSession(): Session {
|
||||
// redelivered until it expires — the consumer's filter is the controller's and may be wider.
|
||||
const listeners: { pattern: string; handler: (env: Envelope<unknown>) => Promise<void> }[] = [];
|
||||
const viaRuntime: Broker = {
|
||||
publish: async <T>(env: Envelope<T>, options?: PublishOptions) => {
|
||||
if (!options?.ack) {
|
||||
await ask("mesh/publish", env);
|
||||
return;
|
||||
}
|
||||
// The runtime answers an acknowledged publish with the bus's sequence, or `{error}` (design 47 G §559).
|
||||
const answer = (await ask("mesh/publish", { ...env, ack: true })) as { error?: unknown } | null;
|
||||
if (answer && typeof answer === "object" && answer.error !== undefined) {
|
||||
throw new Error(`the bus did not acknowledge ${env.key}: ${String(answer.error)}`);
|
||||
}
|
||||
publish: async <T>(env: Envelope<T>) => {
|
||||
await ask("mesh/publish", env);
|
||||
},
|
||||
request: (async <Req, Res>(key: string, body: Req): Promise<Res> =>
|
||||
(await ask("mesh/ask", { key, body })) as Res) as Broker["request"],
|
||||
handle: (async () => {
|
||||
throw new Error("a launched bundle answers through its tools, not by binding subjects (novox/hq ADR 0193)");
|
||||
}) as Broker["handle"],
|
||||
subscribe: (async <T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>, options?: SubscribeOptions) => {
|
||||
subscribe: (async <T>(pattern: string, handler: (env: Envelope<T>) => Promise<void>) => {
|
||||
const listener = { pattern, handler: handler as (env: Envelope<unknown>) => Promise<void> };
|
||||
listeners.push(listener);
|
||||
const remove = (): void => {
|
||||
@@ -121,7 +111,7 @@ function startSession(): Session {
|
||||
if (at >= 0) listeners.splice(at, 1);
|
||||
};
|
||||
try {
|
||||
await ask("mesh/subscribe", options?.deliver ? { pattern, deliver: options.deliver } : { pattern });
|
||||
await ask("mesh/subscribe", { pattern });
|
||||
} catch (err) {
|
||||
// Refused: nothing is bound, and a handler left behind would be handed each event twice once
|
||||
// the module asks again (novox/hq issue 276).
|
||||
@@ -133,8 +123,6 @@ function startSession(): Session {
|
||||
close: async () => {},
|
||||
};
|
||||
useBroker(() => viaRuntime);
|
||||
// Every other method of the runtime a module's code asks (a seat's publish, its config): the same channel.
|
||||
useRuntime(ask);
|
||||
|
||||
let name = "bundle";
|
||||
let byName = new Map<string, ToolDefinition>();
|
||||
@@ -170,11 +158,7 @@ function startSession(): Session {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// The caller the runtime proved, in `_meta`, is held for these arguments while the tool runs (callerOf), never
|
||||
// read from the arguments (novox/hq issue 365).
|
||||
const given = request.params?.arguments;
|
||||
const args = (given && typeof given === "object" && !Array.isArray(given) ? given : {}) as Record<string, unknown>;
|
||||
const result = await runAs(request.params?._meta, args, () => tool.run(args));
|
||||
const result = await tool.run((request.params?.arguments as Record<string, unknown> | undefined) ?? {});
|
||||
say({ jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: JSON.stringify(result ?? null) }] } });
|
||||
} catch (err) {
|
||||
// The tool failed; said as a tool error, not a protocol one, because the call was well-formed.
|
||||
@@ -230,11 +214,11 @@ function startSession(): Session {
|
||||
continue; // not framed; nobody to answer
|
||||
}
|
||||
// The runtime's answer to something this bundle asked.
|
||||
const reply = request as unknown as { id?: string; method?: string; result?: unknown; error?: { message?: string; code?: number } };
|
||||
const reply = request as unknown as { id?: string; method?: string; result?: unknown; error?: { message?: string } };
|
||||
if (reply.method === undefined && typeof reply.id === "string" && awaiting.has(reply.id)) {
|
||||
const waiting = awaiting.get(reply.id)!;
|
||||
awaiting.delete(reply.id);
|
||||
if (reply.error) waiting.reject(Object.assign(new Error(reply.error.message ?? "the runtime refused"), { code: reply.error.code }));
|
||||
if (reply.error) waiting.reject(new Error(reply.error.message ?? "the runtime refused"));
|
||||
else waiting.resolve(reply.result);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
// The finding writer's transport in a tools bundle (design 47 G §559): a bundle holds no bus connection, so the writer says
|
||||
// each event through the runtime channel's `mesh/publish` with `ack: true` and makes its consumer of `findings-asked`
|
||||
// through `mesh/subscribe` with `deliver: new`. The runtime publishes on the subject the module's membership names for the
|
||||
// event, so the writer is handed the events' names (`finding-written`, and a seat's event by its local name
|
||||
// `<seat>.<event>`), not subjects.
|
||||
|
||||
import { broker } from "../messaging/index.js";
|
||||
import { CAP_FINDING_CALLS, requireCapability } from "../runtime/index.js";
|
||||
import type { EventHeaders } from "../contracts/index.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
/** The `publish` and `listen` of a writer's options, over the runtime channel of the bundle's process. */
|
||||
export function bundleTransport(module = process.env.MESH_MODULE ?? "unknown", node = process.env.MESH_NODE ?? "unknown"): {
|
||||
publish(event: string, body: unknown, id: string): Promise<void>;
|
||||
listen(event: string, handle: (body: unknown) => void): Promise<() => void>;
|
||||
} {
|
||||
return {
|
||||
publish: async (event, body, id) => {
|
||||
await requireCapability(CAP_FINDING_CALLS);
|
||||
const headers: EventHeaders = {
|
||||
"x-event-id": id || randomUUID(),
|
||||
"x-source": module,
|
||||
"x-node": node,
|
||||
"x-time": new Date().toISOString(),
|
||||
"content-type": "application/json",
|
||||
};
|
||||
await broker().publish({ key: event, node, body, headers }, { ack: true });
|
||||
},
|
||||
listen: async (event, handle) => {
|
||||
await requireCapability(CAP_FINDING_CALLS);
|
||||
return broker().subscribe(
|
||||
event,
|
||||
async (env) => {
|
||||
handle(env.body);
|
||||
},
|
||||
{ deliver: "new" },
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,613 +0,0 @@
|
||||
// A reader's first view of an owner's state, and its read and ask-again tools (novox/hq ADR 0615, ADR 0621; design 25
|
||||
// § 12.2; design 47 *The forge module's tools come from mesh-sdk's TypeScript side*): the TypeScript side of the Go
|
||||
// `views` package's Follower and StatusTools, with the same rules, so a TypeScript part answers `<module>_first_views`
|
||||
// and `<module>_first_view_again` as the Go parts do and keeps no follower of its own.
|
||||
//
|
||||
// A follower asks the owner's first view at its start (every page), then keeps its picture from the owner's events
|
||||
// alone, asking once more only on a gap in revisions (said in its log), never on a timer. Started while the owner is
|
||||
// down it keeps asking, waiting between asks, and past its bound raises its condition; the answer clears it. It names
|
||||
// no seat and no owner: the part hands it how to ask (a seat's verb through the seat's TypeScript contract, or an
|
||||
// owner's tool) and the events it hears, each in the form below.
|
||||
|
||||
import type { ToolDefinition } from "../contracts/index.js";
|
||||
import type { State } from "../state/index.js";
|
||||
import { callerOf } from "../callers/index.js";
|
||||
|
||||
/** The version of every value this writes and the only one it reads. */
|
||||
export const VERSION = 1;
|
||||
|
||||
/** The state in which a reader keeps each first view's status, as the Go side's `views.StatusState`. */
|
||||
export const STATUS_STATE = "first-views";
|
||||
|
||||
/** How long a reader asks before it raises its condition naming the owner and the tool (ADR 0615 §6), in ms. */
|
||||
export const BOUND_MS = 2 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* How long a part waits for a view before it writes its finding view-waits (design 47 *A part with no view says it
|
||||
* waits*), in ms: the Go side's `views.WaitsBound`, so an owner down for a restart raises nothing.
|
||||
*/
|
||||
export const WAITS_BOUND_MS = 5 * 60 * 1000;
|
||||
|
||||
/** The kind of a part's finding of a view it has waited for past WAITS_BOUND_MS: the Go side's `views.ViewWaitsKind`. */
|
||||
export const VIEW_WAITS_KIND = "view-waits";
|
||||
|
||||
/** The key of a reader's status of its first view of `owner`'s `state`. */
|
||||
export function statusKey(owner: string, state: string): string {
|
||||
return `${owner}.${state}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of a first view: the state's values by key, from `after` on, at the revision of the state the owner said up
|
||||
* to before it read them; `next` is the key to ask after for the rest, empty when the answer is whole. A reader keeps
|
||||
* the first page's revision.
|
||||
*/
|
||||
export interface Answer {
|
||||
readonly v?: number;
|
||||
readonly owner?: string;
|
||||
readonly state?: string;
|
||||
readonly revision: number;
|
||||
/** When the owner's state was made on the bus (RFC 3339): another one is a state made again. */
|
||||
readonly created: string;
|
||||
readonly values: Readonly<Record<string, unknown>>;
|
||||
readonly next?: string;
|
||||
readonly at?: string;
|
||||
/** When the owner's bus wrote each key (RFC 3339); a key whose time the owner does not say is absent. */
|
||||
readonly written?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
/** One change of one key of the owner's state, at the revision it was written at. */
|
||||
export interface ViewEvent {
|
||||
readonly v?: number;
|
||||
readonly owner?: string;
|
||||
readonly state?: string;
|
||||
readonly key: string;
|
||||
readonly revision: number;
|
||||
readonly created: string;
|
||||
readonly deleted?: boolean;
|
||||
readonly value?: unknown;
|
||||
readonly at?: string;
|
||||
/** The value was too large to carry: the reader asks its first view once. */
|
||||
readonly gap?: boolean;
|
||||
}
|
||||
|
||||
/** What a reader's read tool says of one first view: the Go side's `views.Status`, field for field. */
|
||||
export interface Status {
|
||||
owner: string;
|
||||
tool: string;
|
||||
state: string;
|
||||
revision: number;
|
||||
created?: string;
|
||||
keys: number;
|
||||
asked?: string;
|
||||
answered?: string;
|
||||
asks: number;
|
||||
"by-hand": number;
|
||||
raised: boolean;
|
||||
heard?: number;
|
||||
"heard-created"?: string;
|
||||
behind?: string;
|
||||
why?: string;
|
||||
error?: string;
|
||||
/**
|
||||
* The revision of the revision view the part holds from this first view, as its seat's client names it (design 47 *A
|
||||
* part with no view says it waits*); `waits-for` the one it waits for and acts on nothing new until it holds, since
|
||||
* `waiting-since`; `waits-raised` says its view-waits finding is written (past WAITS_BOUND_MS).
|
||||
*/
|
||||
view?: string;
|
||||
"waits-for"?: string;
|
||||
"waiting-since"?: string;
|
||||
"waits-raised"?: boolean;
|
||||
}
|
||||
|
||||
/** How a part makes a follower: the owner and the tool it asks (for the status and the log), and the hooks. */
|
||||
export interface FollowerOptions {
|
||||
readonly owner: string;
|
||||
readonly tool: string;
|
||||
readonly state: string;
|
||||
/** Ask the owner for the page after `after` (empty: the first). */
|
||||
readonly ask: (after: string) => Promise<Answer>;
|
||||
/** The reader's condition of this first view: raised past the bound, cleared by the answer. */
|
||||
readonly raise?: (s: Status) => void | Promise<void>;
|
||||
readonly clear?: (s: Status) => void | Promise<void>;
|
||||
/** The part's view-waits finding: written past WAITS_BOUND_MS of a waitFor, cleared when it holds the view. */
|
||||
readonly raiseWaits?: (s: Status) => void | Promise<void>;
|
||||
readonly clearWaits?: (s: Status) => void | Promise<void>;
|
||||
/** Told of each key the picture changes, after the change is held. */
|
||||
readonly changed?: (key: string, value: unknown, deleted: boolean, at: string) => void | Promise<void>;
|
||||
/** Told of the status each time an ask starts, is answered or fails, and of each event taken: where a reader keeps it. */
|
||||
readonly said?: (s: Status) => void | Promise<void>;
|
||||
readonly log?: (line: string) => void;
|
||||
readonly now?: () => Date;
|
||||
/** How long it asks before it raises, in ms; BOUND_MS when absent. */
|
||||
readonly bound?: number;
|
||||
/** The first wait between two asks that failed, in ms, doubling to a minute; five seconds when absent. */
|
||||
readonly wait?: number;
|
||||
/** Waits ms between two asks; a test hands one that does not sleep. */
|
||||
readonly pause?: (ms: number) => Promise<void>;
|
||||
/** Waits out WAITS_BOUND_MS of a waitFor; a test hands one it ends itself. Absent: a timer that holds no process open. */
|
||||
readonly waitsBound?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
const ms = (t: string | undefined): number => (t ? Date.parse(t) || 0 : 0);
|
||||
|
||||
/** A reader's picture of one state of an owner, kept from its first view and its events. */
|
||||
export class Follower {
|
||||
private readonly o: FollowerOptions;
|
||||
private values = new Map<string, unknown>();
|
||||
private st: Status;
|
||||
private asking = false;
|
||||
private catching = false;
|
||||
private during: ViewEvent[] = [];
|
||||
private heardRev = 0;
|
||||
private heardCreated = "";
|
||||
private answered = false;
|
||||
private closed = false;
|
||||
private markReady!: () => void;
|
||||
/** Resolves once a first view was answered. */
|
||||
readonly ready: Promise<void>;
|
||||
|
||||
constructor(o: FollowerOptions) {
|
||||
this.o = o;
|
||||
this.st = { owner: o.owner, tool: o.tool, state: o.state, revision: 0, keys: 0, asks: 0, "by-hand": 0, raised: false };
|
||||
this.ready = new Promise((resolve) => (this.markReady = resolve));
|
||||
}
|
||||
|
||||
get owner(): string {
|
||||
return this.o.owner;
|
||||
}
|
||||
get state(): string {
|
||||
return this.o.state;
|
||||
}
|
||||
get tool(): string {
|
||||
return this.o.tool;
|
||||
}
|
||||
|
||||
private now(): string {
|
||||
return (this.o.now ? this.o.now() : new Date()).toISOString();
|
||||
}
|
||||
|
||||
private log(line: string): void {
|
||||
this.o.log?.(line);
|
||||
}
|
||||
|
||||
private pause(wait: number): Promise<void> {
|
||||
return this.o.pause ? this.o.pause(wait) : new Promise((resolve) => setTimeout(resolve, wait));
|
||||
}
|
||||
|
||||
/** The status now, with the keys held, the highest revision heard and why the picture is behind it. */
|
||||
status(): Status {
|
||||
const s: Status = { ...this.st, keys: this.values.size };
|
||||
if (this.heardRev) s.heard = this.heardRev;
|
||||
if (this.heardCreated) s["heard-created"] = this.heardCreated;
|
||||
const behind = this.behind();
|
||||
if (behind) s.behind = behind;
|
||||
else delete s.behind;
|
||||
return s;
|
||||
}
|
||||
|
||||
private async say(): Promise<void> {
|
||||
if (this.o.said) {
|
||||
try {
|
||||
await this.o.said(this.status());
|
||||
} catch (err) {
|
||||
this.log(`views: the status of the first view ${this.o.tool} is not kept: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A copy of the picture. */
|
||||
picture(): Map<string, unknown> {
|
||||
return new Map(this.values);
|
||||
}
|
||||
|
||||
/** One key of the picture. */
|
||||
get(key: string): unknown {
|
||||
return this.values.get(key);
|
||||
}
|
||||
|
||||
/** Why the picture is behind an event heard, or "" when it holds every revision heard. */
|
||||
behind(): string {
|
||||
if (!this.heardCreated) return "";
|
||||
if (ms(this.heardCreated) > ms(this.st.created)) {
|
||||
return `the state was made again at ${this.heardCreated}, the picture holds the one made at ${this.st.created ?? "none"}`;
|
||||
}
|
||||
if (ms(this.heardCreated) === ms(this.st.created) && this.heardRev > this.st.revision) {
|
||||
return `revision ${this.heardRev} heard, the picture holds ${this.st.revision}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Say the part waits for `view`, a revision of the revision view its seat's client names, and acts on nothing new
|
||||
* until it holds it (holds): the status says what and since when, and if it still waits for it past WAITS_BOUND_MS,
|
||||
* raiseWaits is told (the part writes view-waits, viewWaitsFinding). Waiting for the view it waits for already changes
|
||||
* nothing, not even since when. Resolves once the status is said; the bound runs on by itself.
|
||||
*/
|
||||
async waitFor(view: string): Promise<void> {
|
||||
if (!view || this.st["waits-for"] === view) return;
|
||||
this.st["waits-for"] = view;
|
||||
this.st["waiting-since"] = this.now();
|
||||
this.st["waits-raised"] = false;
|
||||
this.log(`views: ${this.o.tool} waits for ${this.o.owner}'s view ${view}, from ${this.st["waiting-since"]}`);
|
||||
await this.say();
|
||||
void this.boundWaits(view);
|
||||
}
|
||||
|
||||
private async boundWaits(view: string): Promise<void> {
|
||||
const bound = this.o.waitsBound ?? ((wait: number) => new Promise<void>((resolve) => setTimeout(resolve, wait).unref?.()));
|
||||
await bound(WAITS_BOUND_MS);
|
||||
if (this.closed || this.st["waits-for"] !== view || this.st["waits-raised"]) return;
|
||||
this.st["waits-raised"] = true;
|
||||
this.log(`views: ${this.o.tool} has waited for ${this.o.owner}'s view ${view} since ${this.st["waiting-since"]}`);
|
||||
try {
|
||||
await this.o.raiseWaits?.(this.status());
|
||||
} catch (err) {
|
||||
this.log(`views: the view-waits of ${this.o.tool} is not written: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
await this.say();
|
||||
}
|
||||
|
||||
/** Say the part holds `view` now: it waits no more, and a raised view-waits is cleared (clearWaits). */
|
||||
async holds(view: string): Promise<void> {
|
||||
const raised = !!this.st["waits-raised"];
|
||||
this.st.view = view;
|
||||
delete this.st["waits-for"];
|
||||
delete this.st["waiting-since"];
|
||||
delete this.st["waits-raised"];
|
||||
if (raised) {
|
||||
try {
|
||||
await this.o.clearWaits?.(this.status());
|
||||
} catch (err) {
|
||||
this.log(`views: the view-waits of ${this.o.tool} is not cleared: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
await this.say();
|
||||
}
|
||||
|
||||
/** Ask the first view until it is answered (ADR 0615 §6); resolves once answered, or once the follower is closed. */
|
||||
start(): Promise<void> {
|
||||
return this.askUntil("start", false);
|
||||
}
|
||||
|
||||
/** Ask the first view once more by hand (the re-read tool, recorded by its caller as a hand act). */
|
||||
again(why: string): Promise<void> {
|
||||
return this.askUntil(`by hand: ${why}`, true);
|
||||
}
|
||||
|
||||
/** Ask the first view once more for a gap the reader saw: counted among its asks, never among those by hand. */
|
||||
gap(why: string): Promise<void> {
|
||||
return this.askUntil(`a gap: ${why}`, false);
|
||||
}
|
||||
|
||||
/** Stop asking: a loop waiting between two asks ends at its next turn. */
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
private async askUntil(why: string, byHand: boolean): Promise<void> {
|
||||
if (this.asking) return; // one ask at a time; the one running brings the picture to its newest
|
||||
this.asking = true;
|
||||
this.during = [];
|
||||
this.st.why = why;
|
||||
if (byHand) this.st["by-hand"]++;
|
||||
const bound = this.o.bound ?? BOUND_MS;
|
||||
let wait = this.o.wait ?? 5000;
|
||||
const first = ms(this.now());
|
||||
try {
|
||||
while (!this.closed) {
|
||||
let failed: unknown;
|
||||
try {
|
||||
await this.askOnce();
|
||||
} catch (err) {
|
||||
failed = err ?? new Error("the ask failed");
|
||||
}
|
||||
if (failed === undefined) {
|
||||
// An event heard that the answer does not hold yet leaves the picture behind: asked once more, by itself.
|
||||
this.asking = false;
|
||||
const behind = this.behind();
|
||||
if (behind && !this.catching) {
|
||||
this.catching = true;
|
||||
this.log(`views: ${this.o.owner}'s ${this.o.state} is behind an event heard (${behind}): its first view ${this.o.tool} is asked once more`);
|
||||
void this.catchUp();
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.st.error = failed instanceof Error ? failed.message : String(failed);
|
||||
const raise = !this.st.raised && ms(this.now()) - first >= bound;
|
||||
if (raise) this.st.raised = true;
|
||||
this.log(`the first view ${this.o.tool} of ${this.o.owner}'s ${this.o.state} is not answered (${this.st.error}): asked again in ${wait} ms`);
|
||||
if (raise) await this.o.raise?.(this.status());
|
||||
await this.say();
|
||||
await this.pause(wait);
|
||||
wait = Math.min(wait * 2, 60_000);
|
||||
}
|
||||
} finally {
|
||||
this.asking = false;
|
||||
}
|
||||
}
|
||||
|
||||
// catchUp asks once more, each time after a pause (doubling to a minute, so an owner that answers from before its
|
||||
// last write is not asked in a hot loop), until the picture holds every revision heard. One at a time: while it runs,
|
||||
// an answered ask starts no other.
|
||||
private async catchUp(): Promise<void> {
|
||||
let wait = this.o.wait ?? 5000;
|
||||
try {
|
||||
while (!this.closed) {
|
||||
await this.pause(wait);
|
||||
const behind = this.behind();
|
||||
if (!behind || this.closed) return;
|
||||
this.log(`views: ${this.o.owner}'s ${this.o.state} is still behind (${behind}): its first view ${this.o.tool} is asked once more`);
|
||||
await this.askUntil(`behind: ${behind}`, false);
|
||||
wait = Math.min(wait * 2, 60_000);
|
||||
}
|
||||
} finally {
|
||||
this.catching = false;
|
||||
}
|
||||
}
|
||||
|
||||
// askOnce asks every page and, once whole, takes it as the picture.
|
||||
private async askOnce(): Promise<void> {
|
||||
this.st.asked = this.now();
|
||||
this.st.asks++;
|
||||
await this.say();
|
||||
let firstPage: Answer | undefined;
|
||||
const values = new Map<string, unknown>();
|
||||
const written = new Map<string, string>();
|
||||
let after = "";
|
||||
for (;;) {
|
||||
const a = await this.o.ask(after);
|
||||
if (a.v !== undefined && a.v !== VERSION) throw new Error(`views: unknown value version ${a.v}: this reader reads ${VERSION}`);
|
||||
firstPage ??= a;
|
||||
for (const [k, v] of Object.entries(a.values ?? {})) values.set(k, v);
|
||||
for (const [k, t] of Object.entries(a.written ?? {})) written.set(k, t);
|
||||
if (!a.next || a.next === after) break;
|
||||
after = a.next;
|
||||
}
|
||||
const old = this.values;
|
||||
this.values = values;
|
||||
const wasRaised = this.st.raised;
|
||||
this.st.revision = firstPage!.revision;
|
||||
this.st.created = firstPage!.created;
|
||||
this.st.answered = this.now();
|
||||
this.st.raised = false;
|
||||
delete this.st.error;
|
||||
// The events heard while it asked, after the answer's revision and in order, are taken again.
|
||||
const during = [...this.during].sort((x, y) => x.revision - y.revision);
|
||||
this.during = [];
|
||||
for (const ev of during) {
|
||||
if (ms(ev.created) === ms(this.st.created) && ev.revision === this.st.revision + 1 && !ev.gap) {
|
||||
if (ev.deleted) this.values.delete(ev.key);
|
||||
else this.values.set(ev.key, ev.value);
|
||||
if (ev.at) written.set(ev.key, ev.at);
|
||||
this.st.revision = ev.revision;
|
||||
}
|
||||
}
|
||||
if (!this.answered) {
|
||||
this.answered = true;
|
||||
this.markReady();
|
||||
}
|
||||
if (wasRaised) await this.o.clear?.(this.status());
|
||||
await this.say();
|
||||
if (this.o.changed) {
|
||||
for (const [k, v] of this.values) {
|
||||
if (!old.has(k) || JSON.stringify(old.get(k)) !== JSON.stringify(v)) await this.o.changed(k, v, false, written.get(k) ?? "");
|
||||
}
|
||||
for (const k of old.keys()) if (!this.values.has(k)) await this.o.changed(k, undefined, true, "");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Take one event into the picture and say whether it was a gap: another `created` (the owner's state made again), a
|
||||
* revision past the one after the picture's, or a value too large to carry. A revision at or below the picture's is
|
||||
* in it already and is passed over; so is any event before the first view is answered (the answer holds it).
|
||||
*/
|
||||
async apply(ev: ViewEvent): Promise<{ gap: boolean; why: string }> {
|
||||
if (ev.v !== undefined && ev.v !== VERSION) throw new Error(`views: unknown value version ${ev.v}: this reader reads ${VERSION}`);
|
||||
if (!ev.key || !ev.revision) throw new Error("views: an event names no key or revision");
|
||||
if (ms(ev.created) > ms(this.heardCreated)) {
|
||||
this.heardCreated = ev.created;
|
||||
this.heardRev = ev.revision;
|
||||
} else if (ms(ev.created) === ms(this.heardCreated) && ev.revision > this.heardRev) {
|
||||
this.heardRev = ev.revision;
|
||||
}
|
||||
if (this.asking) this.during.push(ev);
|
||||
if (!this.answered) {
|
||||
this.log(`views: ${this.o.owner}'s ${this.o.state} at revision ${ev.revision} was heard before its first view was answered: passed over, the answer holds it or is asked again`);
|
||||
return { gap: false, why: "" };
|
||||
}
|
||||
let why = "";
|
||||
if (ms(ev.created) !== ms(this.st.created)) {
|
||||
why = `${this.o.owner}'s ${this.o.state} was made again (or not marked when the first view was answered): created ${ev.created}, held ${this.st.created ?? "none"}`;
|
||||
} else if (ev.revision <= this.st.revision) {
|
||||
this.log(`views: ${this.o.owner}'s ${this.o.state} at revision ${ev.revision} is in the picture already (it holds ${this.st.revision}): passed over`);
|
||||
return { gap: false, why: "" };
|
||||
} else if (ev.revision > this.st.revision + 1) {
|
||||
why = `${this.o.owner}'s ${this.o.state} at revision ${ev.revision}, the picture holds ${this.st.revision}: ${ev.revision - this.st.revision - 1} changes missed`;
|
||||
} else if (ev.gap) {
|
||||
why = `${this.o.owner}'s ${this.o.state}.${ev.key} at revision ${ev.revision} was too large to carry`;
|
||||
}
|
||||
if (why) return { gap: true, why };
|
||||
if (ev.deleted) this.values.delete(ev.key);
|
||||
else this.values.set(ev.key, ev.value);
|
||||
this.st.revision = ev.revision;
|
||||
await this.say(); // the revision the picture holds follows the events, not only the asks
|
||||
await this.o.changed?.(ev.key, ev.value, !!ev.deleted, ev.at ?? "");
|
||||
return { gap: false, why: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* A reader's handler of one event: taken into the picture, and a gap asks the first view once more, said in the log
|
||||
* and not waited for (the event is taken; the ask brings the picture to its newest).
|
||||
*/
|
||||
async hear(ev: ViewEvent): Promise<void> {
|
||||
const { gap, why } = await this.apply(ev);
|
||||
if (gap) {
|
||||
this.log(`views: a gap in ${this.o.state} (${why}): its first view ${this.o.tool} is asked once more`);
|
||||
void this.gap(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a views part says is wrong with a state it follows, in plain fields, as the Go side's `views.Finding`: the writer
|
||||
* the part gives encodes it as the condition keeper reads it, which is the seat mesh-conditions' contract, not this
|
||||
* package's (novox/hq ADR 0634 §4).
|
||||
*/
|
||||
export interface Finding {
|
||||
readonly observer: string;
|
||||
readonly kind: string;
|
||||
readonly id: string;
|
||||
readonly summary: string;
|
||||
readonly headline: string;
|
||||
readonly explanation: string;
|
||||
readonly at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A part's finding of the view it has waited for since `s["waiting-since"]` (design 47), as the Go side's
|
||||
* `views.ViewWaitsFinding`: it names the part, the owner and the revision, and clears when the part holds it.
|
||||
*/
|
||||
export function viewWaitsFinding(part: string, s: Status, at: Date): Finding {
|
||||
const since = s["waiting-since"] ? new Date(s["waiting-since"]).toISOString().replace(/\.\d{3}Z$/, "Z") : "";
|
||||
return {
|
||||
observer: part,
|
||||
kind: VIEW_WAITS_KIND,
|
||||
id: `${part}.${s.owner}.${s.state}`,
|
||||
summary: `${part} waits for ${s.owner}'s view ${s["waits-for"] ?? ""} since ${since} and acts on nothing new until it holds it; it holds ${s.view || "none"}`,
|
||||
headline: `${part} waits for a view of ${s.owner}`,
|
||||
explanation:
|
||||
`${part} keeps running what it runs and takes up nothing new until ${s.owner}'s view ${s["waits-for"] ?? ""} reaches it. Look at ${s.owner}: is it running, and has it ` +
|
||||
`said that revision? ${part}'s first views tool says what it holds and waits for.`,
|
||||
at: at.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The kinds a views reader's findings written through the part's writer are of, and the one that is urgent (design 47 G §687). */
|
||||
const TOO_LARGE_KIND = "view-too-large";
|
||||
|
||||
/** A name as a key's part (design 47 G §73): a character outside letters, digits, `-`, `/` and `_` is `=` and its two lowercase hex digits per byte. */
|
||||
export function escapeName(name: string): string {
|
||||
let out = "";
|
||||
for (const b of new TextEncoder().encode(name)) {
|
||||
const c = String.fromCharCode(b);
|
||||
out += /[A-Za-z0-9\-/_]/.test(c) ? c : `=${b.toString(16).padStart(2, "0")}`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A views reader's finding laid out in its wire form by mesh-sdk (design 47 G §687): `kind` the finding's, `scope` module,
|
||||
* `id` the finding's id escaped as a key's name is, `severity` warning but urgent for view-too-large, `source` views,
|
||||
* `subject` the part's module on its node, `summary` and `headline` the finding's texts. The Go side's `views.WriterFindings`.
|
||||
*/
|
||||
export function viewFindingBody(f: Finding, module: string, node: string): Record<string, unknown> {
|
||||
return {
|
||||
kind: f.kind,
|
||||
scope: "module",
|
||||
id: escapeName(f.id),
|
||||
severity: f.kind === TOO_LARGE_KIND ? "urgent" : "warning",
|
||||
source: "views",
|
||||
subject: { scope: "module", id: module, ...(node ? { machine: node } : {}) },
|
||||
summary: f.summary,
|
||||
...(f.headline ? { headline: f.headline } : {}),
|
||||
...(f.at ? { at: f.at } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The part of a Writer a views reader's findings use, whatever the contract's body types. */
|
||||
export interface WireWriter {
|
||||
write(finding: any): Promise<void>;
|
||||
clear(scope: string, id: string, kind: string, why: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** A views reader's findings written through the part's writer, as kinds of the reader's own (design 47 G §639, §687). */
|
||||
export function writerFindings(writer: WireWriter, module: string, node: string): { put(f: Finding): Promise<void>; delete(f: Finding): Promise<void> } {
|
||||
return {
|
||||
put: (f) => writer.write(viewFindingBody(f, module, node)),
|
||||
delete: (f) => writer.clear("module", escapeName(f.id), f.kind, "the part no longer observes it"),
|
||||
};
|
||||
}
|
||||
|
||||
/** A Follower's `said` that keeps its status at statusKey in the reader's state STATUS_STATE. */
|
||||
export function keepStatus(st: State<Status>): (s: Status) => Promise<void> {
|
||||
return async (s) => {
|
||||
await st.put(statusKey(s.owner, s.state), s);
|
||||
};
|
||||
}
|
||||
|
||||
/** A hand act a part records before it does it (ADR 0565 clause 11): what is done, why, and its cause and verb. */
|
||||
export interface HandAct {
|
||||
readonly what: string;
|
||||
readonly why: string;
|
||||
readonly cause: string;
|
||||
readonly verb: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A reader's read tool of its first views (`read`) and its re-read tool (`again`), as the Go side's StatusTools: read
|
||||
* lists what each follower last said, kept in `st` (STATUS_STATE); again records a hand act through `acts` (none
|
||||
* given: refused, nothing asked), then asks that follower's first view again, naming the caller the runtime proved.
|
||||
*/
|
||||
export function statusTools(
|
||||
reader: string,
|
||||
read: string,
|
||||
again: string,
|
||||
followers: readonly Follower[],
|
||||
st: State<Status>,
|
||||
acts: ((act: HandAct) => Promise<void>) | undefined,
|
||||
): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: read,
|
||||
description:
|
||||
`${reader}'s first views of the owners' states it follows (novox/hq ADR 0615): per owner and state, the tool it asks, the ` +
|
||||
"revision its picture holds now (events taken in included), the highest revision it heard and why it is behind it, if it " +
|
||||
"is, when it asked and was answered, how many asks (by hand among them) and whether its condition (unanswered past two " +
|
||||
"minutes) is raised; and the revision of the revision view it holds, the one it waits for and acts on nothing new until it " +
|
||||
"holds, since when, and whether its view-waits finding (past five minutes) is written.",
|
||||
input: { type: "object", properties: {} },
|
||||
run: async () => {
|
||||
const out: Status[] = [];
|
||||
for (const k of await st.keys()) {
|
||||
const e = await st.get(k);
|
||||
if (e?.value && typeof e.value === "object") out.push(e.value);
|
||||
}
|
||||
return { "first-views": out };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: again,
|
||||
description:
|
||||
`Ask ${reader}'s first view of an owner's state again now, by hand (a hand act, its caller and why kept in the status ` +
|
||||
`${read} reads): for a picture a person doubts. The part asks once and follows the owner's events after the answer.`,
|
||||
input: {
|
||||
type: "object",
|
||||
required: ["owner", "state", "why"],
|
||||
properties: {
|
||||
owner: { type: "string", description: "the owner, as the read tool names it" },
|
||||
state: { type: "string", description: "the owner's state, as the read tool names it" },
|
||||
why: { type: "string", description: "why it is asked again, in plain words" },
|
||||
},
|
||||
},
|
||||
run: async (args) => {
|
||||
const owner = typeof args.owner === "string" ? args.owner : "";
|
||||
const state = typeof args.state === "string" ? args.state : "";
|
||||
const why = typeof args.why === "string" ? args.why.trim() : "";
|
||||
if (!owner || !state || !why) throw new Error("again names the owner, the state and why");
|
||||
const f = followers.find((x) => x.owner === owner && x.state === state);
|
||||
if (!f) throw new Error(`${reader} holds no first view of ${owner}'s ${state}`);
|
||||
const by = callerOf(args);
|
||||
if (!acts) throw new Error("the hand act was not recorded, so nothing was asked again: no way to record a hand act is given");
|
||||
try {
|
||||
await acts({ what: `asked ${reader}'s first view of ${owner}'s ${state} again by hand`, why, cause: "first-view-again", verb: again });
|
||||
} catch (err) {
|
||||
throw new Error(`the hand act was not recorded, so nothing was asked again: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
void f.again(`${why} (${by})`);
|
||||
return { asked: { owner, state, why, by }, read };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
export * from "./writer.js";
|
||||
export * from "./bundle.js";
|
||||
@@ -1,349 +0,0 @@
|
||||
// The finding writer, TypeScript side (design 47 G §461, §485, §503): the same acts as the Go `views` writer, with the
|
||||
// same rules, for the observers written in TypeScript, generic over the contract's body types (plain structures) and
|
||||
// working on their wire form, with no layout of a finding of its own (design 47 G A-3, §640). It keeps an observer's findings in its own state
|
||||
// `findings` and says them as events (§383, §384). It names the four events itself (design 47 G A-13, A-17): it says
|
||||
// `finding-written`, `finding-cleared` and `findings-stated` by their names, which the runtime publishes on the subject the
|
||||
// module's membership names for each; the event `findings-asked` is the seat's and is given as `asked` (A-17: mesh-sdk names no seat).
|
||||
// Its acts, `write`, `clear` and a statement, run one at a time in the order they are asked, on one chain of promises.
|
||||
|
||||
import type { State } from "../state/index.js";
|
||||
|
||||
/** The events the writer says, by their names (design 47 G §383, A-13). */
|
||||
export const FINDING_WRITTEN_EVENT = "finding-written";
|
||||
export const FINDING_CLEARED_EVENT = "finding-cleared";
|
||||
export const FINDINGS_STATED_EVENT = "findings-stated";
|
||||
|
||||
/** How long an event the bus did not acknowledge is sent again before it is logged as an error (§383). */
|
||||
export const PUBLISH_RETRY_MS = 60 * 1000;
|
||||
/** How often a failing `observe` is called again until a set is said (§485). */
|
||||
export const OBSERVE_RETRY_MS = 60 * 1000;
|
||||
|
||||
/**
|
||||
* What the writer needs of a contract's finding body (design 47 G A-3, §640): the fields it reads and sets by their
|
||||
* contract names. The body types are the seat generator's, plain structures; a body type lacking one of these fields
|
||||
* does not compile as the writer's `F`, and a value lacking its `subject` is refused at its first write.
|
||||
*/
|
||||
export interface FindingFields {
|
||||
kind: string;
|
||||
scope: string;
|
||||
id: string;
|
||||
subject: object;
|
||||
at?: string;
|
||||
since?: string;
|
||||
observer?: string;
|
||||
owner?: string;
|
||||
"waiting-on"?: string;
|
||||
}
|
||||
|
||||
/** A body in its wire form (design 47 G A-3). */
|
||||
type Wire = Record<string, unknown>;
|
||||
|
||||
/** A key the observer cannot judge yet since its start: its `since` and its bound (a duration such as `5m`). */
|
||||
export interface PendingKey {
|
||||
key: string;
|
||||
since: string;
|
||||
bound: string;
|
||||
}
|
||||
|
||||
/** What the observer's own truth says now: its findings, in the contract's finding type, and its pending keys. */
|
||||
export interface Observed<F> {
|
||||
findings: F[];
|
||||
pending: PendingKey[];
|
||||
}
|
||||
|
||||
/** The finding kinds a views reader writes through the part's writer (design 47 G §639). */
|
||||
export const VIEW_KINDS = ["view-waits", "first-view-unanswered", "view-unsaid", "view-too-large"];
|
||||
|
||||
const SESSION_FORM = /^[a-z0-9][a-z0-9._-]*@[a-z0-9][a-z0-9-]*$/;
|
||||
const SEAT_FORM = /^[a-z][a-z0-9-]*$/;
|
||||
const AUTHOR_FORM = /^forge:[A-Za-z0-9._-]+$/;
|
||||
|
||||
/** A finding's `owner` or `waiting-on` is a session (who@node), a seat's name or a commit's author (design 47 G §678). */
|
||||
function formOfWho(field: string, v: unknown): void {
|
||||
if (v === undefined || v === null || v === "") return;
|
||||
if (typeof v === "string" && (SESSION_FORM.test(v) || SEAT_FORM.test(v) || AUTHOR_FORM.test(v))) return;
|
||||
throw new Error(`the finding's ${field} "${v}" is none of a session (who@node), a seat's name or a commit's author (forge:<account>)`);
|
||||
}
|
||||
|
||||
/** The key of a finding in the state `findings`: `<scope>.<id>.<kind>`. */
|
||||
export function findingKey(scope: string, id: string, kind: string): string {
|
||||
return `${scope}.${id}.${kind}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse a finding the keeper could not make a condition of, naming the field of the first rule it breaks: the key's three
|
||||
* parts (each given, the kind with no dot, since the kind is the key's last part), the subject, and the forms of `owner`
|
||||
* and `waiting-on` (design 47 G §678, §689, A-3). It judges the finding's wire form: the contract's generated type is one.
|
||||
*/
|
||||
export function checkFinding(finding: object): void {
|
||||
const m = finding as Wire;
|
||||
const given = (f: string): boolean => typeof m[f] === "string" && (m[f] as string).trim() !== "";
|
||||
if (!given("scope")) throw new Error("the finding's scope is not given");
|
||||
if (!given("id")) throw new Error("the finding's id is not given");
|
||||
if (!given("kind")) throw new Error("the finding's kind is not given");
|
||||
if ((m.kind as string).includes(".")) throw new Error(`the finding's kind "${m.kind}" holds a dot, and the kind is the last part of its key`);
|
||||
if (!m.subject || typeof m.subject !== "object") throw new Error("the finding's subject is not given, and the contract's finding names it");
|
||||
formOfWho("owner", m.owner);
|
||||
formOfWho("waiting-on", m["waiting-on"]);
|
||||
}
|
||||
|
||||
export interface WriterOptions<F extends FindingFields, C extends object, S extends object, A extends object> {
|
||||
/** The observer's module name: it fills the `observer` of a finding and tells an ask for another module. */
|
||||
module: string;
|
||||
/** The observer's own state `findings`. */
|
||||
state: State<F>;
|
||||
/** The event the writer hears `findings-asked` as: the seat's, which the module fills from the seat's generated contract (design 47 G A-17). */
|
||||
asked: string;
|
||||
/** The finding kinds this writer owns (design 47 G §580): a write or clear of another kind is refused, naming it, and a statement carries them as `kinds` and deletes only keys of them. None: every kind. The views reader's kinds are always its own besides. */
|
||||
kinds?: string[];
|
||||
/** The findings the observer observes now and its pending keys. It is called inside the writer's one chain: it must not call `write` or `clear`. */
|
||||
observe(): Promise<Observed<F>>;
|
||||
/** Say one event, by its name, and resolve when the bus acknowledged it; `id` is the bus's de-duplication id. */
|
||||
publish(subject: string, body: F | C | S, id: string): Promise<void>;
|
||||
/** Make a consumer of the event `subject` names that delivers only the messages published after it is made; resolves to its stop. */
|
||||
listen(subject: string, handle: (body: A) => void): Promise<() => void>;
|
||||
/** Put a set larger than one bus message in the observer's sent store; resolves to what to publish instead. */
|
||||
send?(label: string, body: unknown): Promise<unknown>;
|
||||
log?(line: string): void;
|
||||
now?(): Date;
|
||||
/** Pause for `ms`; resolve false when the writer closed. */
|
||||
wait?(ms: number): Promise<boolean>;
|
||||
}
|
||||
|
||||
/** The finding writer of an observer: `F`, `C`, `S` and `A` are the contract's bodies of `finding-written`, `finding-cleared`, `findings-stated` and `findings-asked`. */
|
||||
export class Writer<F extends FindingFields, C extends object, S extends object, A extends object> {
|
||||
private readonly o: WriterOptions<F, C, S, A>;
|
||||
private chain: Promise<unknown> = Promise.resolve();
|
||||
private seq = 0;
|
||||
private stop?: () => void;
|
||||
private asks: string[] = [];
|
||||
private busy = false;
|
||||
private closed = false;
|
||||
private readonly closing: Promise<void>;
|
||||
private close_!: () => void;
|
||||
|
||||
constructor(o: WriterOptions<F, C, S, A>) {
|
||||
this.o = o;
|
||||
this.closing = new Promise((r) => (this.close_ = r));
|
||||
}
|
||||
|
||||
private owns(kind: string): boolean {
|
||||
return !this.o.kinds?.length || this.o.kinds.includes(kind) || VIEW_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
private log(line: string): void {
|
||||
this.o.log?.(line);
|
||||
}
|
||||
private now(): Date {
|
||||
return this.o.now ? this.o.now() : new Date();
|
||||
}
|
||||
private stamp(d: Date): string {
|
||||
return d.toISOString();
|
||||
}
|
||||
private async pause(ms: number): Promise<boolean> {
|
||||
if (this.o.wait) return this.o.wait(ms);
|
||||
return new Promise((resolve) => {
|
||||
const t = setTimeout(() => resolve(!this.closed), ms);
|
||||
void this.closing.then(() => {
|
||||
clearTimeout(t);
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Run `act` after every act asked before it has ended. */
|
||||
private act<T>(act: () => Promise<T>): Promise<T> {
|
||||
const run = this.chain.then(act, act);
|
||||
this.chain = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the consumer of `findings-asked`, then state the findings now; later each ask for this module (or for none) is
|
||||
* answered by a statement. Resolves once the consumer exists; the start statement, retried every minute until `observe`
|
||||
* answers, runs on.
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
await this.listen();
|
||||
this.request("");
|
||||
}
|
||||
|
||||
/** The bus connection was made again: make the consumer again, from the newest ask, and state the findings again (§485). */
|
||||
async reconnected(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
try {
|
||||
await this.listen();
|
||||
} catch (e) {
|
||||
this.log(`error: the finding writer could not make its consumer of ${this.o.asked} again: ${e}`);
|
||||
}
|
||||
this.request("");
|
||||
}
|
||||
|
||||
/** End the consumer and the statements. */
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.stop?.();
|
||||
this.stop = undefined;
|
||||
this.close_();
|
||||
}
|
||||
|
||||
private async listen(): Promise<void> {
|
||||
const stop = await this.o.listen(this.o.asked, (body) => this.heard(body));
|
||||
this.stop?.();
|
||||
this.stop = stop;
|
||||
}
|
||||
|
||||
private heard(body: unknown): void {
|
||||
const a = body as Wire | null;
|
||||
if (!a || typeof a.ask !== "string") {
|
||||
this.log("an ask for findings could not be read");
|
||||
return;
|
||||
}
|
||||
if (a.module && a.module !== this.o.module) return;
|
||||
this.request(a.ask);
|
||||
}
|
||||
|
||||
private request(ask: string): void {
|
||||
this.asks.push(ask);
|
||||
if (this.busy) return;
|
||||
this.busy = true;
|
||||
void this.drain();
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
while (this.asks.length > 0 && !this.closed) {
|
||||
const asked = this.asks[this.asks.length - 1];
|
||||
this.asks = [];
|
||||
for (;;) {
|
||||
try {
|
||||
await this.state(asked);
|
||||
break;
|
||||
} catch (e) {
|
||||
this.log(`the findings could not be stated, no set said, trying again in ${OBSERVE_RETRY_MS / 1000}s: ${e}`);
|
||||
if (!(await this.pause(OBSERVE_RETRY_MS))) {
|
||||
this.busy = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.busy = false;
|
||||
}
|
||||
|
||||
/** Keep the finding in its key and say `finding-written` only when what it says changed; the key's `since` stays. */
|
||||
write(f: F): Promise<void> {
|
||||
return this.act(async () => {
|
||||
const [full, old] = await this.complete(f);
|
||||
await this.o.state.put(key(full), full as unknown as F);
|
||||
if (old && unsaid(old) === unsaid(full)) return;
|
||||
await this.say(FINDING_WRITTEN_EVENT, "finding-written", key(full), full as unknown as F);
|
||||
});
|
||||
}
|
||||
|
||||
/** Delete the key and say `finding-cleared`, also of a key that does not exist, so a keeper holding it clears it. */
|
||||
clear(scope: string, id: string, kind: string, why: string): Promise<void> {
|
||||
return this.act(async () => {
|
||||
if (!this.owns(kind)) throw new Error(`the finding kind "${kind}" is not one this writer owns (${this.o.kinds})`);
|
||||
const k = findingKey(scope, id, kind);
|
||||
await this.o.state.delete(k);
|
||||
const body = { kind, scope, id, at: this.stamp(this.now()), why };
|
||||
await this.say(FINDING_CLEARED_EVENT, "finding-cleared", k, body as unknown as C);
|
||||
});
|
||||
}
|
||||
|
||||
/** Judge every finding anew, write each key, delete each key neither stated nor pending, and say `findings-stated`. */
|
||||
state(asked = ""): Promise<void> {
|
||||
return this.act(async () => {
|
||||
const obs = await this.o.observe();
|
||||
const keep = new Set<string>();
|
||||
const kinds = this.o.kinds?.length ? [...new Set([...this.o.kinds, ...VIEW_KINDS])].sort() : undefined;
|
||||
const body = { at: this.stamp(this.now()), ...(asked ? { asked } : {}), ...(kinds ? { kinds } : {}), findings: [] as Wire[], pending: [] as PendingKey[] };
|
||||
for (const f of obs.findings) {
|
||||
const [full] = await this.complete(f);
|
||||
await this.o.state.put(key(full), full as unknown as F);
|
||||
keep.add(key(full));
|
||||
body.findings.push(full);
|
||||
}
|
||||
for (const p of obs.pending) {
|
||||
keep.add(p.key);
|
||||
body.pending.push(p);
|
||||
}
|
||||
for (const k of await this.o.state.keys()) {
|
||||
const kind = k.slice(k.lastIndexOf(".") + 1);
|
||||
// a views reader's open findings are stated beside observe's (design 47 G §639)
|
||||
if (!keep.has(k) && VIEW_KINDS.includes(kind)) {
|
||||
const e = await this.o.state.get(k);
|
||||
if (e) {
|
||||
keep.add(k);
|
||||
body.findings.push(e.value as unknown as Wire);
|
||||
}
|
||||
}
|
||||
if (!keep.has(k) && this.owns(kind)) await this.o.state.delete(k);
|
||||
}
|
||||
let out = body as unknown as S;
|
||||
if (this.o.send) {
|
||||
try {
|
||||
out = (await this.o.send(`findings-stated.${this.o.module}`, body)) as S;
|
||||
} catch (e) {
|
||||
this.log(`error: the findings-stated of ${this.o.module} could not be sent, the next statement covers it: ${e}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await this.say(FINDINGS_STATED_EVENT, "findings-stated", this.o.module, out);
|
||||
});
|
||||
}
|
||||
|
||||
private async complete(finding: F): Promise<[Wire, Wire | null]> {
|
||||
const f: Wire = { ...(finding as object) };
|
||||
checkFinding(f);
|
||||
const kind = f.kind as string;
|
||||
if (!this.owns(kind)) throw new Error(`the finding kind "${kind}" is not one this writer owns (${this.o.kinds})`);
|
||||
const e = await this.o.state.get(key(f));
|
||||
const old = e ? (e.value as unknown as Wire) : null;
|
||||
const at = typeof f.at === "string" && f.at ? f.at : this.stamp(this.now());
|
||||
const since = (typeof old?.since === "string" && old.since) || (typeof f.since === "string" && f.since) || at;
|
||||
return [{ ...f, observer: f.observer || this.o.module, at, since }, old];
|
||||
}
|
||||
|
||||
/** Publish awaiting the acknowledgement, again for a minute when unacknowledged, then log the error naming what it said. */
|
||||
private async say(subject: string, event: string, what: string, body: F | C | S): Promise<void> {
|
||||
const id = `${this.o.module}-${event}-${this.now().getTime()}-${++this.seq}`;
|
||||
const start = this.now().getTime();
|
||||
for (let delay = 1000; ; delay = Math.min(delay * 2, 10000)) {
|
||||
try {
|
||||
await this.o.publish(subject, body, id);
|
||||
return;
|
||||
} catch (e) {
|
||||
if (this.now().getTime() - start >= PUBLISH_RETRY_MS || this.closed || !(await this.pause(delay))) {
|
||||
this.log(`error: ${event} for ${what} was not acknowledged by the bus, the next statement covers it: ${e}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function key(f: object): string {
|
||||
const m = f as Wire;
|
||||
return findingKey(m.scope as string, m.id as string, m.kind as string);
|
||||
}
|
||||
|
||||
/** A finding as compared to tell whether what it says changed: not the time it was last seen, nor what saw it. */
|
||||
function unsaid(f: Wire): string {
|
||||
const { at: _at, run: _run, ...rest } = f;
|
||||
return canonical(rest);
|
||||
}
|
||||
|
||||
/** JSON with every object's keys in order, so two equal findings compare equal whatever order they were built in. */
|
||||
function canonical(v: unknown): string {
|
||||
if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
|
||||
if (v && typeof v === "object") {
|
||||
const o = v as Record<string, unknown>;
|
||||
return `{${Object.keys(o)
|
||||
.filter((k) => o[k] !== undefined)
|
||||
.sort()
|
||||
.map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(v);
|
||||
}
|
||||
Reference in New Issue
Block a user