From da8ce4c4e787988c51c310b6808f42acd7de9d68 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 19:46:00 -0700 Subject: [PATCH 1/8] feat: primitive in-process event bus - the single dispatch pipeline Lock-step with mercury-python (ratified design, Eric 2026-08-23): every invocation reaches a function the same way - a per-route FIFO mailbox consumed by 'instances' worker loops (the parameter becomes faithful; the semaphore is gone). The HTTP host and the local side of PostOffice are thin ingress adapters over the bus. - bus.ts (internal): deliver (RPC, ttl-bounded -> 408; dead-work skip for queued calls whose caller already timed out) and publish (drop-n-forget, 202-shape ack). Worker owns the invocation pipeline: per-delivery trace context, AppException -> portable error envelope, execTime, error logging for un-replied publishes. An in-flight RPC's deadline timer is deliberately referenced (pending work holds the process open, at most until its deadline); an idle bus holds no handles. - PostOffice without an endpoint = local ingress with the engines' semantics: private routes callable in-app (the wire keeps its 403), headers verbatim, reply envelope identical to the remote path; unregistered route -> 404 envelope. With an endpoint: unchanged wire client. - No spill tier, no queue cap (ratified): back-pressure belongs to the tier that owns recovery - the engines' flows and graphs. - Demo gains the local-composition pair (public hello.chain -> private demo.suffix.helper); README documents local calls, faithful private and the workflow boundary; scope statement amended. Pins: test/bus.test.ts - the same eight as the python twin (local RPC public+private, unregistered 404, FIFO order, instances=2 concurrency peak, local 408 + dead-work skip proven, trace chained caller -> entry -> private helper, local send ack). The existing host suite now exercises the bus path. Gates: tests 39/39 (tsc + node:test). Co-Authored-By: Claude Code --- CHANGELOG.md | 11 +++ README.md | 30 ++++++- examples/demo-app.mjs | 12 +++ src/bus.ts | 197 ++++++++++++++++++++++++++++++++++++++++++ src/client.ts | 33 ++++++- src/registry.ts | 5 ++ src/server.ts | 105 +++------------------- test/bus.test.ts | 143 ++++++++++++++++++++++++++++++ 8 files changed, 434 insertions(+), 102 deletions(-) create mode 100644 src/bus.ts create mode 100644 test/bus.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 17b046b7..22ebfa63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## 0.1.0 (unreleased) +- Primitive in-process event bus - the single dispatch pipeline: one FIFO mailbox per + route consumed by `instances` worker loops (the parameter is faithful); RPC deliveries + are ttl-bounded with a dead-work skip; drop-n-forget returns the 202-shape ack. The + HTTP host and the local side of PostOffice are thin ingress adapters over it. No spill + tier and no queue cap by design - back-pressure belongs to the engines' flows/graphs; + a leaf host fails fast by deadline. An in-flight RPC holds the process open (at most + until its deadline); an idle bus holds nothing. +- PostOffice without an endpoint delivers locally (engine semantics): private routes are + callable in-app while the wire keeps its 403; headers pass verbatim; the reply envelope + shape is identical to the remote path. + Repository repurposed for the Mercury Composable **polyglot initiative** (August 2026): instead of re-porting the full composable foundation, the fresh start is a lightweight wrapper of the engines' Event-over-HTTP protocol. diff --git a/README.md b/README.md index 51030d7d..ac0266cf 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ This package is a deliberately **lightweight wrapper of the Event-over-HTTP prot registered functions, - a **thin client** (`PostOffice`) to call functions on peer applications the same way, - the **standard event envelope wire format** codec (language-neutral MsgPack), and +- a **primitive in-process event bus** — the single dispatch pipeline: one FIFO mailbox + per route consumed by `instances` worker loops, and - the **minimalist utilities** shared with the engines for consistency: configuration management, logging in the engines' presentation format, and distributed-trace context. @@ -78,6 +80,24 @@ status and reply headers). Node.js is non-blocking by nature; handlers may be as - Functions must be stateless; anything you must keep belongs to the caller's flow model or state machine. +### Local function calls + +`PostOffice` **without an endpoint** delivers through this application's own event bus — +the engines' semantics for an in-app `po` call: + +- `isPrivate: true` means exactly what it means in the engines: callable **in-app only**. + Local calls reach private and public routes alike; the HTTP host keeps answering 403 + for private targets from the wire. +- `instances` is faithful: each route has one FIFO mailbox consumed by that many worker + loops. RPC waits are bounded by `timeoutMs` (the standard 408 envelope on breach), and + a queued call whose caller already timed out is skipped, never wastefully executed. +- There is **no spill tier and no queue cap** by design: back-pressure belongs to the tier + that owns recovery — the engines' flows and graphs. A leaf host fails fast by deadline + instead of hoarding work. + +Local eventing is for simple leaf-side composition. Workflow processing belongs in Event +Script and Knowledge Graph on the engines — that boundary is the architecture. + ## Configuration, logging, telemetry The same conventions as the engines, so a polyglot installation stays uniform: @@ -120,10 +140,12 @@ millisecond precision; binary payloads are `Uint8Array`. ## Scope -This package intentionally contains **no event bus, no flows, no graphs and no -orchestration** — those live in the engines. It provides functions plus the minimalist -foundation utilities, keeping Node.js fast to prototype with while the composable core -guarantees the architecture. +This package intentionally contains **no orchestration: no flows, no graphs, no +persistence, no pub/sub broadcast** — those live in the engines. What it does carry is +deliberately minimal: functions, a primitive in-process event bus (route mailboxes + +workers, RPC and drop-n-forget — nothing more), and the minimalist foundation utilities, +keeping Node.js fast to prototype with while the composable core guarantees the +architecture. ## License diff --git a/examples/demo-app.mjs b/examples/demo-app.mjs index f86cda76..3e5c2e5b 100644 --- a/examples/demo-app.mjs +++ b/examples/demo-app.mjs @@ -25,3 +25,15 @@ preload('hello.node', { instances: 10 }, async (headers, body) => { preload('hello.declarative', { instances: 10 }, async (headers, body) => { return { body, headers, language: 'node.js' }; }); + +// Private helper - callable in-app only (the HTTP host answers 403 for it). +preload('demo.suffix.helper', { instances: 10, isPrivate: true }, async (_headers, body) => { + return { text: `${body?.text ?? ''}!`, language: 'node.js' }; +}); + +// Local composition: a public function calls a private sibling through the bus. +preload('hello.chain', { instances: 10 }, async (_headers, body) => { + const { PostOffice } = await import('../dist/src/index.js'); + const reply = await new PostOffice().request('demo.suffix.helper', body, { timeoutMs: 5000 }); + return reply.body; +}); diff --git a/src/bus.ts b/src/bus.ts new file mode 100644 index 00000000..3281ae76 --- /dev/null +++ b/src/bus.ts @@ -0,0 +1,197 @@ +/** + * The primitive in-process event bus - the single dispatch pipeline. + * + * Every invocation reaches a function the same way: through a per-route FIFO + * mailbox consumed by `instances` worker loops (the engines' semantics - the + * parameter is faithful). The HTTP host and the local side of PostOffice are + * thin ingress adapters over this bus; neither has its own invocation path. + * + * Deliberately primitive, riding the runtime's native event loop: + * - Two operations only: deliver (RPC - ttl-bounded, with a dead-work skip + * for queued calls whose caller already timed out) and publish + * (drop-n-forget - returns the 202-shape acknowledgement). + * - No spill tier and no queue cap: back-pressure belongs to the tier that + * owns recovery - the engines' flows and graphs. A leaf host fails fast by + * deadline (the 408 envelope) instead of hoarding work. + * - In-memory only; no orchestration, no flows, no persistence, no broadcast. + * + * The bus is internal: application code uses preload() and PostOffice, never + * this module - the same way engine developers never touch the engine bus. + */ +import { EventEnvelope, isoUtc } from './envelope.js'; +import { AppException } from './exceptions.js'; +import { getLogger } from './log.js'; +import type { ServiceDef } from './registry.js'; +import { runWithTrace, TraceInfo } from './trace.js'; + +const log = getLogger('mercury.bus'); + +/** An RPC delivery missed its deadline; adapters shape the 408 for their protocol. */ +export class DeliveryTimeout extends Error { + readonly ttlMs: number; + + constructor(ttlMs: number) { + super(`Timeout for ${ttlMs} ms`); + this.name = 'DeliveryTimeout'; + this.ttlMs = ttlMs; + } +} + +/** The 202 drop-n-forget acknowledgement (EventApiService shape). */ +export function asyncAck(): EventEnvelope { + return new EventEnvelope().setStatus(202) + .setBody({ type: 'async', delivered: true, time: isoUtc() }); +} + +interface TraceFields { + traceId?: string; + tracePath?: string; + cid?: string; +} + +interface Delivery extends TraceFields { + service: ServiceDef; + headers: Record; + body: unknown; + settled: boolean; + resolve?: (reply: EventEnvelope) => void; // absent = drop-n-forget +} + +const CLOSED: unique symbol = Symbol('bus-closed'); + +/** Unbounded FIFO handing items to awaiting workers. */ +class Mailbox { + private items: Array = []; + private waiters: Array<(item: Delivery | typeof CLOSED) => void> = []; + + push(item: Delivery | typeof CLOSED): void { + const waiter = this.waiters.shift(); + if (waiter) { + waiter(item); + } else { + this.items.push(item); + } + } + + next(): Promise { + const item = this.items.shift(); + if (item !== undefined) { + return Promise.resolve(item); + } + return new Promise((resolve) => this.waiters.push(resolve)); + } +} + +/** Per-registry bus: one FIFO mailbox and N workers per registered route. */ +export class EventBus { + private mailboxes = new Map(); + + private mailbox(service: ServiceDef): Mailbox { + let mailbox = this.mailboxes.get(service.route); + if (!mailbox) { + // lazy: the mailbox and its workers start on first use + mailbox = new Mailbox(); + this.mailboxes.set(service.route, mailbox); + for (let n = 0; n < service.instances; n++) { + void this.runWorker(mailbox); + } + } + return mailbox; + } + + /** RPC: enqueue and await the reply envelope within the ttl. */ + deliver(service: ServiceDef, headers: Record, body: unknown, + ttlMs: number, trace: TraceFields = {}): Promise { + const delivery: Delivery = { service, headers, body, settled: false, ...trace }; + this.mailbox(service).push(delivery); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + if (!delivery.settled) { + // dead-work mark: a worker reaching this delivery later will skip it + delivery.settled = true; + reject(new DeliveryTimeout(ttlMs)); + } + }, Math.max(100, ttlMs)); + // deliberately referenced: an in-flight RPC is pending work and holds the + // process open (at most until its deadline); an idle bus holds nothing + delivery.resolve = (reply) => { + clearTimeout(timer); + resolve(reply); + }; + }); + } + + /** Drop-n-forget: enqueue and return the 202-shape acknowledgement. */ + publish(service: ServiceDef, headers: Record, body: unknown, + trace: TraceFields = {}): EventEnvelope { + this.mailbox(service).push({ service, headers, body, settled: false, ...trace }); + return asyncAck(); + } + + /** Stop all workers (orderly shutdown; worker promises hold no OS handle). */ + close(): void { + for (const mailbox of this.mailboxes.values()) { + mailbox.push(CLOSED); + } + this.mailboxes.clear(); + } + + private async runWorker(mailbox: Mailbox): Promise { + for (;;) { + const delivery = await mailbox.next(); + if (delivery === CLOSED) { + mailbox.push(CLOSED); // release the next worker on the same mailbox + return; + } + // dead-work check: the caller of a queued RPC already gave up (408 sent) + if (delivery.settled) { + continue; + } + const reply = await this.execute(delivery); + if (delivery.resolve) { + if (!delivery.settled) { + delivery.settled = true; + delivery.resolve(reply); + } + } else if (reply.hasError()) { + log.warn(`Async event ${delivery.service.route} ended with status ` + + `${reply.getStatus()} - ${reply.body}`); + } + } + } + + /** Run the handler under its trace context and shape the outcome as a reply. */ + private async execute(delivery: Delivery): Promise { + const info: TraceInfo = { + traceId: delivery.traceId, + tracePath: delivery.tracePath, + cid: delivery.cid, + annotations: {} + }; + const start = process.hrtime.bigint(); + let reply: EventEnvelope; + try { + const result = await runWithTrace(info, async () => + delivery.service.handler(delivery.headers, delivery.body)); + reply = result instanceof EventEnvelope ? result : new EventEnvelope(undefined, result); + } catch (e) { + if (e instanceof AppException) { + reply = new EventEnvelope().setStatus(e.status).setBody(e.message); + } else { + // any handler failure becomes the portable error contract + // (status 500 + message + stack), mirroring the engines + const error = e as Error; + reply = new EventEnvelope().setStatus(500).setBody(error.message ?? String(e)); + if (error.stack) { + reply.stack = error.stack; + } + } + } + reply.sender = reply.sender ?? delivery.service.route; + reply.execTime = Math.round(Number(process.hrtime.bigint() - start) / 1000) / 1000; + if (Object.keys(info.annotations).length) { + reply.annotations = { ...info.annotations, ...reply.annotations }; + } + return reply; + } +} diff --git a/src/client.ts b/src/client.ts index c5619799..51b5dabc 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,8 +11,10 @@ * The decoded reply envelope is authoritative: an error from the target rides * back as a normal envelope with status >= 400 — inspect reply.getStatus(). */ +import { DeliveryTimeout } from './bus.js'; import { EventEnvelope } from './envelope.js'; import { AppException } from './exceptions.js'; +import { defaultRegistry, FunctionRegistry } from './registry.js'; import { getTrace } from './trace.js'; const W3C_TRACE_ID = /^[0-9a-f]{32}$/; @@ -28,7 +30,32 @@ export interface CallOptions { export class PostOffice { constructor(private readonly endpoint?: string, - private readonly securityHeaders: Record = {}) {} + private readonly securityHeaders: Record = {}, + private readonly registry: FunctionRegistry = defaultRegistry) {} + + /** In-app delivery through the primitive event bus (private OR public). */ + private async callLocal(route: string, body: unknown, options: CallOptions, + isAsync: boolean): Promise { + const service = this.registry.get(route); + if (!service) { + return new EventEnvelope().setStatus(404).setBody(`Route ${route} not found`); + } + const timeoutMs = options.timeoutMs ?? 30000; + const event = this.buildEvent(route, body, options); + const trace = { traceId: event.traceId, tracePath: event.tracePath, cid: event.cid }; + const bus = this.registry.bus; + if (isAsync) { + return bus.publish(service, event.headers, event.body, trace); + } + try { + return await bus.deliver(service, event.headers, event.body, timeoutMs, trace); + } catch (e) { + if (e instanceof DeliveryTimeout) { + return new EventEnvelope().setStatus(408).setBody(`Timeout for ${timeoutMs} ms`); + } + throw e; + } + } private httpHeaders(timeoutMs: number, isAsync: boolean, event: EventEnvelope): Record { @@ -65,8 +92,8 @@ export class PostOffice { isAsync: boolean): Promise { const url = options.endpoint ?? this.endpoint; if (!url) { - throw new Error("Missing event endpoint - " + - "e.g. new PostOffice('http://peer:8085/api/event')"); + // no endpoint = local: the engines' semantics for an in-app po call + return this.callLocal(route, body, options, isAsync); } const timeoutMs = options.timeoutMs ?? 30000; const event = this.buildEvent(route, body, options); diff --git a/src/registry.ts b/src/registry.ts index a001d680..0075b598 100644 --- a/src/registry.ts +++ b/src/registry.ts @@ -5,6 +5,7 @@ * TypedLambdaFunction — and return the reply body (or an EventEnvelope for * full control of status and reply headers). */ +import { EventBus } from './bus.js'; import { EventEnvelope } from './envelope.js'; export type Handler = ( @@ -32,6 +33,10 @@ export function validateRoute(route: string): string { } export class FunctionRegistry { + // the registry's own dispatch pipeline (see bus.ts) - shared by the + // HTTP host and the local side of PostOffice + readonly bus = new EventBus(); + private services = new Map(); register(route: string, handler: Handler, diff --git a/src/server.ts b/src/server.ts index 435e366c..73997c21 100644 --- a/src/server.ts +++ b/src/server.ts @@ -12,42 +12,16 @@ * read-only my_correlation_id header. */ import * as http from 'node:http'; +import { DeliveryTimeout } from './bus.js'; import { appConfig } from './config.js'; -import { EventEnvelope, isoUtc } from './envelope.js'; -import { AppException, CompactFormatError } from './exceptions.js'; +import { EventEnvelope } from './envelope.js'; +import { CompactFormatError } from './exceptions.js'; import { getLogger } from './log.js'; -import { defaultRegistry, FunctionRegistry, ServiceDef } from './registry.js'; -import { runWithTrace, TraceInfo } from './trace.js'; +import { defaultRegistry, FunctionRegistry } from './registry.js'; const OCTET_STREAM = 'application/octet-stream'; const log = getLogger('mercury.server'); -class Semaphore { - private queue: Array<() => void> = []; - private available: number; - - constructor(permits: number) { - this.available = permits; - } - - async acquire(): Promise { - if (this.available > 0) { - this.available--; - return; - } - await new Promise((resolve) => this.queue.push(resolve)); - } - - release(): void { - const next = this.queue.shift(); - if (next) { - next(); - } else { - this.available++; - } - } -} - function transportError(res: http.ServerResponse, status: number, message: string): void { const reply = new EventEnvelope().setStatus(status).setBody(message); const bytes = reply.toBytes(); @@ -71,54 +45,9 @@ function handlerHeaders(event: EventEnvelope): Record { } export class EventApiServer { - private semaphores = new Map(); - + /** Thin ingress: protocol guards + header hygiene, then the registry's bus. */ constructor(readonly registry: FunctionRegistry = defaultRegistry) {} - private semaphore(service: ServiceDef): Semaphore { - let semaphore = this.semaphores.get(service.route); - if (!semaphore) { - semaphore = new Semaphore(service.instances); - this.semaphores.set(service.route, semaphore); - } - return semaphore; - } - - /** Run the handler under its trace context and shape the outcome as a reply. */ - private async invoke(service: ServiceDef, event: EventEnvelope, - headers: Record): Promise { - const info: TraceInfo = { - traceId: event.traceId, - tracePath: event.tracePath, - cid: event.cid, - annotations: {} - }; - const semaphore = this.semaphore(service); - await semaphore.acquire(); - const start = process.hrtime.bigint(); - let reply: EventEnvelope; - try { - const result = await runWithTrace(info, async () => service.handler(headers, event.body)); - reply = result instanceof EventEnvelope ? result : new EventEnvelope(undefined, result); - } catch (e) { - if (e instanceof AppException) { - reply = new EventEnvelope().setStatus(e.status).setBody(e.message); - } else { - const error = e as Error; - reply = new EventEnvelope().setStatus(500).setBody(error.message ?? String(e)); - if (error.stack) reply.stack = error.stack; - } - } finally { - semaphore.release(); - } - reply.sender = reply.sender ?? service.route; - reply.execTime = Math.round(Number(process.hrtime.bigint() - start) / 1000) / 1000; - if (Object.keys(info.annotations).length) { - reply.annotations = { ...info.annotations, ...reply.annotations }; - } - return reply; - } - private async handleEvent(req: http.IncomingMessage, res: http.ServerResponse, raw: Buffer): Promise { const ttl = Math.max(1000, parseInt(String(req.headers['x-ttl'] ?? '0'), 10) || 0); @@ -148,32 +77,24 @@ export class EventApiServer { return; } const headers = handlerHeaders(event); + const bus = this.registry.bus; + const trace = { traceId: event.traceId, tracePath: event.tracePath, cid: event.cid }; if (isAsync) { - this.invoke(service, event, headers).then((reply) => { - if (reply.hasError()) { - log.warn(`Async event ${event.to} ended with status ${reply.getStatus()} - ${reply.body}`); - } - }).catch((e) => log.error(`Async event ${event.to} failed - ${(e as Error).message}`)); - const ack = new EventEnvelope().setStatus(202) - .setBody({ type: 'async', delivered: true, time: isoUtc() }); + const ack = bus.publish(service, headers, event.body, trace); const bytes = ack.toBytes(); res.writeHead(202, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); res.end(bytes); return; } - const timeout = new Promise((_, reject) => { - const timer = setTimeout(() => reject(new TimeoutSignal()), ttl); - timer.unref(); - }); try { - const reply = await Promise.race([this.invoke(service, event, headers), timeout]); + const reply = await bus.deliver(service, headers, event.body, ttl, trace); log.info(`Handled ${event.to} status=${reply.getStatus()} ` + `exec_time=${reply.execTime}ms trace_id=${event.traceId ?? 'none'}`); const bytes = reply.toBytes(); res.writeHead(200, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); res.end(bytes); } catch (e) { - if (e instanceof TimeoutSignal) { + if (e instanceof DeliveryTimeout) { log.warn(`Event ${event.to} timeout for ${ttl} ms (trace_id=${event.traceId ?? 'none'})`); transportError(res, 408, `Timeout for ${ttl} ms`); } else { @@ -207,12 +128,6 @@ export class EventApiServer { } } -class TimeoutSignal extends Error { - constructor() { - super('timeout'); - } -} - export class Platform { constructor(readonly registry: FunctionRegistry = defaultRegistry) {} diff --git a/test/bus.test.ts b/test/bus.test.ts new file mode 100644 index 00000000..6153127a --- /dev/null +++ b/test/bus.test.ts @@ -0,0 +1,143 @@ +/** Primitive event bus pins: local RPC (public+private), FIFO, workers, deadlines. */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { PostOffice } from '../src/client.js'; +import { EventEnvelope } from '../src/envelope.js'; +import { FunctionRegistry } from '../src/registry.js'; +import { getTrace, runWithTrace } from '../src/trace.js'; + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +test('local rpc to public route (headers verbatim)', async () => { + const registry = new FunctionRegistry(); + registry.register('bus.echo', async (headers, body) => ({ headers, body })); + const po = new PostOffice(undefined, {}, registry); + const reply = await po.request('bus.echo', { a: 1 }, + { headers: { h1: 'v1' }, timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 200); + const result = reply.body as Record; + assert.deepEqual(result.body, { a: 1 }); + // local delivery passes headers verbatim (hygiene is a wire-ingress concern) + assert.deepEqual(result.headers, { h1: 'v1' }); + assert.equal(reply.sender, 'bus.echo'); + assert.ok(typeof reply.execTime === 'number'); +}); + +test('local rpc reaches a private route (engine semantics)', async () => { + const registry = new FunctionRegistry(); + registry.register('bus.secret', async () => ({ secret: 'ok' }), { isPrivate: true }); + const po = new PostOffice(undefined, {}, registry); + const reply = await po.request('bus.secret', {}, { timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 200); + assert.deepEqual(reply.body, { secret: 'ok' }); +}); + +test('unregistered local route answers 404', async () => { + const po = new PostOffice(undefined, {}, new FunctionRegistry()); + const reply = await po.request('bus.no.where', {}, { timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 404); + assert.equal(reply.body, 'Route bus.no.where not found'); +}); + +test('fifo ordering with one worker', async () => { + const registry = new FunctionRegistry(); + const processed: number[] = []; + let done: () => void = () => {}; + const allDone = new Promise((resolve) => { done = resolve; }); + registry.register('bus.fifo', async (_headers, body) => { + processed.push(Number((body as Record).n)); + if (processed.length === 3) done(); + }, { instances: 1 }); + const po = new PostOffice(undefined, {}, registry); + for (const n of [1, 2, 3]) { + const ack = await po.send('bus.fifo', { n }, { timeoutMs: 5000 }); + assert.equal(ack.getStatus(), 202); + assert.equal((ack.body as Record).delivered, true); + } + await allDone; + assert.deepEqual(processed, [1, 2, 3]); +}); + +test('instances bounds concurrency faithfully', async () => { + const registry = new FunctionRegistry(); + let active = 0; + let peak = 0; + registry.register('bus.slow', async () => { + active++; + peak = Math.max(peak, active); + await sleep(150); + active--; + return { ok: true }; + }, { instances: 2 }); + const po = new PostOffice(undefined, {}, registry); + const replies = await Promise.all( + Array.from({ length: 4 }, () => po.request('bus.slow', {}, { timeoutMs: 5000 }))); + assert.ok(replies.every((r) => r.getStatus() === 200)); + assert.equal(peak, 2); // instances = the number of concurrent workers +}); + +test('local timeout 408 and dead-work skip', async () => { + const registry = new FunctionRegistry(); + const executed: string[] = []; + let release: () => void = () => {}; + const gateOpen = new Promise((resolve) => { release = resolve; }); + registry.register('bus.gate', async (_headers, body) => { + executed.push(String((body as Record).id)); + await gateOpen; + return { ok: true }; + }, { instances: 1 }); + const po = new PostOffice(undefined, {}, registry); + const first = po.request('bus.gate', { id: 'first' }, { timeoutMs: 5000 }); + await sleep(50); // the single worker is now blocked inside 'first' + // the second RPC waits in the mailbox and times out before a worker frees up + const reply = await po.request('bus.gate', { id: 'second' }, { timeoutMs: 200 }); + assert.equal(reply.getStatus(), 408); + assert.equal(reply.body, 'Timeout for 200 ms'); + release(); + assert.equal((await first).getStatus(), 200); + await sleep(50); // give the worker a chance to reach the dead delivery + // dead-work check: the timed-out delivery was skipped, never executed + assert.deepEqual(executed, ['first']); +}); + +test('trace chains through a local private sibling', async () => { + const registry = new FunctionRegistry(); + registry.register('bus.helper', async () => { + const info = getTrace(); + assert.ok(info); + return { helper_trace: info.traceId, helper_cid: info.cid }; + }, { isPrivate: true }); + registry.register('bus.entry', async () => { + const info = getTrace(); + assert.ok(info); + const po = new PostOffice(undefined, {}, registry); + const inner = await po.request('bus.helper', {}, { timeoutMs: 5000 }); + return { entry_trace: info.traceId, ...(inner.body as Record) }; + }); + const po = new PostOffice(undefined, {}, registry); + const reply = await runWithTrace( + { traceId: 'trace-bus-1', tracePath: 'TEST /bus', cid: 'cid-bus-1', annotations: {} }, + () => po.request('bus.entry', {}, { timeoutMs: 5000 })); + assert.equal(reply.getStatus(), 200); + // one trace id flows: caller context -> entry handler -> private helper + assert.deepEqual(reply.body, { + entry_trace: 'trace-bus-1', + helper_trace: 'trace-bus-1', + helper_cid: 'cid-bus-1' + }); +}); + +test('local send returns the 202 ack envelope and delivers', async () => { + const registry = new FunctionRegistry(); + let seen: () => void = () => {}; + const delivered = new Promise((resolve) => { seen = resolve; }); + registry.register('bus.sink', async () => { seen(); }); + const po = new PostOffice(undefined, {}, registry); + const ack = await po.send('bus.sink', { fire: 'forget' }, { timeoutMs: 5000 }); + assert.ok(ack instanceof EventEnvelope); + assert.equal(ack.getStatus(), 202); + assert.equal((ack.body as Record).type, 'async'); + await delivered; +}); From 31c8b0bf9423caf7007b9d228595f15adba889d9 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 19:52:51 -0700 Subject: [PATCH 2/8] chore: align the bus with the python twin's Sonar round Preemptive mirror of the python fixes: the 'absent = drop-n-forget' comment reworded (it parsed as commented-out code), and execute is static (uses nothing from the instance). Gates: tests 39/39. Co-Authored-By: Claude Code --- src/bus.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bus.ts b/src/bus.ts index 3281ae76..0b67cbc7 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -54,7 +54,7 @@ interface Delivery extends TraceFields { headers: Record; body: unknown; settled: boolean; - resolve?: (reply: EventEnvelope) => void; // absent = drop-n-forget + resolve?: (reply: EventEnvelope) => void; // drop-n-forget deliveries carry no resolver } const CLOSED: unique symbol = Symbol('bus-closed'); @@ -147,7 +147,7 @@ export class EventBus { if (delivery.settled) { continue; } - const reply = await this.execute(delivery); + const reply = await EventBus.execute(delivery); if (delivery.resolve) { if (!delivery.settled) { delivery.settled = true; @@ -161,7 +161,7 @@ export class EventBus { } /** Run the handler under its trace context and shape the outcome as a reply. */ - private async execute(delivery: Delivery): Promise { + private static async execute(delivery: Delivery): Promise { const info: TraceInfo = { traceId: delivery.traceId, tracePath: delivery.tracePath, From 3d866f1c2c915130cd2789e7bd0566f99dda54d8 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 19:53:40 -0700 Subject: [PATCH 3/8] chore: unshadow the inner PostOffice in the trace-chain test Twin of the python fix: the entry handler's local 'po' shadowed the test's outer 'po' - renamed innerPo. Co-Authored-By: Claude Code --- test/bus.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/bus.test.ts b/test/bus.test.ts index 6153127a..76f8a690 100644 --- a/test/bus.test.ts +++ b/test/bus.test.ts @@ -112,8 +112,8 @@ test('trace chains through a local private sibling', async () => { registry.register('bus.entry', async () => { const info = getTrace(); assert.ok(info); - const po = new PostOffice(undefined, {}, registry); - const inner = await po.request('bus.helper', {}, { timeoutMs: 5000 }); + const innerPo = new PostOffice(undefined, {}, registry); + const inner = await innerPo.request('bus.helper', {}, { timeoutMs: 5000 }); return { entry_trace: info.traceId, ...(inner.body as Record) }; }); const po = new PostOffice(undefined, {}, registry); From a5f84f6ee9ebe89ad34ed3e04b0046ca94c75883 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 19:55:41 -0700 Subject: [PATCH 4/8] session 2026-08-23 [Claude Code] --- memory/continuity.md | 14 ++++++++++- memory/sessions/2026-08-23-024601.md | 36 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 memory/sessions/2026-08-23-024601.md diff --git a/memory/continuity.md b/memory/continuity.md index d56902ed..c611cef4 100644 --- a/memory/continuity.md +++ b/memory/continuity.md @@ -17,7 +17,7 @@ polyglot initiative: a lightweight Event-over-HTTP function host + thin client, repurposed August 2026 (the previous full-framework port, up to v4.3.28, lives in git history and on npm) - **last_enabled:** 2026-08-22 -- **last_session:** 2026-08-22 | agent: Claude Code (2026-08-22-175327) +- **last_session:** 2026-08-23 | agent: Claude Code (2026-08-23-024601) - **last_review:** (none yet) - **last_invariant_check:** (none yet) - **repo:** ~/sandbox/mercury-nodejs (origin: github.com/Accenture/mercury-nodejs) @@ -83,6 +83,18 @@ ## Open Threads +- [ ] (feature — **IMPLEMENTED 2026-08-23 on `feature/primitive-event-bus`, commit + `da8ce4c`, tests 39/39; PENDING Eric's PR gate**; lock-step twin of mercury-python + `957d6b7`, where the ratified design record lives: thread-primitive-event-bus) + **Primitive in-process event bus — the single dispatch pipeline.** Per-route FIFO + mailbox + `instances` worker loops (faithful); deliver (ttl → 408, dead-work skip) + + publish (202 ack); host and local PostOffice are thin ingress adapters; `isPrivate` + faithful (in-app callable, wire keeps 403); NO spill tier / NO queue cap — back-pressure + belongs to the engines' flows/graphs. Node-specific ruling: an in-flight RPC's deadline + timer is REFERENCED (pending work holds the process open); an idle bus holds no + handles. Live wire proof: chain → private via bus; wire → private = 403. + + > Mark completed items `- [x]` and leave them in place — the review sweeps them to > the archive once older than `archive_window` sessions. Don't archive them by hand. diff --git a/memory/sessions/2026-08-23-024601.md b/memory/sessions/2026-08-23-024601.md new file mode 100644 index 00000000..67cc3e72 --- /dev/null +++ b/memory/sessions/2026-08-23-024601.md @@ -0,0 +1,36 @@ +# Session (2026-08-23T02:46:01.000Z) + +**Agent:** Claude Code + +## Summary + +**The primitive in-process event bus implemented — lock-step twin of mercury-python's +`957d6b7` — branch `feature/primitive-event-bus`, commit `da8ce4c`.** + +- `bus.ts` (internal): per-route FIFO Mailbox + `instances` worker loops (faithful + parameter; the Semaphore class is gone). `deliver` (RPC, ttl-bounded → 408, dead-work + skip via the settled flag) + `publish` (drop-n-forget, 202-shape ack). Worker owns the + invocation pipeline (runWithTrace, AppException → portable error, execTime, error + logging for un-replied publishes). **Event-loop lifecycle ruling discovered in test: + an in-flight RPC's deadline timer is deliberately REFERENCED (pending work holds the + process open, at most until its deadline); an idle bus holds no handles** — the + unref'd-everything first cut drained the loop mid-test (cancelledByParent). +- HTTP host = thin ingress; PostOffice without an endpoint = local ingress (private + faithful: in-app callable, wire keeps 403); ctor gained the registry parameter. +- Demo chain pair added; README + CHANGELOG document local calls, no-spill/no-cap + posture, the workflow boundary, and the lifecycle ruling. +- Pins: test/bus.test.ts — the same eight as the python twin. Live wire proof green: + `hello.chain` over `/api/event` → `{'text': 'polyglot!', 'language': 'node.js'}`; + direct private → 403. + +Follow-up commits: `31c8b0b` (aligned with the python twin's Sonar round — comment +wording + static execute) and `3d866f1` (unshadowed inner PostOffice in the trace-chain +test). + +Gates: **tests 39/39** (tsc + node:test). Branch = 3 commits, pending Eric's PR gate. + +## Memory References + +- referenced: (python-repo id) thread-primitive-event-bus (the ratified design; this repo + implements the twin) +- created: thread-primitive-event-bus-node (tier: working) From 342a8549d41ed162911327bf30c6297976a5e18f Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 20:19:20 -0700 Subject: [PATCH 5/8] feat: actuator endpoints - the engines' operational surface for Kubernetes GET /info, /info/routes, /env, /health, /livenessprobe on the Event API host, mirroring the Java ActuatorServices shapes as ported to Rust. Health-check functions are normal registered functions speaking the engines' type=info / type=health contract, listed in mandatory/optional.health.dependencies and called through the event bus; /livenessprobe follows the most recent /health outcome (400 when down, engine parity). VERSION moved to version.ts (single TS-side source). Co-Authored-By: Claude Code --- CHANGELOG.md | 7 ++ README.md | 32 +++++ examples/demo-app.mjs | 10 ++ src/actuator.ts | 279 ++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 3 +- src/server.ts | 23 +++- src/version.ts | 2 + test/actuator.test.ts | 217 ++++++++++++++++++++++++++++++++ test/server.test.ts | 13 +- 9 files changed, 576 insertions(+), 10 deletions(-) create mode 100644 src/actuator.ts create mode 100644 src/version.ts create mode 100644 test/actuator.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 22ebfa63..01dff490 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## 0.1.0 (unreleased) +- Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` - + the engines' operational surface, for Kubernetes probes and one-dashboard monitoring + of polyglot installations. Health-check functions are normal registered functions + speaking the engines' `type=info` / `type=health` interface contract, listed in + `mandatory.health.dependencies` / `optional.health.dependencies` and called through + the event bus. `/health` answers `UP` (200) / `DOWN` (400); `/livenessprobe` follows + the most recent health outcome. - Primitive in-process event bus - the single dispatch pipeline: one FIFO mailbox per route consumed by `instances` worker loops (the parameter is faithful); RPC deliveries are ttl-bounded with a dead-work skip; drop-n-forget returns the 202-shape ack. The diff --git a/README.md b/README.md index ac0266cf..f6c143fe 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,38 @@ Log lines follow the Java reference engine's pattern for one-aggregation consist 2026-08-22 10:15:30.123 INFO app:12 - Loaded PUBLIC hello.node, instances=10 ``` +## Actuator endpoints + +The host serves the engines' operational endpoints on the same port as `/api/event`, so +Kubernetes probes and dashboards treat a Node.js app exactly like a Java or Rust engine app: + +| Endpoint | Purpose | +|----------|---------| +| `GET /info` | app identity, runtime, origin id, start time, uptime | +| `GET /info/routes` | registered routes split by visibility, with instance counts | +| `GET /env` | selected environment variables and configuration parameters | +| `GET /health` | dependency health checks — `UP` (HTTP 200) or `DOWN` (HTTP 400) | +| `GET /livenessprobe` | `OK` while the last health outcome was good, else HTTP 400 | + +Configuration keys carry the engines' names: `info.app.version`, `info.app.description`, +`show.env.variables` and `show.application.properties` (opt-in lists — secrets are never +dumped wholesale), and `mandatory.health.dependencies` / `optional.health.dependencies` +(routes of health-check functions; optional ones never change the overall status). A +health-check function is a normal registered function — usually private — speaking the +engines' interface contract, called through the event bus: + +```javascript +preload('demo.health', { isPrivate: true }, async (headers, _body) => { + if (headers.type === 'info') { + return { service: 'demo.service', href: 'http://127.0.0.1' }; + } + return 'demo.service is running fine'; // a non-200 reply marks it down +}); +``` + +Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at +`/health`. + ## Wire compatibility The codec implements the diff --git a/examples/demo-app.mjs b/examples/demo-app.mjs index 3e5c2e5b..dd6b6480 100644 --- a/examples/demo-app.mjs +++ b/examples/demo-app.mjs @@ -37,3 +37,13 @@ preload('hello.chain', { instances: 10 }, async (_headers, body) => { const reply = await new PostOffice().request('demo.suffix.helper', body, { timeoutMs: 5000 }); return reply.body; }); + +// Health check speaking the engines' interface contract (type=info / type=health). +// Activate it for the /health actuator endpoint: +// node dist/src/cli.js examples/demo-app.mjs -Dmandatory.health.dependencies=demo.health +preload('demo.health', { instances: 5, isPrivate: true }, async (headers, _body) => { + if (headers.type === 'info') { + return { service: 'demo.service', href: 'http://127.0.0.1' }; + } + return 'demo.service is running fine'; +}); diff --git a/src/actuator.ts b/src/actuator.ts new file mode 100644 index 00000000..95df9987 --- /dev/null +++ b/src/actuator.ts @@ -0,0 +1,279 @@ +/** + * Actuator endpoints for operations and Kubernetes deployment. + * + * The same operational surface as the engines (the Java ActuatorServices and + * its Rust port), so a polyglot installation monitors every app one way: + * + * - GET /info - application identity (name, version, description), runtime, + * origin id, start/current time and uptime. + * - GET /info/routes - the local routing table split by visibility + * (routing.public / routing.private, route -> instance count). + * - GET /env - selected environment variables (show.env.variables) and + * selected configuration parameters (show.application.properties) - + * opt-in lists, so secrets are never dumped wholesale (engine parity). + * - GET /health - runs the health-check functions listed in + * mandatory.health.dependencies / optional.health.dependencies. All + * mandatory up -> UP (HTTP 200); any mandatory down -> DOWN (HTTP 400, + * engine parity). The outcome feeds the liveness state. + * - GET /livenessprobe - "OK" (text) while the last health outcome is good, + * else HTTP 400 "Unhealthy. Please check '/health' endpoint." + * + * A health-check function is a normal registered function (usually private) + * speaking the engines' interface contract - called through the same event + * bus that serves PostOffice, first with header type=info (an advisory + * identity map merged into its dependency entry), then with type=health (a + * status text or map; a non-200 reply marks the dependency down): + * + * preload('demo.health', { isPrivate: true }, async (headers, _body) => { + * if (headers.type === 'info') { + * return { service: 'demo.service', href: 'http://127.0.0.1' }; + * } + * return 'demo.service is running fine'; + * }); + * + * Engine deltas (deliberate, wrapper-scale): no /info/lib (a wrapper app has + * no runtime dependency manifest - deferred on the Rust port too), no XML + * responses, and no 5-second info cache (dependencies are in-process + * functions, so the type=info lookup costs nothing). + */ +import { randomUUID } from 'node:crypto'; +import * as http from 'node:http'; +import { DeliveryTimeout } from './bus.js'; +import { appConfig } from './config.js'; +import { isoUtc } from './envelope.js'; +import { getLogger } from './log.js'; +import { FunctionRegistry } from './registry.js'; +import { VERSION } from './version.js'; + +const log = getLogger('mercury.actuator'); + +const INFO_TIMEOUT_MS = 3000; // engine value for the advisory type=info lookup +const HEALTH_TIMEOUT_MS = 10000; // engine value for the type=health probe +const UNHEALTHY = "Unhealthy. Please check '/health' endpoint."; + +let origin: string | undefined; + +/** + * Unique instance id, minted once per process (the Java reference engine's + * format: UTC yyyyMMdd date prefix + 32-hex uuid). + */ +export function appOrigin(): string { + if (!origin) { + const date = isoUtc(new Date()).slice(0, 10).replaceAll('-', ''); + origin = date + randomUUID().replaceAll('-', ''); + } + return origin; +} + +/** + * Human-readable duration matching the engines' rendering (including their + * strict boundary behavior, kept verbatim for parity). + */ +export function elapsedTime(milliseconds: number): string { + const ONE_SECOND = 1000; + const ONE_MINUTE = 60 * ONE_SECOND; + const ONE_HOUR = 60 * ONE_MINUTE; + const ONE_DAY = 24 * ONE_HOUR; + let remaining = Math.trunc(milliseconds); + const parts: string[] = []; + if (remaining > ONE_DAY) { + const days = Math.trunc(remaining / ONE_DAY); + parts.push(`${days} day${days === 1 ? '' : 's'}`); + remaining -= days * ONE_DAY; + } + if (remaining > ONE_HOUR) { + const hours = Math.trunc(remaining / ONE_HOUR); + parts.push(`${hours} hour${hours === 1 ? '' : 's'}`); + remaining -= hours * ONE_HOUR; + } + if (remaining > ONE_MINUTE) { + const minutes = Math.trunc(remaining / ONE_MINUTE); + parts.push(`${minutes} minute${minutes === 1 ? '' : 's'}`); + remaining -= minutes * ONE_MINUTE; + } + if (remaining >= ONE_SECOND) { + const seconds = Math.trunc(remaining / ONE_SECOND); + parts.push(`${seconds} second${seconds === 1 ? '' : 's'}`); + } + return parts.length ? parts.join(' ') : `${remaining} ms`; +} + +/** A comma/space-separated string (engine syntax) or a YAML list. */ +function asList(value: unknown): string[] { + const items = Array.isArray(value) + ? value.map((item) => String(item).trim()) + : String(value ?? '').split(/[,\s]+/); + return items.filter((item) => item.length > 0); +} + +function isMessageShape(body: unknown): boolean { + // the engines accept only text or map dependency messages + return typeof body === 'string' || + (body !== null && typeof body === 'object' && !Array.isArray(body)); +} + +function sendText(res: http.ServerResponse, status: number, text: string): void { + res.writeHead(status, { 'content-type': 'text/plain' }); + res.end(text); +} + +function sendJson(res: http.ServerResponse, status: number, body: unknown): void { + const bytes = Buffer.from(JSON.stringify(body)); + res.writeHead(status, { 'content-type': 'application/json', 'content-length': bytes.length }); + res.end(bytes); +} + +/** HTTP handlers for the actuator endpoints (wired by EventApiServer). */ +export class Actuator { + private readonly registry: FunctionRegistry; + private readonly start = new Date(); + private healthy = true; // liveness follows the most recent /health outcome + private readonly appName: string; + private readonly appVersion: string; + private readonly description: string; + private readonly required: string[]; + private readonly optional: string[]; + + constructor(registry: FunctionRegistry) { + const config = appConfig(); + this.registry = registry; + this.appName = config.getProperty('application.name', 'application') || 'application'; + this.appVersion = config.getProperty('info.app.version', VERSION) || VERSION; + this.description = config.getProperty('info.app.description', this.appName) || this.appName; + this.required = asList(config.get('mandatory.health.dependencies')); + this.optional = asList(config.get('optional.health.dependencies')); + if (this.required.length) { + log.info(`Mandatory service dependencies - ${JSON.stringify(this.required)}`); + } + if (this.optional.length) { + log.info(`Optional services dependencies - ${JSON.stringify(this.optional)}`); + } + } + + /** Route a GET to its actuator endpoint; false when the path is not ours. */ + async handle(pathname: string, res: http.ServerResponse): Promise { + switch (pathname) { + case '/info': + sendJson(res, 200, this.info()); + return true; + case '/info/routes': + sendJson(res, 200, this.routes()); + return true; + case '/env': + sendJson(res, 200, this.env()); + return true; + case '/health': { + const [status, body] = await this.health(); + sendJson(res, status, body); + return true; + } + case '/livenessprobe': + if (this.healthy) { + sendText(res, 200, 'OK'); + } else { + sendText(res, 400, UNHEALTHY); + } + return true; + default: + return false; + } + } + + private appBlock(): Record { + return { name: this.appName, version: this.appVersion, description: this.description }; + } + + private info(): Record { + const now = new Date(); + return { + app: this.appBlock(), + runtime: { language: 'node.js', node: process.version, mercury_composable: VERSION }, + origin: appOrigin(), + time: { start: isoUtc(this.start), current: isoUtc(now) }, + up_time: elapsedTime(now.getTime() - this.start.getTime()) + }; + } + + private routes(): Record { + const publicRoutes: Record = {}; + const privateRoutes: Record = {}; + for (const service of this.registry.routes()) { // already route-sorted + (service.isPrivate ? privateRoutes : publicRoutes)[service.route] = service.instances; + } + return { app: this.appBlock(), routing: { public: publicRoutes, private: privateRoutes } }; + } + + private env(): Record { + const config = appConfig(); + const environment: Record = {}; + for (const name of asList(config.get('show.env.variables'))) { + environment[name] = process.env[name] ?? ''; + } + const properties: Record = {}; + for (const name of asList(config.get('show.application.properties'))) { + properties[name] = config.getProperty(name) ?? ''; + } + return { app: this.appBlock(), env: { environment, properties } }; + } + + private async health(): Promise<[number, Record]> { + const dependency: Record[] = []; + // optional services never affect the overall status (engine semantics) + await this.checkServices(this.optional, false, dependency); + const up = await this.checkServices(this.required, true, dependency); + this.healthy = up; + const result: Record = {}; + if (!dependency.length) { + result.message = 'Did you forget to define mandatory.health.dependencies ' + + 'or optional.health.dependencies'; + } + result.dependency = dependency; + result.status = up ? 'UP' : 'DOWN'; + result.origin = appOrigin(); + result.name = this.appName; + return [up ? 200 : 400, result]; + } + + private async checkServices(services: string[], required: boolean, + dependency: Record[]): Promise { + let allUp = true; + for (const route of services) { + const entry: Record = { route, required }; + dependency.push(entry); + const service = this.registry.get(route); + if (!service) { + allUp = false; + entry.status_code = 404; + entry.message = `Please check - Route ${route} not found`; + continue; + } + const bus = this.registry.bus; + // info is advisory - merge whatever the service reports about itself; + // the health probe below decides the status + try { + const info = await bus.deliver(service, { type: 'info' }, null, INFO_TIMEOUT_MS); + if (info.body !== null && typeof info.body === 'object' && !Array.isArray(info.body)) { + Object.assign(entry, info.body); + } + } catch (e) { + if (!(e instanceof DeliveryTimeout)) throw e; + } + try { + const reply = await bus.deliver(service, { type: 'health' }, null, HEALTH_TIMEOUT_MS); + entry.status_code = reply.getStatus(); + if (isMessageShape(reply.body)) { + entry.message = reply.body; + } + if (reply.hasError()) { + allUp = false; + } + } catch (e) { + if (!(e instanceof DeliveryTimeout)) throw e; + allUp = false; + entry.status_code = 408; + entry.message = `Please check - ${e.message}`; + } + } + return allUp; + } +} diff --git a/src/index.ts b/src/index.ts index 025a3535..e4c30c83 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,5 +20,4 @@ export type { Handler, ServiceDef } from './registry.js'; export { EventApiServer, Platform, platform } from './server.js'; export { annotateTrace, getTrace } from './trace.js'; export type { TraceInfo } from './trace.js'; - -export const VERSION = '0.1.0'; +export { VERSION } from './version.js'; diff --git a/src/server.ts b/src/server.ts index 73997c21..09340535 100644 --- a/src/server.ts +++ b/src/server.ts @@ -10,8 +10,12 @@ * Reserved header hygiene: x-event-api and transported my_* keys are removed * from the handler's header view; the my_cid tag is injected as the * read-only my_correlation_id header. + * The host also serves the engines' actuator endpoints (/info, /info/routes, + * /env, /health, /livenessprobe) for operations and Kubernetes probes - see + * actuator.ts. */ import * as http from 'node:http'; +import { Actuator } from './actuator.js'; import { DeliveryTimeout } from './bus.js'; import { appConfig } from './config.js'; import { EventEnvelope } from './envelope.js'; @@ -45,8 +49,12 @@ function handlerHeaders(event: EventEnvelope): Record { } export class EventApiServer { + private readonly actuator: Actuator; + /** Thin ingress: protocol guards + header hygiene, then the registry's bus. */ - constructor(readonly registry: FunctionRegistry = defaultRegistry) {} + constructor(readonly registry: FunctionRegistry = defaultRegistry) { + this.actuator = new Actuator(registry); + } private async handleEvent(req: http.IncomingMessage, res: http.ServerResponse, raw: Buffer): Promise { @@ -106,9 +114,16 @@ export class EventApiServer { createServer(): http.Server { return http.createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://localhost'); - if (req.method === 'GET' && url.pathname === '/health') { - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end('OK'); + if (req.method === 'GET') { + this.actuator.handle(url.pathname, res).then((handled) => { + if (!handled) { + res.writeHead(404, { 'content-type': 'text/plain' }); + res.end('Not found'); + } + }).catch((e) => { + res.writeHead(500, { 'content-type': 'text/plain' }); + res.end((e as Error).message ?? String(e)); + }); return; } if (req.method === 'POST' && url.pathname === '/api/event') { diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 00000000..2b096a62 --- /dev/null +++ b/src/version.ts @@ -0,0 +1,2 @@ +/** Package version - the single TS-side source (package.json mirrors it). */ +export const VERSION = '0.1.0'; diff --git a/test/actuator.test.ts b/test/actuator.test.ts new file mode 100644 index 00000000..72f0dd91 --- /dev/null +++ b/test/actuator.test.ts @@ -0,0 +1,217 @@ +/** Actuator endpoint pins: engine-parity operational surface for Kubernetes. */ +import assert from 'node:assert/strict'; +import type * as http from 'node:http'; +import { afterEach, test } from 'node:test'; +import { appOrigin, elapsedTime } from '../src/actuator.js'; +import { AppException } from '../src/exceptions.js'; +import { appConfig } from '../src/config.js'; +import { FunctionRegistry } from '../src/registry.js'; +import { EventApiServer } from '../src/server.js'; +import { VERSION } from '../src/version.js'; + +const ORIGIN_SHAPE = /^\d{8}[0-9a-f]{32}$/; // UTC yyyyMMdd + 32-hex uuid (Java reference) + +const CONFIG_KEYS = [ + 'mandatory.health.dependencies', 'optional.health.dependencies', + 'show.env.variables', 'show.application.properties', + 'application.name', 'info.app.description', 'info.app.version' +]; + +afterEach(() => { + const config = appConfig(); + for (const key of CONFIG_KEYS) { + config.set(key, ''); // empty override = unset (the Actuator treats '' as absent) + } +}); + +// the Actuator reads its configuration at construction (engine semantics), +// so each test sets config BEFORE calling start() +async function start(registry: FunctionRegistry): Promise<{ base: string; stop: () => Promise }> { + const server: http.Server = new EventApiServer(registry).createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as { port: number }; + return { + base: `http://127.0.0.1:${address.port}`, + stop: () => new Promise((resolve) => { + registry.bus.close(); + server.close(() => resolve()); + }) + }; +} + +async function getJson(url: string): Promise<[number, Record]> { + const response = await fetch(url); + return [response.status, await response.json() as Record]; +} + +async function getText(url: string): Promise<[number, string]> { + const response = await fetch(url); + return [response.status, await response.text()]; +} + +/** A health-check function speaking the engines' type=info/type=health contract. */ +function engineContractRegistry(): FunctionRegistry { + const registry = new FunctionRegistry(); + registry.register('demo.health', async (headers) => { + if (headers.type === 'info') { + return { service: 'demo.service', href: 'http://127.0.0.1' }; + } + return 'demo.service is running fine'; + }, { isPrivate: true }); + return registry; +} + +test('info reports identity, runtime and origin', async () => { + const config = appConfig(); + config.set('application.name', 'unit-app'); + config.set('info.app.description', 'actuator test app'); + const { base, stop } = await start(new FunctionRegistry()); + try { + const [status, info] = await getJson(`${base}/info`); + assert.equal(status, 200); + assert.deepEqual(info.app, { name: 'unit-app', version: VERSION, + description: 'actuator test app' }); + const runtime = info.runtime as Record; + assert.equal(runtime.language, 'node.js'); + assert.equal(runtime.mercury_composable, VERSION); + assert.match(String(info.origin), ORIGIN_SHAPE); + const time = info.time as Record; + assert.ok(time.start <= time.current); + assert.ok('up_time' in info); + } finally { + await stop(); + } +}); + +test('info/routes splits by visibility', async () => { + const registry = new FunctionRegistry(); + registry.register('unit.public.route', async () => null, { instances: 8 }); + registry.register('unit.private.route', async () => null, { instances: 2, isPrivate: true }); + const { base, stop } = await start(registry); + try { + const [status, result] = await getJson(`${base}/info/routes`); + assert.equal(status, 200); + assert.deepEqual(result.routing, { public: { 'unit.public.route': 8 }, + private: { 'unit.private.route': 2 } }); + assert.equal((result.app as Record).name, 'application'); + } finally { + await stop(); + } +}); + +test('env shows only opted-in values', async () => { + process.env.MERCURY_UNIT_ENV = 'unit-value'; + const config = appConfig(); + config.set('show.env.variables', 'MERCURY_UNIT_ENV, MERCURY_UNIT_ABSENT'); + config.set('show.application.properties', 'application.name'); + config.set('application.name', 'unit-app'); + const { base, stop } = await start(new FunctionRegistry()); + try { + const [status, result] = await getJson(`${base}/env`); + assert.equal(status, 200); + // a missing environment variable renders as an empty string (engine parity) + assert.deepEqual(result.env, { + environment: { MERCURY_UNIT_ENV: 'unit-value', MERCURY_UNIT_ABSENT: '' }, + properties: { 'application.name': 'unit-app' } + }); + } finally { + delete process.env.MERCURY_UNIT_ENV; + await stop(); + } +}); + +test('health up with the engine-contract dependency', async () => { + appConfig().set('mandatory.health.dependencies', 'demo.health'); + const { base, stop } = await start(engineContractRegistry()); + try { + const [status, health] = await getJson(`${base}/health`); + assert.equal(status, 200); + assert.equal(health.status, 'UP'); + assert.equal(health.name, 'application'); + assert.match(String(health.origin), ORIGIN_SHAPE); + // the info map merges into the dependency entry; health decides the status + assert.deepEqual(health.dependency, [{ + route: 'demo.health', required: true, + service: 'demo.service', href: 'http://127.0.0.1', + status_code: 200, message: 'demo.service is running fine' + }]); + assert.deepEqual(await getText(`${base}/livenessprobe`), [200, 'OK']); + } finally { + await stop(); + } +}); + +test('health down on a missing dependency drives liveness', async () => { + appConfig().set('mandatory.health.dependencies', 'no.such.route'); + const { base, stop } = await start(new FunctionRegistry()); + try { + // healthy until proven otherwise + assert.deepEqual(await getText(`${base}/livenessprobe`), [200, 'OK']); + const [status, health] = await getJson(`${base}/health`); + assert.equal(status, 400); + assert.equal(health.status, 'DOWN'); + assert.deepEqual(health.dependency, [{ + route: 'no.such.route', required: true, + status_code: 404, message: 'Please check - Route no.such.route not found' + }]); + assert.deepEqual(await getText(`${base}/livenessprobe`), + [400, "Unhealthy. Please check '/health' endpoint."]); + } finally { + await stop(); + } +}); + +test('optional failure never downs health', async () => { + const registry = engineContractRegistry(); + registry.register('broken.health', async () => { + throw new AppException(500, 'backend down'); + }, { isPrivate: true }); + const config = appConfig(); + config.set('mandatory.health.dependencies', 'demo.health'); + config.set('optional.health.dependencies', 'broken.health'); + const { base, stop } = await start(registry); + try { + const [status, health] = await getJson(`${base}/health`); + assert.equal(status, 200); + assert.equal(health.status, 'UP'); + const brokenDep = (health.dependency as Record[]) + .find((d) => d.route === 'broken.health'); + assert.ok(brokenDep); + assert.equal(brokenDep.required, false); + assert.equal(brokenDep.status_code, 500); + assert.equal(brokenDep.message, 'backend down'); + } finally { + await stop(); + } +}); + +test('health without dependencies teaches the config keys', async () => { + const { base, stop } = await start(new FunctionRegistry()); + try { + const [status, health] = await getJson(`${base}/health`); + assert.equal(status, 200); + assert.equal(health.status, 'UP'); + assert.deepEqual(health.dependency, []); + assert.ok(String(health.message).startsWith('Did you forget to define')); + } finally { + await stop(); + } +}); + +test('elapsedTime matches the engine rendering', () => { + assert.equal(elapsedTime(0), '0 ms'); + assert.equal(elapsedTime(500), '500 ms'); + assert.equal(elapsedTime(1000), '1 second'); + assert.equal(elapsedTime(61_000), '1 minute 1 second'); + // the engines' strict boundary behavior, kept verbatim + assert.equal(elapsedTime(60_000), '60 seconds'); + assert.equal(elapsedTime(3_600_000), '60 minutes'); + assert.equal(elapsedTime(86_400_000), '24 hours'); + assert.equal(elapsedTime(120_000), '2 minutes'); + assert.equal(elapsedTime(90_061_000), '1 day 1 hour 1 minute 1 second'); +}); + +test('origin is stable and engine-shaped', () => { + assert.equal(appOrigin(), appOrigin()); // minted once per process + assert.match(appOrigin(), ORIGIN_SHAPE); +}); diff --git a/test/server.test.ts b/test/server.test.ts index 216f6cba..7221f977 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -160,8 +160,13 @@ test('async drop-n-forget 202 ack', async () => { assert.ok('time' in ack); }); -test('health endpoint', async () => { - const response = await fetch(`${base}/health`); - assert.equal(response.status, 200); - assert.equal(await response.text(), 'OK'); +test('actuator endpoints are wired', async () => { + // shapes are pinned in actuator.test.ts - this pins the host wiring only + const live = await fetch(`${base}/livenessprobe`); + assert.equal(live.status, 200); + assert.equal(await live.text(), 'OK'); + const info = await fetch(`${base}/info`); + assert.equal(info.status, 200); + const body = await info.json() as { runtime: { language: string } }; + assert.equal(body.runtime.language, 'node.js'); }); From 7a8b12cadcd72a1f15bd09e9b3453c2e4fdf1341 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 20:23:11 -0700 Subject: [PATCH 6/8] chore: align with the python twin's Sonar round - spelling, origin test assert Co-Authored-By: Claude Code --- CHANGELOG.md | 2 +- README.md | 4 ++-- src/actuator.ts | 4 ++-- test/actuator.test.ts | 7 ++++--- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01dff490..a322201f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` - the engines' operational surface, for Kubernetes probes and one-dashboard monitoring - of polyglot installations. Health-check functions are normal registered functions + of polyglot installations. Health check functions are normal registered functions speaking the engines' `type=info` / `type=health` interface contract, listed in `mandatory.health.dependencies` / `optional.health.dependencies` and called through the event bus. `/health` answers `UP` (200) / `DOWN` (400); `/livenessprobe` follows diff --git a/README.md b/README.md index f6c143fe..9581144d 100644 --- a/README.md +++ b/README.md @@ -141,8 +141,8 @@ Kubernetes probes and dashboards treat a Node.js app exactly like a Java or Rust Configuration keys carry the engines' names: `info.app.version`, `info.app.description`, `show.env.variables` and `show.application.properties` (opt-in lists — secrets are never dumped wholesale), and `mandatory.health.dependencies` / `optional.health.dependencies` -(routes of health-check functions; optional ones never change the overall status). A -health-check function is a normal registered function — usually private — speaking the +(routes of health check functions; optional ones never change the overall status). A +health check function is a normal registered function — usually private — speaking the engines' interface contract, called through the event bus: ```javascript diff --git a/src/actuator.ts b/src/actuator.ts index 95df9987..173ef92f 100644 --- a/src/actuator.ts +++ b/src/actuator.ts @@ -11,14 +11,14 @@ * - GET /env - selected environment variables (show.env.variables) and * selected configuration parameters (show.application.properties) - * opt-in lists, so secrets are never dumped wholesale (engine parity). - * - GET /health - runs the health-check functions listed in + * - GET /health - runs the health check functions listed in * mandatory.health.dependencies / optional.health.dependencies. All * mandatory up -> UP (HTTP 200); any mandatory down -> DOWN (HTTP 400, * engine parity). The outcome feeds the liveness state. * - GET /livenessprobe - "OK" (text) while the last health outcome is good, * else HTTP 400 "Unhealthy. Please check '/health' endpoint." * - * A health-check function is a normal registered function (usually private) + * A health check function is a normal registered function (usually private) * speaking the engines' interface contract - called through the same event * bus that serves PostOffice, first with header type=info (an advisory * identity map merged into its dependency entry), then with type=health (a diff --git a/test/actuator.test.ts b/test/actuator.test.ts index 72f0dd91..cf122bfc 100644 --- a/test/actuator.test.ts +++ b/test/actuator.test.ts @@ -49,7 +49,7 @@ async function getText(url: string): Promise<[number, string]> { return [response.status, await response.text()]; } -/** A health-check function speaking the engines' type=info/type=health contract. */ +/** A health check function speaking the engines' type=info/type=health contract. */ function engineContractRegistry(): FunctionRegistry { const registry = new FunctionRegistry(); registry.register('demo.health', async (headers) => { @@ -212,6 +212,7 @@ test('elapsedTime matches the engine rendering', () => { }); test('origin is stable and engine-shaped', () => { - assert.equal(appOrigin(), appOrigin()); // minted once per process - assert.match(appOrigin(), ORIGIN_SHAPE); + const minted = appOrigin(); + assert.equal(minted, appOrigin()); // minted once per process + assert.match(minted, ORIGIN_SHAPE); }); From 8ed42661a8b4f0f4e68f112940df02762c8c5f2f Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 20:31:34 -0700 Subject: [PATCH 7/8] feat: log.format compact (JSONL) + sample resources/application.yml for the demo log.format now carries the engines' three presentations: text (default), json (pretty-printed, matching the engine's pretty serializer) and compact (single-line JSONL for log aggregators). The demo app gains examples/resources/application.yml - the engines' resources convention, auto-loaded next to the app file - wiring the demo.health dependency and demonstrating the well-known keys. README quick start teaches the -D override syntax instead of --port. Co-Authored-By: Claude Code --- CHANGELOG.md | 4 ++++ README.md | 10 ++++++---- examples/demo-app.mjs | 10 +++++++--- examples/resources/application.yml | 22 ++++++++++++++++++++++ src/config.ts | 5 +++-- src/log.ts | 18 +++++++++++------- 6 files changed, 53 insertions(+), 16 deletions(-) create mode 100644 examples/resources/application.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index a322201f..677927fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ `mandatory.health.dependencies` / `optional.health.dependencies` and called through the event bus. `/health` answers `UP` (200) / `DOWN` (400); `/livenessprobe` follows the most recent health outcome. +- `log.format` carries the engines' three presentations: `text` (default), `json` + (pretty-printed) and `compact` (single-line JSONL for log aggregators). A sample + `examples/resources/application.yml` demonstrates the resources convention and the + well-known keys. - Primitive in-process event bus - the single dispatch pipeline: one FIFO mailbox per route consumed by `instances` worker loops (the parameter is faithful); RPC deliveries are ttl-bounded with a dead-work skip; drop-n-forget returns the 202-shape ack. The diff --git a/README.md b/README.md index 9581144d..5c5e225e 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Run it: ```bash npm install && npm run build -node dist/src/cli.js app.mjs --port 8087 # or: mercury-serve app.mjs --port 8087 +node dist/src/cli.js app.mjs -Drest.server.port=8087 # or: mercury-serve app.mjs -Drest.server.port=8087 ``` Call it from a Mercury engine application with two configuration entries and no code — @@ -106,12 +106,14 @@ The same conventions as the engines, so a polyglot installation stays uniform: |-----|---------|---------| | `application.name` | application identity in logs | `application` | | `rest.server.port` | Event API port | `8085` | -| `log.format` | `text` or `json` | `text` | +| `log.format` | `text`, `json` (pretty-printed) or `compact` (single-line JSONL) | `text` | | `log.level` | log level (`LOG_LEVEL` env var wins) | `INFO` | Configuration lives in the `resources` folder, mirroring the engines: -`resources/application.yml` (or `.yaml` / `.properties`), or an explicit `--config` path. -Values support `${ENV_VAR:default}` substitution. Runtime parameter overrides use the +`resources/application.yml` (or `.yaml` / `.properties`) in the working directory or next +to the application file, or an explicit `--config` path — see +[`examples/resources/application.yml`](examples/resources/application.yml) for a worked +sample. Values support `${ENV_VAR:default}` substitution. Runtime parameter overrides use the same `-D` syntax as the Java engine and the Rust port — checked first on every read (`appConfig().set(key, value)` does the same programmatically, the `f:setConfig` analog): diff --git a/examples/demo-app.mjs b/examples/demo-app.mjs index dd6b6480..81a33340 100644 --- a/examples/demo-app.mjs +++ b/examples/demo-app.mjs @@ -1,7 +1,11 @@ /** * Demo polyglot functions. * - * Run: node dist/src/cli.js examples/demo-app.mjs --port 8087 + * Run: node dist/src/cli.js examples/demo-app.mjs + * + * Configuration comes from examples/resources/application.yml (the engines' + * "resources" convention - port 8087, the demo.health dependency, log format); + * override any key with -Dkey=value, e.g. -Drest.server.port=8090. * * Then map a route from a Mercury engine application (event-over-http.yaml): * @@ -39,8 +43,8 @@ preload('hello.chain', { instances: 10 }, async (_headers, body) => { }); // Health check speaking the engines' interface contract (type=info / type=health). -// Activate it for the /health actuator endpoint: -// node dist/src/cli.js examples/demo-app.mjs -Dmandatory.health.dependencies=demo.health +// Activated for the /health actuator endpoint by mandatory.health.dependencies +// in examples/resources/application.yml (or a -D override). preload('demo.health', { instances: 5, isPrivate: true }, async (headers, _body) => { if (headers.type === 'info') { return { service: 'demo.service', href: 'http://127.0.0.1' }; diff --git a/examples/resources/application.yml b/examples/resources/application.yml new file mode 100644 index 00000000..c4e9bc0f --- /dev/null +++ b/examples/resources/application.yml @@ -0,0 +1,22 @@ +# Sample configuration - the engines' "resources" convention. +# mercury-serve loads resources/application.yml from the working directory, or from +# the resources folder next to the application file (this one). Any key can be +# overridden at run time with the engines' -D syntax, e.g.: +# node dist/src/cli.js examples/demo-app.mjs -Drest.server.port=8090 -Dlog.format=compact + +application.name: 'demo-app' +info.app.description: 'Mercury Composable polyglot demo' + +rest.server.port: 8087 + +# text (default) | json (pretty-printed) | compact (single-line JSONL) +log.format: text +log.level: INFO + +# Actuator /health dependencies - routes of health check functions speaking the +# engines' type=info / type=health contract (demo.health in demo-app.mjs). +mandatory.health.dependencies: 'demo.health' + +# Opt-in lists for the /env endpoint - nothing is ever dumped wholesale. +show.env.variables: 'LOG_LEVEL' +show.application.properties: 'application.name, rest.server.port' diff --git a/src/config.ts b/src/config.ts index 6d090d1d..da88cf09 100644 --- a/src/config.ts +++ b/src/config.ts @@ -10,8 +10,9 @@ * environment first, then a base configuration key, then the default. * * Well-known keys shared with the engines: application.name, - * rest.server.port (default 8085), log.format (text|json), log.level - * (LOG_LEVEL environment variable wins). + * rest.server.port (default 8085), log.format (text | json pretty-printed | + * compact single-line JSONL), log.level (LOG_LEVEL environment variable + * wins). */ import * as fs from 'node:fs'; import YAML from 'yaml'; diff --git a/src/log.ts b/src/log.ts index 3ad9fc33..49799415 100644 --- a/src/log.ts +++ b/src/log.ts @@ -6,9 +6,11 @@ * %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger:%line - %msg * * Level comes from the LOG_LEVEL environment variable when set (mirroring the - * engines), else the log.level configuration key, else INFO. log.format=json - * switches to one JSON object per line with the same information plus - * trace_id when a trace context is active. + * engines), else the log.level configuration key, else INFO. log.format + * carries the engines' three presentations: text (default), json + * (pretty-printed JSON with the same information plus trace_id when a trace + * context is active) and compact (the same object on a single line - JSONL - + * for log aggregators). */ import { appConfig } from './config.js'; import { getTrace } from './trace.js'; @@ -18,7 +20,7 @@ export type Level = (typeof LEVELS)[number]; let configured = false; let minLevel = 1; // INFO -let jsonFormat = false; +let logFormat = 'text'; function setup(): void { if (configured) return; @@ -26,7 +28,7 @@ function setup(): void { const levelName = (process.env.LOG_LEVEL ?? String(config.get('log.level', 'INFO'))).toUpperCase(); const idx = LEVELS.indexOf(levelName as Level); minLevel = idx === -1 ? 1 : idx; - jsonFormat = String(config.get('log.format', 'text')).toLowerCase() === 'json'; + logFormat = String(config.get('log.format', 'text')).toLowerCase(); configured = true; } @@ -52,7 +54,7 @@ function write(level: Level, name: string | undefined, message: string, args: un ? `${message} ${args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')}` : message; const logger = name ?? callSite(); - if (jsonFormat) { + if (logFormat === 'json' || logFormat === 'compact') { const entry: Record = { time: timestamp(), level, @@ -61,7 +63,9 @@ function write(level: Level, name: string | undefined, message: string, args: un }; const info = getTrace(); if (info?.traceId) entry.trace_id = info.traceId; - process.stdout.write(JSON.stringify(entry) + '\n'); + // engine presentations: json = pretty-printed, compact = one line (JSONL) + const indent = logFormat === 'json' ? 2 : undefined; + process.stdout.write(JSON.stringify(entry, null, indent) + '\n'); } else { process.stdout.write(`${timestamp()} ${level.padEnd(5)} ${logger} - ${rendered}\n`); } From 329c93123f8bbadde683b526a3b5205857c18332 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 22 Aug 2026 21:12:37 -0700 Subject: [PATCH 8/8] session 2026-08-23 [Claude Code] --- memory/continuity.md | 20 +++++++++- memory/sessions/2026-08-23-031920.md | 57 ++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 memory/sessions/2026-08-23-031920.md diff --git a/memory/continuity.md b/memory/continuity.md index c611cef4..80f8d665 100644 --- a/memory/continuity.md +++ b/memory/continuity.md @@ -17,7 +17,7 @@ polyglot initiative: a lightweight Event-over-HTTP function host + thin client, repurposed August 2026 (the previous full-framework port, up to v4.3.28, lives in git history and on npm) - **last_enabled:** 2026-08-22 -- **last_session:** 2026-08-23 | agent: Claude Code (2026-08-23-024601) +- **last_session:** 2026-08-23 | agent: Claude Code (2026-08-23-031920) - **last_review:** (none yet) - **last_invariant_check:** (none yet) - **repo:** ~/sandbox/mercury-nodejs (origin: github.com/Accenture/mercury-nodejs) @@ -95,6 +95,24 @@ handles. Live wire proof: chain → private via bus; wire → private = 403. +- [ ] (feature — Eric's directive 2026-08-23, **IMPLEMENTED same day on + `feature/primitive-event-bus`, commits `342a854` + `7a8b12c` (twin-alignment round); + python twin `56c002c` + `a674198`; PENDING Eric's PR gate together with the bus**) + **Actuator endpoints — the engines' operational surface for Kubernetes PODs.** + GET `/info`, `/info/routes`, `/env`, `/health`, `/livenessprobe` on the Event API port; + shapes mirror the Rust engine's actuator (the approved minimalist port of Java + `ActuatorServices`), byte-symmetric with python except the runtime block. Health check + functions are normal registered functions speaking the engines' `type=info` / + `type=health` interface contract (Eric's ruling), listed in + `mandatory.health.dependencies` / `optional.health.dependencies` and called through the + event bus; `/health` = UP 200 / DOWN 400 (Java parity); `/livenessprobe` follows the + most recent health outcome. Engine formats verbatim (origin = UTC yyyyMMdd + 32-hex + uuid per the Java reference; elapsedTime boundary quirks pinned). Documented deltas: + no `/info/lib`, no XML, no info cache. `version.ts` = the single TS-side version + source. 10 pins + live demo drives on both wrappers. + Relates [[thread-primitive-event-bus-node]]; serves [[bp-publish-interop-gate]]. + + > Mark completed items `- [x]` and leave them in place — the review sweeps them to > the archive once older than `archive_window` sessions. Don't archive them by hand. diff --git a/memory/sessions/2026-08-23-031920.md b/memory/sessions/2026-08-23-031920.md new file mode 100644 index 00000000..6fa795b3 --- /dev/null +++ b/memory/sessions/2026-08-23-031920.md @@ -0,0 +1,57 @@ +# Session (2026-08-23T03:19:20.000Z) + +**Agent:** Claude Code + +Actuator endpoints on `feature/primitive-event-bus` — the node half of Eric's directive +(wrapper apps deploy as Kubernetes PODs, so they carry the engines' operational surface). +Commits `342a854` (feature) + `7a8b12c` (spelling + origin-test assert, aligning with the +python twin's IDE/Sonar round). Python twin: `56c002c` + `a674198` — the full design +narrative lives in mercury-python's log `2026-08-23-031558` (single-authored, shared +design); this log records the node-side specifics. + +## What shipped (node specifics) + +- `src/actuator.ts`: GET `/info`, `/info/routes`, `/env`, `/health`, `/livenessprobe`; + shapes mirror the Rust engine's actuator (the approved minimalist port of Java + `ActuatorServices`), byte-symmetric with the python twin except the runtime block + (`{language: "node.js", node: process.version, mercury_composable: VERSION}`). +- Health check functions speak the engines' `type=info` / `type=health` interface + contract through the event bus (Eric's ruling); `mandatory.health.dependencies` / + `optional.health.dependencies` config; UP 200 / DOWN 400; `/livenessprobe` follows the + most recent health outcome. Engine formats verbatim (origin = UTC yyyyMMdd + 32-hex + uuid per the Java reference; elapsedTime boundary quirks pinned). +- `Actuator.handle(pathname, res)` single dispatcher; `server.ts` routes every GET + through it (unknown GET → 404 text). The python twin adopted this dispatcher shape in + its Sonar round — the twins are now structurally symmetric. +- `src/version.ts` becomes the single TS-side version source (`index.ts` re-exports) — + breaks the actuator → index import cycle. +- The pre-release `/health` "OK" scaffolding endpoint is replaced by the real one. +- `examples/demo-app.mjs` gained `demo.health` (private, contract-speaking); README + "Actuator endpoints" section (+ K8s probe wiring); CHANGELOG entry. + +## Verification + +- 48/48 (`npm test`: tsc + node --test) — 10 actuator pins mirroring the python set + (five shapes, liveness-follows-health, optional-failure-never-downs, teach-message, + elapsed/origin vectors); re-run after the alignment round. +- Live drive: `node dist/src/cli.js examples/demo-app.mjs --port 8398 + -Dmandatory.health.dependencies=demo.health` → all five endpoints engine-shaped, + `/health` UP with the full dependency entry, symmetric with python on 8399. + +## Follow-up round (Eric's three asks, commit `8ed4266`; python twin `7d5ca6c`) + +- `log.format` gains `compact` (single-line JSONL); `json` becomes pretty-printed + (indent 2) — matching the Java engine's JsonAppender/CompactAppender pair (same data + map, two renderings). Full rationale in the python twin's log `2026-08-23-031558`. +- Sample `examples/resources/application.yml` (port 8087, demo.health dependency, + opt-in /env lists) — auto-loaded by the CLI's next-to-app fallback; the demo runs + with plain `node dist/src/cli.js examples/demo-app.mjs`. README quick start teaches + the `-D` override syntax instead of `--port`. +- Live drive through the yml: /health UP under the demo-app identity, /env opted-in + keys, `-Dlog.format=compact` emits JSONL. Gates: 48/48. + +## Memory References + +- created: thread-actuator-endpoints-node +- referenced: thread-primitive-event-bus-node, bp-publish-interop-gate, + vision-mercury-nodejs