From c0c28a6e91d4d92e4618368518416e243bc4c69b Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Sat, 29 Aug 2026 21:55:56 -0700 Subject: [PATCH] Event streaming, telemetry lineage and app log context - v4.12.0 milestone The wrapper half of the progressive-rendering program: the multi-shot reply contract and envelope-mode SSE dialect (producer EventStreamWriter + streaming /api/event host + PostOffice.stream/streamTo consumer), the engines' reply_to mechanism on the primitive bus, business correlation-id continuity, full span lineage with the engines' distributed-trace dataset on stdout logs, and the app-log-context feature with the packaged default template. Version aligned with the engine lock-step line at 4.12.0 (npm lineage jumps the legacy 4.3.x). Co-Authored-By: Claude Code --- CHANGELOG.md | 59 ++- docs/guides/function-patterns.md | 39 +- docs/guides/http-surface-reference.md | 3 +- docs/guides/streaming.md | 129 +++++ .../progressive-rendering-interop.md | 371 ++++++++++++++ examples/demo-app.mjs | 30 +- mkdocs.yml | 2 + package-lock.json | 4 +- package.json | 8 +- src/bus.ts | 270 +++++++++- src/client.ts | 349 ++++++++++++- src/config.ts | 9 + src/default-log-context.yaml | 19 + src/envelope.ts | 5 + src/event-stream.ts | 387 ++++++++++++++ src/index.ts | 14 +- src/log-context.ts | 184 +++++++ src/log.ts | 50 +- src/registry.ts | 46 +- src/server.ts | 216 +++++++- src/trace.ts | 71 ++- src/version.ts | 2 +- test/event-stream.test.ts | 482 ++++++++++++++++++ test/log-context.test.ts | 89 ++++ 24 files changed, 2773 insertions(+), 65 deletions(-) create mode 100644 docs/guides/streaming.md create mode 100644 docs/test-reports/progressive-rendering-interop.md create mode 100644 src/default-log-context.yaml create mode 100644 src/event-stream.ts create mode 100644 src/log-context.ts create mode 100644 test/event-stream.test.ts create mode 100644 test/log-context.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d384d158..597c112c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,64 @@ # Changelog -## 0.1.0 (unreleased) +## 4.12.0 (2026-08-30) +The progressive-rendering milestone release. The version aligns with the Mercury +Composable engine lock-step line (Java and Rust engines, Python and Node.js +language packs all at v4.12.0): token/event streaming end to end with full +OpenTelemetry lineage, business-correlation continuity and application log +context across all four runtimes - useful on its own, and the foundation for +the AI SDLC (agent, MCP and tool adapters as wrapper-side functions with +complete observability). (The npm lineage jumps from the legacy pre-composable +4.3.x line directly to 4.12.0.) + +- **Event streaming** - the platform-wide multi-shot reply contract, both halves. + Producer: `preload(route, { interceptor: true }, handler)` handlers receive the + raw envelope and stream through `EventStreamWriter` (the engines' exact API - + `first`, `write`, `writeNamed`, `close` with trailing metadata, `fail` with the + standard error key-values); the `/api/event` host answers a caller that accepts + `text/event-stream` with the platform's hybrid SSE dialect (envelope frames for + the head, the terminals and non-text segments; raw frames for text tokens), + refuses a non-accepting caller of a streaming function with the pinned 406, and + keeps single-shot replies over the capable path byte-identical. Consumer: + `PostOffice.stream()` (an async iterator yielding the same decoded envelopes an + engine reply route receives, with the dialect conformance guards) and + `PostOffice.streamTo()` (the relay form: forward your caller's reply address and + segments flow through verbatim - engine-parity composition). Under it all, the + primitive event bus gained the engines' reply_to mechanism: envelope-routed + delivery to a LOCAL function or per-request reply sink - simple routing, no + orchestration. Same keep-alive config key as the engines + (`event.stream.keep.alive`). Engine-identical wire and messages + (Java PR #299-#301 / Rust PR #216-#218 lineage; python twin same round). +- **Business correlation-id continuity** (the engines' PostOffice parity): the + client stamps the current context's business correlation-id onto outbound + events as the engine-managed `my_cid` tag, local bus deliveries inject the + read-only `my_correlation_id` header view exactly like the HTTP host, and + `getTrace()` / `runWithTrace()` (now exported) carry `myCorrelationId` - so + the business correlation-id continues across engine⇄wrapper and + wrapper⇄wrapper hops. +- **Span lineage** (the engines' telemetry model): every traced execution mints + a 16-hex span with the caller's span (from the inbound envelope) as its + parent, outbound events carry the current span so the next hop parents onto + it (`PostOffice.touch` parity, W3C `traceparent` included), streaming + segments carry the producer's span, and non-RPC executions emit the engines' + distributed-trace dataset record on the `distributed.tracing` log stream - + the same `{"trace": {...}, "annotations": {...}}` shape the Java engine + logs, so stdout log-ingest agents stitch spans across all four runtimes. + RPC round-trips are suppressed exactly like the engines (the new `rpc` + envelope tag rides `request()` calls). `runWithTrace()` accepts `spanId` + to parent onto an external OpenTelemetry span. Outbound events and stream + segments also fill their sender with the executing function's route, and + the `/api/event` host fills `event.api.service` for an anonymous caller - + the engines' sender-attribution rules. +- **Application log context** (the engines' app-log-context feature, on by + default via the packaged `default-log-context.yaml` - the engines' resource + twin): with `log.format` json/compact, every log line inside a traced + request carries a `context` block - cid (the business correlation-id), + traceId, tracePath, spanId, parentSpanId, service, timestamp - so app logs + and the distributed-trace records correlate end to end. Customize with + `resources/app-log-context.yaml` (reserved `$tokens` or constants with + `${ENV:default}`), opt out with `app.log.context=false`, and add + per-request key-values with `updateContext()` (reserved keys guarded). - Documentation site (mkdocs-material, the engine repo's theme): the three-layer theme reference, rationale/design foundations (including the anycast-vs-EventEmitter rationale), function-writing patterns, flow and knowledge-graph join chapters, a diff --git a/docs/guides/function-patterns.md b/docs/guides/function-patterns.md index d27d6eb3..52551149 100644 --- a/docs/guides/function-patterns.md +++ b/docs/guides/function-patterns.md @@ -75,24 +75,51 @@ message and a stack trace, mirroring the engines. Handler-level errors always ri HTTP 200; only transport-level failures (unknown route, private target, timeout, undecodable envelope) surface as HTTP status codes. -## Trace context +## Trace context and span lineage -Every delivery runs under its caller's trace: +Every delivery runs under its caller's trace, and every traced execution mints +its own **span** with the caller's span as its parent - the engines' exact +OpenTelemetry lineage model, so a chain like *user → engine flow → wrapper +function (agent, MCP tool) → engine* stays one connected trace tree: ```javascript import { annotateTrace, getTrace } from 'mercury-composable'; -const info = getTrace(); // { traceId, tracePath, cid, annotations } or undefined -annotateTrace('model', 'v3'); // rides back on the reply envelope +const info = getTrace(); // { traceId, tracePath, cid, myCorrelationId, + // spanId, parentSpanId, annotations } or undefined +annotateTrace('model', 'v3'); // rides back on the reply envelope AND the trace record ``` -Outside a hosted function (batch jobs, tests), establish context explicitly: +Outbound calls carry the current span (the receiver's parent), the business +correlation-id (`my_cid` tag), and a W3C `traceparent` header when the trace id +is W3C-shaped. Non-RPC executions emit the engines' distributed-trace dataset +on the `distributed.tracing` log stream - the same +`{"trace": {...}, "annotations": {...}}` record the Java engine logs - so a +stdout log-ingest agent (Dynatrace-style) or any log aggregation stitches the +span tree across all four runtimes. RPC round-trips fold into the caller's +view, exactly like the engines. + +**Application log context**: with `log.format` json/compact, every log line a +function writes inside a traced request carries a `context` block (the +engines' app-log-context feature, on by default) - the standard trace context +(`cid` = the business correlation-id, `traceId`, `tracePath`, `spanId`, +`parentSpanId`, `service`, `timestamp`) - so application logs and the +distributed-trace records correlate in one aggregation. Customize with your +own `resources/app-log-context.yaml` (`context:` section mapping output keys +to reserved `$tokens` or constants, `${ENV:default}` supported), opt out with +`app.log.context=false`, and add per-request key-values from a handler with +`updateContext('tenant', 'acme')` (a logging-only sink; reserved keys are +guarded; `null` removes). + +Outside a hosted function (batch jobs, tests), establish context explicitly - +including an external OpenTelemetry span to parent onto: ```javascript import { runWithTrace } from 'mercury-composable'; const reply = await runWithTrace( - { traceId: 'trace-1', tracePath: 'BATCH /nightly', cid: 'order-42', annotations: {} }, + { traceId: '4bf92f3577b34da6a3ce929d0e0e4736', tracePath: 'BATCH /nightly', + cid: 'order-42', spanId: '00f067aa0ba902b7', annotations: {} }, () => po.request('my.function', { ... }, { timeoutMs: 5000 })); ``` diff --git a/docs/guides/http-surface-reference.md b/docs/guides/http-surface-reference.md index 67012658..dcacc84a 100644 --- a/docs/guides/http-surface-reference.md +++ b/docs/guides/http-surface-reference.md @@ -22,7 +22,8 @@ Mirrors the engines' `event.api.service`: | Reply | always envelope bytes, `content-type: application/octet-stream` | | Handler outcome | rides **HTTP 200** with the status inside the envelope (including AppException and unexpected errors) | | Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`) | -| Header hygiene | inbound `x-event-api` and `my_*` removed; the `my_cid` tag becomes the read-only `my_correlation_id` header | +| Header hygiene | inbound `x-event-api` and `my_*` removed; the `my_cid` tag becomes the read-only `my_correlation_id` header (local bus deliveries inject the same view). Outbound, the client stamps the current context's business correlation-id back onto the event as the `my_cid` tag — the engines' PostOffice parity, so the business correlation-id continues across every hop | +| `accept: text/event-stream` | streaming-capable call to an interceptor target: a streamed reply rides the same call as SSE in the envelope-mode dialect; a single-shot reply stays byte-identical; a streaming reply to a NON-accepting caller → 406 `Streaming function requires a caller that accepts text/event-stream`. See [Event Streaming](streaming.md) | ## Actuator endpoints diff --git a/docs/guides/streaming.md b/docs/guides/streaming.md new file mode 100644 index 00000000..56104417 --- /dev/null +++ b/docs/guides/streaming.md @@ -0,0 +1,129 @@ +# Event Streaming + +A function that produces its result progressively — an LLM relay emitting tokens, a +long-running job reporting progress — should not make its caller wait for the whole +answer. This chapter is the wrapper's half of the platform-wide streaming contract: +the same paradigm on all four runtimes (Java, Rust, Python, Node.js): + +> **The caller provides a reply address; the callee streams events to it until a +> terminal signal.** + +Each segment is one event to the caller's `reply_to`, marked with the reserved +envelope header `x-event-stream: data | eof | exception`. A calling engine renders +the segments out its HTTP edge, hands them to a flow, or relays them onward — your +Node.js function neither knows nor cares. + +## Write a streaming function + +A streaming producer is an **interceptor**: it receives the raw `EventEnvelope` +(so the caller's reply address travels the engines' way) and replies through +`EventStreamWriter` instead of a return value: + +```javascript +import { EventStreamWriter, preload } from 'mercury-composable'; + +preload('hello.tokens', { instances: 10, interceptor: true }, async (headers, event) => { + const out = EventStreamWriter.fromRequest(event); + out.first(200, 'text/event-stream'); // head control rides the first event + out.write('The answer is'); // data segment + out.writeNamed('tokens', { n: 2 }); // named (typed) SSE event + out.close({ usage: { tokens: 2 } }); // end of transmission + trailing metadata + // or out.fail(e); // in-band failure +}); +``` + +The writer is the engines' exact API. `first(status, contentType, ttlSeconds?)` +declares the response head and, optionally, the idle allowance between segments; +`fail(e)` carries the standard error key-values +`'{"type": "error", "status": n, "message": text}'`; writes after `close()`/`fail()` +are dropped. + +An interceptor's return value is never auto-replied. To answer single-shot from an +interceptor (a relay that sometimes buffers, for example), send a plain envelope to +`event.replyTo` yourself through `registry.sendEvent()`. An uncaught exception +becomes the standard error envelope to the caller — single-shot before the stream +starts, in-band after. + +## How it crosses the wire + +When a calling engine (or `curl`) invokes your streaming function through +`POST /api/event` with `Accept: text/event-stream`, the host answers the same call +with a Server-Sent Events response in the platform's hybrid dialect: + +- **envelope frames** — the reserved SSE event name `envelope`, one base64-encoded + serialized envelope per frame — carry everything with envelope semantics: the + first event (head control), the `eof`/`exception` terminals, and any segment that + cannot round-trip as plain text (an object or binary body, text containing a + carriage return, an event name colliding with the reserved word); +- **raw SSE frames** carry plain text segments, so token relays stay near-zero + overhead. + +Everything degrades explicitly: a caller that did not opt in receives +`406 Streaming function requires a caller that accepts text/event-stream` instead of +a truncated reply; a non-streaming (single-shot) answer over the capable path is +byte-identical to a normal RPC reply; idle expiry fails the stream in-band with the +standard 408 error body. The `x-ttl` request header (ms) is the idle allowance +between segments — your `first(..., ttlSeconds)` can extend it for the whole stream. +While the producer is quiet, the host emits `: ping` keep-alive comments +(`event.stream.keep.alive`, the engines' config key — default 30s, `0` disables). + +## Consume a stream + +`PostOffice.stream()` is the consumer surface — an async iterator yielding the same +decoded envelopes an engine reply route receives: `data` segments, then the terminal. +It works against a remote peer's `/api/event` (an engine or another function host) +and against local functions alike, and opting in is always safe — a non-streaming +target simply yields its one classic reply: + +```javascript +import { PostOffice } from 'mercury-composable'; + +const po = new PostOffice(); +for await (const segment of po.stream('hello.tokens', undefined, { + endpoint: 'http://127.0.0.1:8100/api/event', timeoutMs: 30000 +})) { + const marker = segment.headers['x-event-stream']; + if (marker === 'data') { + console.log(segment.body); + } else if (marker === 'exception') { + throw new Error(segment.body.message); + } + // eof: segment.body carries the trailing metadata, if any +} +``` + +`timeoutMs` is the idle allowance between segments. The consumer guards the dialect +for you: a malformed frame, a stream that ends without a terminal, or idle expiry +each yield the standard in-band exception envelope, then the iterator ends. + +## Compose a relay + +The pattern the whole streaming program is built on: forward **your own caller's** +reply address into a call against a remote streaming function, and the segments flow +`engine → your function → remote peer → back to the original caller` with no +buffering anywhere: + +```javascript +preload('llm.relay', { instances: 10, interceptor: true }, async (headers, event) => { + const po = new PostOffice(); + await po.streamTo('remote.tokens', undefined, event.replyTo ?? '', { + endpoint: 'http://peer:8085/api/event', cid: event.cid, timeoutMs: 30000 + }); +}); +``` + +`streamTo()` forwards every decoded envelope verbatim to the named LOCAL route +(here, the reply sink the host opened for your caller) and returns the terminal. +Combined with a calling engine's `stream: true` endpoint, this streams a remote +peer's tokens progressively out that engine's HTTP edge — with zero imperative +streaming code in between. + +## See also + +- The engines' HTTP Response Streaming guides (the same contract at the HTTP edge): + [Java](https://accenture.github.io/mercury-composable/guides/http-streaming/) · + [Rust](https://accenture.github.io/mercury/guides/http-streaming/) +- [Interop Test Report — Progressive Rendering](../test-reports/progressive-rendering-interop.md) — + the live four-runtime validation of this contract +- [HTTP Surface Reference](http-surface-reference.md) — the `/api/event` contract +- [Function Writing Patterns](function-patterns.md) diff --git a/docs/test-reports/progressive-rendering-interop.md b/docs/test-reports/progressive-rendering-interop.md new file mode 100644 index 00000000..49149208 --- /dev/null +++ b/docs/test-reports/progressive-rendering-interop.md @@ -0,0 +1,371 @@ +--- +title: Interop Test Report — Progressive Rendering, all four runtimes +summary: Permanent record of the live cross-runtime validation of the progressive + streaming contract - the multi-shot reply protocol and the Event-over-HTTP + envelope-mode SSE dialect - across the Java and Rust engines and the Python and + Node.js function hosts. +layer: reference +audience: [developer, architect] +keywords: [interop, streaming, sse, event over http, envelope mode, test report] +--- + +# Interop Test Report — Progressive Rendering, all four runtimes + +*Live cross-runtime validation of the progressive streaming contract across the four +Mercury Composable runtimes — the Java engine +([mercury-composable](https://github.com/Accenture/mercury-composable)), the Rust engine +([mercury](https://github.com/Accenture/mercury)), and the Python +([mercury-python](https://github.com/Accenture/mercury-python)) and Node.js +([mercury-nodejs](https://github.com/Accenture/mercury-nodejs)) function hosts — conducted +2026-08-30 (UTC) at the close of the streaming program's wrapper round. This report is a +permanent record in the tradition of the +[Event over HTTP interop report](https://accenture.github.io/mercury-composable/test-reports/event-over-http-interop/): what was tested, the +evidence, and the defects the round surfaced with their fixes.* + +## The contract under test + +One paradigm on all four runtimes: **the caller provides a reply address; the callee +streams events to it until a terminal signal.** Each segment is one event to the +caller's `reply_to`, marked with the reserved envelope header +`x-event-stream: data | eof | exception`. Across the Event-over-HTTP hop, the peer +answers the one POST with a Server-Sent Events response in the **hybrid envelope-mode +dialect**: envelope frames (the reserved SSE event name `envelope`, one base64-encoded +serialized envelope per frame) wherever envelope semantics matter — the head, the +terminals, and any segment that cannot round-trip as plain text — and raw SSE frames +for text tokens. The consuming client decodes the dialect and forwards each event to +the original reply address with the original correlation id, so a local stream and a +remote stream are indistinguishable to the consumer. + +Delivered by: Java engine PRs +[#299](https://github.com/Accenture/mercury-composable/pull/299) (edge streaming), +[#300](https://github.com/Accenture/mercury-composable/pull/300) (SSE consumption), +[#301](https://github.com/Accenture/mercury-composable/pull/301) (envelope mode) — +ADR-0018/0019; Rust engine PRs +[#216](https://github.com/Accenture/mercury/pull/216), +[#217](https://github.com/Accenture/mercury/pull/217), +[#218](https://github.com/Accenture/mercury/pull/218) — ADR-0015/0016; and the +matching wrapper round in mercury-python and mercury-nodejs (interceptor functions, +`EventStreamWriter`, streaming `/api/event` host, `stream()`/`stream_to()` client). + +## The live matrix + +Ten producer/consumer combinations were driven live with the SHIPPED demo applications +— no test shims. Producers pace their segments (300 ms in these drives), so +progressive delivery is directly observable in the arrival timestamps; buffered +delivery would show all segments arriving together. + +| # | Consumer | Producer | Result | +|---|----------|----------|--------| +| 1 | Node.js client | Python `hello.tokens` | segments at ~11/312/612/916 ms, eof metadata `{count, language: python}` | +| 2 | Python client | Node.js `hello.tokens` | segments at ~5/304/606/908 ms, eof metadata `{count, language: node.js}` | +| 3 | Python client | **Java engine** `hello.sse` | segments at ~103/407/708/1012 ms, terminal `eof` | +| 4 | Node.js client | **Java engine** `hello.sse` | segments at ~13/320/620/924 ms, terminal `eof` | +| 5 | Python client | **Rust engine** `hello.sse` | segments at ~3/306/607 ms, terminal `eof` | +| 6 | Node.js client | **Rust engine** `hello.sse` | segments at ~10/312/615 ms, terminal `eof` | +| 7 | **Java engine** edge (`/api/hello/remote`) | Python `hello.tokens` | SSE out the engine edge at ~195/493/793/1094 ms, terminal `event: done` with the Python eof metadata | +| 8 | **Java engine** edge | Node.js `hello.tokens` | ~217/516/817 ms, terminal metadata `{count, language: node.js}` | +| 9 | **Rust engine** edge | Python `hello.tokens` | ~20/323/624 ms, same shape | +| 10 | **Rust engine** edge | Node.js `hello.tokens` | ~19/320/622 ms, same shape | + +Common observations across all ten: + +- **Progressive on the wire** — arrival gaps match the producer's pacing; nothing + buffers end-to-end (rows 7–10 traverse the full chain: HTTP edge → engine relay + function → Event-over-HTTP → wrapper host → wrapper function and back). +- **Correlation** — the caller's correlation id is restored on every delivered + envelope (D7), and the engines' demo authentication (`authorization: demo`) rides + the per-target security headers unchanged. +- **Exact types** — eof trailing metadata arrives as a real map, not text, on every + path (the envelope-frame escape hatch). +- **Explicit degradation, observed live** — a missing token produced the engine's + 401 and a private target its 403, both delivered as clean envelopes through the + buffered fallback; a caller without the `accept: text/event-stream` opt-in receives + the pinned `406 Streaming function requires a caller that accepts + text/event-stream`. + +## Engine ⇄ engine and per-runtime coverage + +Because the protocol signatures are identical across the four runtimes, each +repository's unit suite exercises the full protocol against its own application +instance (client consuming its own `/api/event` host in one process): Java +`EventOverHttpStreamTest` (14 cases), Rust `event_over_http_stream.rs` (14), Python +`test_event_stream.py` (17), Node.js `event-stream.test.ts` (17). Each suite also +carries **misbehaving-peer fixtures** — a raw first frame, a transport end without a +decoded terminal, trailing frames after the terminal — because a self-loop alone +cannot catch a deviation implemented identically in both halves of one runtime; the +live matrix above is the cross-implementation conformance check, and it passed with +zero shims. + +## Trace continuity (OpenTelemetry span / parent-span verification) + +The drives were repeated with telemetry capture to verify distributed-trace +continuity across the streaming hop. Findings, with the observed evidence: + +- **One trace id end to end, both directions.** In the engine→wrapper drive, the + Java edge minted trace `f22af2e005f2445198563e2dc4f1ba54`; every engine span + carried it (the relay function, the HTTP client leg, each reply-lane segment + delivery), the Python function received it (trace id and path ride inside the + wire envelope), and the demo now echoes it in the eof trailing metadata - so + the terminal frame rendered out the engine's own edge carries the same trace + id the edge minted: continuity is self-documenting in the demo output. In the + wrapper→engine drive, a Python caller supplied W3C trace id + `4bf92f3577b34da6a3ce929d0e0e4736` with trace path `PY /stream-drive`; the + engine's `event.api.auth`, `event.api.service` and `hello.sse` spans all + carried that id, and the function's span carried the caller's trace path. +- **Span parenting chains on the engines.** The streaming target's span parents + onto the Event API service span - observed live: + `event.api.service span_id=bfcddb32dd597ddb` → + `hello.sse parent_span_id=bfcddb32dd597ddb`. Outbound, the engines' relay leg + sends the W3C `traceparent` header carrying the sending function's span id + (the trace-aware PostOffice stamps the span onto the outbound event), so a + receiving ENGINE parents its spans onto the caller's - the same cross-engine + parenting validated in the Event over HTTP interop report. +- **Wrapper executions are real spans** (closed at this round - the wrappers + originally propagated the trace id but minted no spans, which broke the + lineage into disconnected segments at every wrapper hop). The function hosts + now implement the engines' exact span model: every traced execution mints a + 16-hex span with the caller's span (from the inbound envelope) as its + parent; outbound calls and stream segments carry the current span onward; + and non-RPC executions emit the engines' distributed-trace dataset record on + the `distributed.tracing` log stream - the same + `{"trace": {...}, "annotations": {...}}` shape the Java engine logs - so one + log aggregation (or a stdout log-ingest agent forwarding to an observability + dashboard) stitches the full span tree across all four runtimes. RPC + round-trips emit no dataset, exactly like the engines: their metrics fold + into the caller's view. +- **The connected tree, live-proven in all three directions.** Engine→wrapper: + under one Java-edge trace, the relay function's span `8cbc0b4d4be75362` + became the Python `hello.tokens` span's parent (`span_id=7b90847f4b8b617a`, + `parent_span_id=8cbc0b4d4be75362` in the wrapper's own trace record), and + the Java reply-lane delivery spans then parented onto the Python span - + edge → engine function → wrapper function → engine deliveries, one unbroken + chain. Wrapper→engine: a Python caller carrying external span + `00f067aa0ba902b7` (the shape of a user-edge OpenTelemetry span) produced + `event.api.auth` and `event.api.service` spans parented on it, with + `hello.sse` parented on the service span. Wrapper⇄wrapper: a Node.js + execution's record showed the Python caller's span as its parent. This is + the lineage the AI SDLC requires - user → agent → MCP → tools in one tree. +- **One deliberate exception**: plain-text token segments ride raw SSE frames, + which carry no envelope metadata (the zero-overhead token path), so their + engine-side delivery spans join the trace unparented; a stream's head and + terminal segments ride envelope frames and parent correctly. The engines' + HTTP client leg (`async.http.request`) remains a sibling span - classic + Event-over-HTTP parity. +- **Correlation id**: the caller's cid rode every delivered envelope in every + drive (`cid-trace-drive` on all four segments of the supplied-trace drive). + +The check itself surfaced defect #5: the engine demo relay originally built its +forward event with the raw EventEmitter, which stamps no trace - the hop +continued cid but DROPPED the trace id. Fixed by using a trace-aware +PostOffice (its `touch` fill-stamps from/trace/span), and the wrapper demos' +`hello.tokens` now echo their received trace id in the eof metadata so the +continuity is visible in every future drive. + +## Business correlation-id continuity + +The same verification was run for the business correlation-id (`my_cid`) - the +engine-managed envelope tag captured at an engine's HTTP edge from the +configured header (default `X-Correlation-Id`) and injected into every +receiving function's input headers as the read-only `my_correlation_id` view. +The wrapper demos' `hello.tokens` echo the view in the eof metadata alongside +the trace id, so every future drive self-documents both continuity dimensions. +Live results: + +- **Java engine edge → Python**: `X-Correlation-Id: biz-e2w-001` on the edge + request came back in the terminal metadata rendered out the same edge - + edge header → `my_cid` tag → relay function's injected header view → + trace-aware PostOffice re-stamp → packed envelope over the hop → wrapper + host injection → function echo. +- **Rust engine edge → Python**: `biz-rust-005` echoed identically. The Rust + demo relay needed no change: the Rust engine has one PostOffice and + `apply_current_trace` always stamps trace and business correlation-id from + the ambient context. +- **Python → Node.js and Node.js → Python** (wrapper ⇄ wrapper): a caller-side + context (`trace_context(..., my_correlation_id=...)` / `runWithTrace({..., + myCorrelationId})`) produced `biz-w2w-002` / `biz-w2w-003` echoes from the + opposite wrapper - the tag crossed the hop and the receiving host injected + the view. +- **Wrapper → engine**: the wrappers stamp the identical tag bytes (the same + codec proven above), and the engines' pinned suites cover the receiving + half: an `/api/event` caller carrying the `my_cid` tag reaches the target + function as `po.getMyCorrelationId()` (Java + `EventHttpTest.eventOverHttpPropagatesTraceAndCorrelationId`; Rust twin). + +The check surfaced one parity gap in the (unreleased) wrapper round, fixed and +test-pinned in both wrappers: the wrapper clients inherited trace id/path and +the internal correlation id into outbound events but did not re-stamp the +business correlation-id as the `my_cid` tag, and local bus deliveries skipped +the header-view injection that the HTTP host performs. Both halves now mirror +the engines (`PostOffice.touch` / WorkerHandler parity): outbound events carry +the context's business correlation-id as the tag, local deliveries inject the +read-only view, and the trace context (`get_trace()` / `getTrace()`) exposes +it to handlers and relays. + +By design (confirmed at this verification round): an engine's `/api/event` +ingress serves LOCAL routes only - it answers 404 for a route it does not +host, even when its own `yaml.event.over.http` map points that route at a +peer. The map is caller-side routing for the app's own outbound calls; +forwarding inbound calls onward would make every application an +Event-over-HTTP relay and open routing loops (the `x-event-api` wire marker +exists precisely to prevent such re-forwarding). Callers address the owning +peer directly; deliberate hop-through composition is an explicit relay +function - the demo `hello.remote.relay` is exactly that pattern. + +## Defects surfaced by the round (fixed and re-verified) + +Honest engineering record — each was caught by the twin-building discipline before +any release: + +1. **Rust engine**: the envelope-mode single-shot reply initially reached the caller + unwrapped (rendered as plain JSON instead of the classic packed-envelope wire); + fixed by wrapping at the one `SingleShot` outcome site — caught by the twin suite's + first run. +2. **Node.js host**: a `Promise.race` against a queue waiter abandoned the losing + waiter, which would steal and drop the next envelope; fixed by reusing one pending + promise across keep-alive cycles (`raceMs` documents the rule) — caught in design + review before the first test run. +3. **Error-body contract**: the in-band exception bodies converged on the standard + error key-values `type` / `status` / `message` across all four runtimes (three + Java sites and their twins were missing the `type` key or used a plain-text body). +4. **Node.js**: object error bodies would have stringified as `[object Object]`; + fixed with JSON rendering (`errorText`). +5. **Java demo relay**: the forward event was built with the raw (untraced) + EventEmitter, silently dropping the distributed trace across the hop; fixed + with a trace-aware PostOffice - found by the trace-continuity verification + above. + +## Reproduce + +Every row of the matrix uses shipped demo applications: + +- **Engine as producer**: run the Java `lambda-example` (port 8085) or Rust + `hello-world` (8085; any port with `-Drest.server.port=…`); their public + `hello.sse` streams paced test messages. Consume from a wrapper with + `PostOffice.stream("hello.sse", …, endpoint="http://host:port/api/event")` and the + demo `authorization: demo` header. +- **Engine as consumer**: run a wrapper demo app (python `mercury-serve + examples/demo_app.py`, port 8086; node demo, 8087), then the engine demo with its + routing map (Java: `-Dyaml.event.over.http=classpath:/event-over-http.yaml`; Rust: + ships enabled) and `-Dpeer.demo.port` as needed, and watch + `curl -N -H 'accept: text/event-stream' + 'http://127.0.0.1:8085/api/hello/remote?delay=300&count=3'` render the wrapper's + tokens progressively out the engine's edge. +- **Wrapper ⇄ wrapper**: point either wrapper's `stream()` at the other demo's + `/api/event`. + +Baselines at the time of the drives: Java engine main after PR #301, Rust engine main +after PR #218, mercury-python and mercury-nodejs at the streaming feature round - +shipped together as the v4.12.0 milestone release across all four repositories. + +## Appendix - telemetry and app context example (live capture) + +One live request, captured end to end, showing how the telemetry stream and +the application log context connect the engine to the wrapper. Setup: the Java +`lambda-example` (port 8085) with its event-over-http map pointing +`hello.tokens` at the Python demo app (port 8086, `-Dlog.format=compact`). +The caller supplies a business correlation-id; the engine's HTTP edge mints +the trace: + +```bash +curl -N -H 'accept: text/event-stream' -H 'X-Correlation-Id: biz-e2e-777' \ + 'http://127.0.0.1:8085/api/hello/remote?delay=100&count=1' +``` + +**1. Java engine - the relay function's telemetry record** (the root span of +trace `710dcb0b706e4b5b949be138d0992b0b`, minted at the edge): + +```json +{ + "level": "INFO", + "time": "2026-08-29 21:24:17.734", + "source": "org.platformlambda.core.services.Telemetry.handleEvent(Telemetry.java:81)", + "thread": 762, + "message": { + "trace": { + "path": "GET /api/hello/remote?delay=100&count=1", + "span_id": "afa2897918e3871b", + "service": "hello.remote.relay", + "success": true, + "origin": "20260830a0dcb550832b4683b4853c609778cd82", + "start": "2026-08-30T04:24:17.733Z", + "exec_time": 0.728, + "from": "http.request", + "id": "710dcb0b706e4b5b949be138d0992b0b", + "status": 200 + } + } +} +``` + +**2. The wire** - the relay's trace-aware PostOffice stamps the outbound event +with the trace id and path, its own span id (`afa2897918e3871b`) and the +`my_cid` tag (`biz-e2e-777`); the whole envelope crosses `POST /api/event`, +with `X-Trace-Id` and the W3C `traceparent` on the HTTP headers. + +**3. Python wrapper - the function's own application log line.** The handler +runs `log.info("Streaming %d messages", count)`; the app-log-context feature +adds the `context` block. Note the join keys: the engine's trace id, the +business `cid` from the edge header, and this execution's `spanId` with the +relay's span as `parentSpanId`: + +```json +{"time": "2026-08-29 21:24:17.847", "level": "INFO", "logger": "mercury_user_app:93", "message": "Streaming 1 messages", "context": {"cid": "biz-e2e-777", "traceId": "710dcb0b706e4b5b949be138d0992b0b", "tracePath": "GET /api/hello/remote?delay=100&count=1", "spanId": "55ebd6464ffdf9c2", "parentSpanId": "afa2897918e3871b", "service": "hello.tokens", "timestamp": "2026-08-30T04:24:17.847Z"}} +``` + +**4. Python wrapper - the telemetry record for the same execution** (same +`span_id` as the app log line's `spanId` - the join key between the two +streams; `from` names the calling engine function): + +```json +{"time": "2026-08-29 21:24:17.949", "level": "INFO", "logger": "distributed.tracing:158", "message": {"trace": {"origin": "202608303cbae673831a4ab08cbb6f108fec0171", "id": "710dcb0b706e4b5b949be138d0992b0b", "path": "GET /api/hello/remote?delay=100&count=1", "service": "hello.tokens", "start": "2026-08-30T04:24:17.847Z", "success": true, "from": "hello.remote.relay", "exec_time": 101.673, "status": 200, "span_id": "55ebd6464ffdf9c2", "parent_span_id": "afa2897918e3871b"}}} +``` + +**5. Java engine - a reply-lane delivery record.** The wrapper's stream +segments carry its span, so the engine-side delivery span parents onto the +Python function (`parent_span_id = 55ebd6464ffdf9c2`): + +```json +{ + "level": "INFO", + "time": "2026-08-29 21:24:17.853", + "source": "org.platformlambda.core.services.Telemetry.handleEvent(Telemetry.java:81)", + "thread": 779, + "message": { + "trace": { + "path": "GET /api/hello/remote?delay=100&count=1", + "parent_span_id": "55ebd6464ffdf9c2", + "span_id": "a50c19b7415406df", + "service": "async.http.response.stream.499", + "success": true, + "origin": "20260830a0dcb550832b4683b4853c609778cd82", + "start": "2026-08-30T04:24:17.851Z", + "exec_time": 1.202, + "from": "hello.tokens", + "id": "710dcb0b706e4b5b949be138d0992b0b", + "status": 200 + } + } +} +``` + +**6. The caller's view** - the terminal SSE frame rendered back out the Java +edge echoes both continuity dimensions: + +```text +event: done +data: {"trace_id":"710dcb0b706e4b5b949be138d0992b0b","count":1,"my_correlation_id":"biz-e2e-777","language":"python"} +``` + +**Connectivity, in one paragraph.** Every record above carries the one trace +id the engine minted at its HTTP edge, and the span ids chain across the +runtime boundary in both directions: the edge request → the relay function's +span (`afa289...`) → the Python execution's span (`55ebd6...`, parented on the +relay) → the engine's reply-lane delivery spans (parented on the Python span). +The business correlation-id from the `X-Correlation-Id` edge header rides the +`my_cid` envelope tag through every hop and surfaces as the `cid` in the +wrapper's app-log context and in the demo's terminal metadata. The wrapper's +application log line and its telemetry record share the same `span_id`, which +is what lets a log aggregation (or a stdout log-ingest agent) attach a +function's own log output to the exact span of the distributed trace - the +complete telemetry and app-context story from user to engine to wrapper and +back, assembled entirely from the four runtimes' stdout logs. diff --git a/examples/demo-app.mjs b/examples/demo-app.mjs index 0e34549c..0efa718f 100644 --- a/examples/demo-app.mjs +++ b/examples/demo-app.mjs @@ -13,7 +13,9 @@ * - route: 'hello.node' * target: 'http://127.0.0.1:8087/api/event' */ -import { AppException, annotateTrace, getLogger, preload } from '../dist/src/index.js'; +import { + AppException, annotateTrace, EventStreamWriter, getLogger, getTrace, preload +} from '../dist/src/index.js'; const log = getLogger('demo-app'); @@ -44,6 +46,32 @@ preload('hello.chain', { instances: 10 }, async (_headers, body) => { return reply.body; }); +// Streaming demo: paced test messages over the multi-shot reply contract. +// A calling engine consumes this progressively through Event-over-HTTP +// (accept: text/event-stream on the outbound event) and can render it out its +// own HTTP edge - engine-to-wrapper token streaming. Optional headers: +// "delay" ms between messages (default 500, clamped 50-5000) and "count" +// messages (default 5, clamped 1-100). +preload('hello.tokens', { instances: 10, interceptor: true }, async (headers, event) => { + const delay = Math.min(5000, Math.max(50, Number.parseInt(headers.delay ?? '500', 10) || 500)); + const count = Math.min(100, Math.max(1, Number.parseInt(headers.count ?? '5', 10) || 5)); + // with log.format=json/compact, this line carries the application log + // "context" block (trace ids, business cid) - see the streaming guide + log.info(`Streaming ${count} messages`); + const out = EventStreamWriter.fromRequest(event); + out.first(200, 'text/event-stream'); + out.write('The following messages are rendered slowly to demonstrate streaming:'); + for (let n = 1; n <= count; n++) { + await new Promise((resolve) => setTimeout(resolve, delay)); + out.write(`test message ${n} (node.js)`); + } + // the trailing metadata echoes the distributed trace id and the business + // correlation-id, so a calling engine's edge shows both continuity + // dimensions end to end + out.close({ count, language: 'node.js', trace_id: getTrace()?.traceId ?? null, + my_correlation_id: headers.my_correlation_id ?? null }); +}); + // Health check speaking the engines' interface contract (type=info / type=health). // Activated for the /health actuator endpoint by mandatory.health.dependencies // in examples/resources/application.yml (or a -D override). diff --git a/mkdocs.yml b/mkdocs.yml index 33af34de..9a3c92a0 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -109,6 +109,7 @@ nav: - Write functions: - Function Writing Patterns: guides/function-patterns.md + - Event Streaming: guides/streaming.md - Configuration, Logging & Actuators: guides/config-logging-actuators.md - Testing Your Functions: guides/testing.md @@ -122,5 +123,6 @@ nav: - Reference: - Configuration Reference: guides/configuration-reference.md - HTTP Surface Reference: guides/http-surface-reference.md + - Interop Test Report — Progressive Rendering: test-reports/progressive-rendering-interop.md - Release Notes: https://github.com/Accenture/mercury-nodejs/blob/main/CHANGELOG.md - Contributing: https://github.com/Accenture/mercury-nodejs/blob/main/CONTRIBUTING.md diff --git a/package-lock.json b/package-lock.json index 0164a06f..d9c59802 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mercury-composable", - "version": "0.1.0", + "version": "4.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mercury-composable", - "version": "0.1.0", + "version": "4.12.0", "license": "Apache-2.0", "dependencies": { "@msgpack/msgpack": "^3.0.0", diff --git a/package.json b/package.json index 51c96eb0..f4734da7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mercury-composable", - "version": "0.1.0", + "version": "4.12.0", "description": "Lightweight Event-over-HTTP function host and client for Mercury Composable", "type": "module", "license": "Apache-2.0", @@ -30,9 +30,9 @@ "README.md" ], "scripts": { - "build": "tsc -p .", - "test": "tsc -p . && node --test dist/test/*.test.js", - "prepack": "tsc -p ." + "build": "tsc -p . && node -e \"require('node:fs').cpSync('src/default-log-context.yaml','dist/src/default-log-context.yaml')\"", + "test": "npm run build && node --test dist/test/*.test.js", + "prepack": "npm run build" }, "dependencies": { "@msgpack/msgpack": "^3.0.0", diff --git a/src/bus.ts b/src/bus.ts index 755b5bd9..be05fcb6 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -36,7 +36,9 @@ 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'; +import { randomBytes } from 'node:crypto'; +import { appOrigin } from './actuator.js'; +import { MY_CID_TAG, MY_CORRELATION_ID, RPC_TAG, runWithTrace, TraceInfo } from './trace.js'; const log = getLogger('mercury.bus'); @@ -61,6 +63,10 @@ interface TraceFields { traceId?: string; tracePath?: string; cid?: string; + // the raw envelope: delivery context for engine-managed tags (e.g. the + // business correlation-id), and the verbatim event an interceptor handler + // receives - reply_to and correlation id travel the engines' way + envelope?: EventEnvelope; } interface Delivery extends TraceFields { @@ -71,14 +77,103 @@ interface Delivery extends TraceFields { resolve?: (reply: EventEnvelope) => void; // drop-n-forget deliveries carry no resolver } +/** + * The caller's business correlation-id at delivery: the engine-managed my_cid + * envelope tag, else a my_correlation_id view already injected by an HTTP host + * (the engines' WorkerHandler resolution order). + */ +function businessCid(delivery: Delivery): string | undefined { + return delivery.envelope?.tags[MY_CID_TAG] ?? delivery.headers[MY_CORRELATION_ID]; +} + +/** + * The handler's header view, with the read-only business correlation-id + * injected at delivery (engine parity). + */ +function headersView(delivery: Delivery, myCid: string | undefined): Record { + if (myCid && !(MY_CORRELATION_ID in delivery.headers)) { + return { ...delivery.headers, [MY_CORRELATION_ID]: myCid }; + } + return delivery.headers; +} + +// the engines' distributed-trace log stream (Java Telemetry parity) +const telemetryLog = getLogger('distributed.tracing'); + +/** + * The execution's trace context. Under a trace, every execution mints its own + * 16-hex span and records the caller's span (from the inbound envelope) as + * its parent - the engines' WorkerHandler model. + */ +function traceInfoOf(delivery: Delivery, myCid: string | undefined): TraceInfo { + return { + route: delivery.service.route, + traceId: delivery.traceId, + tracePath: delivery.tracePath, + cid: delivery.cid, + myCorrelationId: myCid, + spanId: delivery.traceId ? randomBytes(8).toString('hex') : undefined, + parentSpanId: delivery.envelope?.spanId, + annotations: {} + }; +} + +/** + * True for an RPC round-trip: a local reply resolver, or the engines' rpc + * envelope tag transported over the wire. RPC legs emit no trace dataset + * (engine parity) - their metrics fold into the caller's view. + */ +function isRpc(delivery: Delivery): boolean { + return Boolean(delivery.resolve) || Boolean(delivery.envelope?.tags[RPC_TAG]); +} + +/** + * Emit the engines' distributed-trace dataset for a traced, non-RPC + * execution - the same record shape the Java reference engine logs + * (message = {"trace": {...}, "annotations": {...}}), so polyglot log + * aggregation and stdout log-ingest agents stitch spans across runtimes. + */ +function emitTrace(delivery: Delivery, info: TraceInfo, start: string, + execTime: number, status: number, success: boolean, + exception: string | undefined): void { + if (!info.traceId || isRpc(delivery)) { + return; + } + const trace: Record = { + origin: appOrigin(), + id: info.traceId, + path: info.tracePath, + service: delivery.service.route, + start, + success, + from: delivery.envelope?.sender ?? 'unknown', + exec_time: execTime, + status + }; + if (!success && exception) { + trace.exception = exception; + } + if (info.spanId) { + trace.span_id = info.spanId; + } + if (info.parentSpanId) { + trace.parent_span_id = info.parentSpanId; + } + const dataset: Record = { trace }; + if (Object.keys(info.annotations).length) { + dataset.annotations = { ...info.annotations }; + } + telemetryLog.info(dataset); +} + const CLOSED: unique symbol = Symbol('bus-closed'); -/** Unbounded FIFO handing items to awaiting workers. */ -class Mailbox { - private readonly items: Array = []; - private readonly waiters: Array<(item: Delivery | typeof CLOSED) => void> = []; +/** Unbounded FIFO handing items to awaiting consumers (node's missing asyncio.Queue). */ +export class Mailbox { + private readonly items: T[] = []; + private readonly waiters: Array<(item: T) => void> = []; - push(item: Delivery | typeof CLOSED): void { + push(item: T): void { const waiter = this.waiters.shift(); if (waiter) { waiter(item); @@ -87,7 +182,7 @@ class Mailbox { } } - next(): Promise { + next(): Promise { const item = this.items.shift(); if (item !== undefined) { return Promise.resolve(item); @@ -96,18 +191,82 @@ class Mailbox { } } +/** + * Race one PENDING promise against a timeout; null on expiry. The pending + * promise survives a lost race (a bare promise cannot be cancelled), so a + * caller that keeps waiting must keep reusing THE SAME promise until it + * resolves - a fresh queue.next() per cycle would leave an abandoned waiter + * in the mailbox that steals and drops the next item. A caller that + * terminates on expiry may race a fresh promise each time. + */ +export async function raceMs(pending: Promise, timeoutMs: number): Promise { + let timer: NodeJS.Timeout | undefined; + const expiry = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), Math.max(1, timeoutMs)); + }); + try { + return await Promise.race([pending, expiry]); + } finally { + clearTimeout(timer); + } +} + +/** Route an envelope to a local target - wired by the registry (backref). */ +export type EnvelopeRouter = (event: EventEnvelope) => boolean; + /** Per-registry bus: one FIFO mailbox and N workers per registered route. */ export class EventBus { - private readonly mailboxes = new Map(); + private readonly mailboxes = new Map>(); + // per-request reply sinks (the engines' inbox idea): generated local route + // names backed by queues - the reply_to addressing of interceptor dispatch + // and of streaming responses. Local-only by design. + private readonly sinks = new Map>(); + // reply routing for the interceptor error contract (registry owns this bus) + private router: EnvelopeRouter | undefined; + private sinkSequence = 0; + + bindRouter(router: EnvelopeRouter): void { + this.router = router; + } + + /** Open a per-request reply sink under a generated local route name. */ + openSink(): [string, Mailbox] { + const route = `inbox.${++this.sinkSequence}.${Date.now().toString(36)}`; + const queue = new Mailbox(); + this.sinks.set(route, queue); + return [route, queue]; + } - private mailbox(service: ServiceDef): Mailbox { + closeSink(route: string): void { + this.sinks.delete(route); + } + + /** + * Deliver an envelope to a reply sink; false when the sink is gone (a + * completed, timed-out or disconnected request) - late segments are no-op + * drops, the engines' semantics. + */ + offerSink(route: string, event: EventEnvelope): boolean { + const queue = this.sinks.get(route); + if (!queue) { + return false; + } + queue.push(event); + return true; + } + + 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); + const created = new Mailbox(); + mailbox = created; + this.mailboxes.set(service.route, created); for (let n = 0; n < service.instances; n++) { - void this.runWorker(mailbox); + // workers are long-lived loops created lazily on first use, so they + // would inherit the creating caller's trace store - detach so nothing + // from an arbitrary first caller leaks into later executions' logs + void runWithTrace(undefined, () => this.runWorker(created)); } } return mailbox; @@ -142,6 +301,19 @@ export class EventBus { return asyncAck(); } + /** + * Route one envelope to a local function (the reply_to mechanism): + * drop-n-forget delivery carrying the raw envelope, so an interceptor + * handler receives reply_to and the correlation id the engines' way. + */ + publishEnvelope(service: ServiceDef, event: EventEnvelope): void { + this.mailbox(service).push({ + service, headers: { ...event.headers }, body: event.body, settled: false, + traceId: event.traceId, tracePath: event.tracePath, cid: event.cid, + envelope: event + }); + } + /** Stop all workers (orderly shutdown; worker promises hold no OS handle). */ close(): void { for (const mailbox of this.mailboxes.values()) { @@ -150,7 +322,7 @@ export class EventBus { this.mailboxes.clear(); } - private async runWorker(mailbox: Mailbox): Promise { + private async runWorker(mailbox: Mailbox): Promise { for (;;) { const delivery = await mailbox.next(); if (delivery === CLOSED) { @@ -161,7 +333,9 @@ export class EventBus { if (delivery.settled) { continue; } - const reply = await EventBus.execute(delivery); + const reply = delivery.service.interceptor + ? await this.executeInterceptor(delivery) + : await EventBus.execute(delivery); if (delivery.resolve) { if (!delivery.settled) { delivery.settled = true; @@ -176,17 +350,15 @@ export class EventBus { /** Run the handler under its trace context and shape the outcome as a reply. */ private static async execute(delivery: Delivery): Promise { - const info: TraceInfo = { - traceId: delivery.traceId, - tracePath: delivery.tracePath, - cid: delivery.cid, - annotations: {} - }; + const myCid = businessCid(delivery); + const headers = headersView(delivery, myCid); + const info = traceInfoOf(delivery, myCid); + const startIso = isoUtc(); const start = process.hrtime.bigint(); let reply: EventEnvelope; try { const result = await runWithTrace(info, async () => - delivery.service.handler(delivery.headers, delivery.body)); + delivery.service.handler(headers, delivery.body)); reply = result instanceof EventEnvelope ? result : new EventEnvelope(undefined, result); } catch (e) { if (e instanceof AppException) { @@ -206,6 +378,62 @@ export class EventBus { if (Object.keys(info.annotations).length) { reply.annotations = { ...info.annotations, ...reply.annotations }; } + emitTrace(delivery, info, startIso, reply.execTime, reply.getStatus(), + !reply.hasError(), reply.hasError() ? String(reply.body) : undefined); return reply; } + + /** + * Run an interceptor handler: it receives the raw envelope, replies + * manually through reply_to (the engines' EventInterceptor contract), and + * its return value is discarded. An uncaught exception becomes an error + * envelope to the delivery's reply_to - so a caller waiting on a reply + * sink sees it - and a streaming host renders it in-band. + */ + private async executeInterceptor(delivery: Delivery): Promise { + const event = delivery.envelope ?? + new EventEnvelope(delivery.service.route, delivery.body, delivery.headers); + const myCid = businessCid(delivery); + const headers = headersView(delivery, myCid); + const info = traceInfoOf(delivery, myCid); + const startIso = isoUtc(); + const start = process.hrtime.bigint(); + let error: unknown; + try { + await runWithTrace(info, async () => + delivery.service.handler(headers, event)); + } catch (e) { + error = e; + this.replyInterceptorError(delivery.service.route, event, e); + } + const status = error instanceof AppException ? error.status : (error ? 500 : 200); + const execTime = Math.round(Number(process.hrtime.bigint() - start) / 1000) / 1000; + emitTrace(delivery, info, startIso, execTime, status, !error, + error ? String((error as Error).message ?? error) : undefined); + // an interceptor's own outcome is never auto-replied + return new EventEnvelope(); + } + + private replyInterceptorError(route: string, event: EventEnvelope, e: unknown): void { + let error: EventEnvelope; + if (e instanceof AppException) { + error = new EventEnvelope().setStatus(e.status).setBody(e.message); + } else { + const raw = e as Error; + error = new EventEnvelope().setStatus(500).setBody(raw.message ?? String(e)); + if (raw.stack) { + error.stack = raw.stack; + } + } + error.sender = route; + if (event.cid) { + error.setCorrelationId(event.cid); + } + const delivered = Boolean( + event.replyTo && this.router?.(error.setTo(event.replyTo))); + if (!delivered) { + log.warn(`Interceptor ${route} ended with status ` + + `${error.getStatus()} - ${error.body}`); + } + } } diff --git a/src/client.ts b/src/client.ts index 51b5dabc..aa2cf03f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,11 +11,25 @@ * 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 { asyncAck, DeliveryTimeout, raceMs } from './bus.js'; import { EventEnvelope } from './envelope.js'; +import { + DATA, + ENVELOPE, + EOF, + errorText, + EXCEPTION, + exceptionEnvelope, + SseParser, + STREAM_CALLER_REQUIRED, + streamSignal, + TEXT_EVENT_STREAM, + X_EVENT_NAME, + X_EVENT_STREAM +} from './event-stream.js'; import { AppException } from './exceptions.js'; import { defaultRegistry, FunctionRegistry } from './registry.js'; -import { getTrace } from './trace.js'; +import { getTrace, MY_CID_TAG, RPC_TAG } from './trace.js'; const W3C_TRACE_ID = /^[0-9a-f]{32}$/; const W3C_SPAN_ID = /^[0-9a-f]{16}$/; @@ -42,8 +56,39 @@ export class PostOffice { } const timeoutMs = options.timeoutMs ?? 30000; const event = this.buildEvent(route, body, options); - const trace = { traceId: event.traceId, tracePath: event.tracePath, cid: event.cid }; + if (!isAsync) { + // the engines' RPC round-trip marker: an RPC leg emits no trace + // dataset - its metrics fold into the caller's view + event.tags[RPC_TAG] ??= String(timeoutMs); + } + const trace = { + traceId: event.traceId, tracePath: event.tracePath, cid: event.cid, + envelope: event + }; const bus = this.registry.bus; + if (service.interceptor) { + if (isAsync) { + bus.publishEnvelope(service, event); + return asyncAck(); + } + // RPC to an interceptor: a per-request reply sink is the reply address; + // the first envelope classifies exactly like the engines - unmarked = + // the reply; marked = a streaming target refusing a single-shot caller + const [sinkRoute, queue] = bus.openSink(); + try { + bus.publishEnvelope(service, event.setReplyTo(sinkRoute)); + const first = await raceMs(queue.next(), Math.max(100, timeoutMs)); + if (!first) { + return new EventEnvelope().setStatus(408).setBody(`Timeout for ${timeoutMs} ms`); + } + if (streamSignal(first) !== undefined) { + return new EventEnvelope().setStatus(406).setBody(STREAM_CALLER_REQUIRED); + } + return first; + } finally { + bus.closeSink(sinkRoute); + } + } if (isAsync) { return bus.publish(service, event.headers, event.body, trace); } @@ -82,9 +127,24 @@ export class PostOffice { const event = new EventEnvelope(route, body, options.headers); if (options.fromRoute) event.setFrom(options.fromRoute); const info = getTrace(); + // fill the sender with the executing function's route (touch parity) + if (info?.route && !event.sender) { + event.setFrom(info.route); + } if (info?.traceId) event.setTrace(info.traceId, info.tracePath ?? route); const cid = options.cid ?? info?.cid; if (cid) event.setCorrelationId(cid); + // propagate the business correlation-id to the next touch point as the + // engine-managed my_cid tag (the engines' PostOffice.touch parity) - the + // receiving host injects it as the read-only my_correlation_id header + if (info?.myCorrelationId && !(MY_CID_TAG in event.tags)) { + event.tags[MY_CID_TAG] = info.myCorrelationId; + } + // carry this execution's span so the receiver stores it as its + // parent_span_id (touch parity) - also lights up the traceparent header + if (info?.spanId) { + event.setSpanId(info.spanId); + } return event; } @@ -97,6 +157,10 @@ export class PostOffice { } const timeoutMs = options.timeoutMs ?? 30000; const event = this.buildEvent(route, body, options); + if (!isAsync) { + // the engines' RPC round-trip marker (see callLocal) + event.tags[RPC_TAG] ??= String(timeoutMs); + } // +100 ms cushion so the HTTP client does not time out before the target const response = await fetch(url, { method: 'POST', @@ -122,4 +186,283 @@ export class PostOffice { async send(route: string, body?: unknown, options: CallOptions = {}): Promise { return this.call(route, body, options, true); } + + /** + * Consume a streaming function progressively - the same decoded envelopes + * an engine reply route receives: `data` segments, then the `eof` or + * `exception` terminal. A non-streaming target yields its one classic reply + * (opting in is always safe). `timeoutMs` is the idle allowance between + * segments; expiry, a truncated stream and a malformed dialect yield the + * in-band exception envelope, then end. + * + * Remote (an endpoint is given, or set on the constructor): the peer's + * /api/event answers the one POST with the envelope-mode SSE dialect. + * Local (no endpoint): the same first-envelope classification through a + * per-request reply sink on the primitive bus. + */ + async *stream(route: string, body?: unknown, + options: CallOptions = {}): AsyncGenerator { + const url = options.endpoint ?? this.endpoint; + const timeoutMs = options.timeoutMs ?? 30000; + const event = this.buildEvent(route, body, options); + if (!url) { + yield* this.streamLocal(route, event, timeoutMs); + return; + } + yield* this.streamRemote(url, event, timeoutMs); + } + + /** + * The relay form of stream() for composition: every decoded envelope + * forwards verbatim to the LOCAL replyTo route (typically the caller's own + * reply address, handed through by an interceptor), so segments flow + * remote peer -> this application -> the original caller with no + * buffering. Awaits and returns the last envelope (normally the terminal). + */ + async streamTo(route: string, body: unknown, replyTo: string, + options: CallOptions = {}): Promise { + let last = new EventEnvelope().setStatus(500).setBody('Stream produced no events'); + for await (const segment of this.stream(route, body, options)) { + last = segment; + const forward = EventEnvelope.fromMap(segment.toMap()).setTo(replyTo); + if (!this.registry.sendEvent(forward)) { + // the local consumer is gone - late segments are no-op drops + break; + } + } + return last; + } + + private async *streamLocal(route: string, event: EventEnvelope, + timeoutMs: number): AsyncGenerator { + const service = this.registry.get(route); + if (!service) { + yield new EventEnvelope().setStatus(404).setBody(`Route ${route} not found`); + return; + } + if (!service.interceptor) { + // a plain function cannot stream - its single reply is the stream + yield await this.callLocal(route, event.body, { + headers: event.headers, timeoutMs, fromRoute: event.sender, cid: event.cid + }, false); + return; + } + const bus = this.registry.bus; + const [sinkRoute, queue] = bus.openSink(); + try { + bus.publishEnvelope(service, event.setReplyTo(sinkRoute)); + const idleMs = Math.max(100, timeoutMs); + let streaming = false; + for (;;) { + // a lost race terminates the wait, so a fresh next() per cycle is safe + const reply = await raceMs(queue.next(), idleMs); + if (!reply) { + const seconds = Math.trunc(idleMs / 1000); + yield exceptionEnvelope(408, `Timeout for ${seconds} seconds`); + return; + } + const [out, done] = classifySinkReply(reply, streaming); + streaming = true; + yield out; + if (done) { + return; + } + } + } finally { + bus.closeSink(sinkRoute); + } + } + + private async *streamRemote(url: string, event: EventEnvelope, + timeoutMs: number): AsyncGenerator { + const effectiveCid = event.cid; + const headers = this.httpHeaders(timeoutMs, false, event); + headers['accept'] = TEXT_EVENT_STREAM; + // no total limit - a healthy stream may outlive any fixed total; the + // per-read race below is the idle allowance between segments + const idleMs = Math.max(1000, timeoutMs); + const response = await fetch(url, { + method: 'POST', + headers, + body: event.toBytes() + }); + const contentType = response.headers.get('content-type') ?? ''; + if (!contentType.startsWith(TEXT_EVENT_STREAM)) { + // the peer answered single-shot (a non-streaming target, or an edge + // error) - the classic reply, decoded tolerantly + const payload = new Uint8Array(await response.arrayBuffer()); + yield decodeSingleShot(payload, response.status); + return; + } + const body = response.body; + if (!body) { + yield relayGuard(500, 'Event stream ended without eof', effectiveCid); + return; + } + const reader = body.getReader(); + try { + yield* relayFrames(reader, idleMs, effectiveCid); + } catch (e) { + yield relayGuard(500, (e as Error).message ?? String(e), effectiveCid); + } finally { + await reader.cancel().catch(() => undefined); + } + } +} + +/** + * Pump the envelope-mode SSE frames of one response body: decoded envelopes + * out, ending at the terminal (frames after it are discarded); idle expiry + * and a transport end without a decoded terminal fail in-band. + */ +async function* relayFrames(reader: ReadableStreamDefaultReader, + idleMs: number, + cid: string | undefined): AsyncGenerator { + const parser = new SseParser(); + let headSeen = false; + for (;;) { + // a lost race terminates the stream, so a fresh read() per cycle is safe + const result = await raceMs(reader.read(), idleMs); + if (!result) { + const seconds = Math.trunc(idleMs / 1000); + yield relayGuard(408, `Timeout for ${seconds} seconds`, cid); + return; + } + if (result.done) { + // the dialect ends with a decoded terminal - a bare transport end is a + // truncation + yield relayGuard(500, 'Event stream ended without eof', cid); + return; + } + for (const [name, text] of parser.feed(result.value)) { + const [reply, terminal] = decodeFrame(name, text, headSeen, cid); + if (!reply) { + continue; + } + headSeen = true; + yield reply; + if (terminal) { + return; // frames after the terminal are discarded + } + } + } +} + +/** + * Classify one reply-sink envelope exactly like the engines: unmarked before + * any segment = the classic single-shot answer; unmarked mid-stream = the + * bus's error contract for an uncaught interceptor exception (fails + * in-band); marked = a stream segment, terminal on eof/exception. + */ +function classifySinkReply(reply: EventEnvelope, + streaming: boolean): [EventEnvelope, boolean] { + const marker = streamSignal(reply); + if (marker === undefined) { + if (streaming) { + return [exceptionEnvelope(reply.getStatus(), errorText(reply.body)), true]; + } + return [reply, true]; + } + return [reply, marker === EOF || marker === EXCEPTION]; +} + +/** An in-band exception envelope synthesized by the consuming relay. */ +function relayGuard(status: number, message: string, + cid: string | undefined): EventEnvelope { + const event = exceptionEnvelope(status, message); + if (cid) { + event.setCorrelationId(cid); + } + return event; +} + +/** + * Decode one SSE frame of the envelope-mode dialect: an "envelope" frame is + * one base64-encoded serialized envelope (the head, the terminals and + * non-text segments); any other frame is a raw text segment. Returns + * [envelope-or-null, terminal]. Dialect guards fail in-band: the first frame + * must be an envelope frame, and a malformed frame ends the stream. + */ +function decodeFrame(name: string | undefined, text: string, headSeen: boolean, + cid: string | undefined): [EventEnvelope | null, boolean] { + if (name === ENVELOPE) { + return decodeEnvelopeFrame(text, cid); + } + if (!headSeen) { + // the dialect guarantees an envelope frame first (conformance guard) + return [relayGuard(500, 'Invalid event stream - missing envelope head', cid), true]; + } + const segment = new EventEnvelope(undefined, text).setHeader(X_EVENT_STREAM, DATA); + if (name) { + segment.setHeader(X_EVENT_NAME, name); + } + if (cid) { + segment.setCorrelationId(cid); + } + return [segment, false]; +} + +/** + * One base64-encoded serialized envelope: the head, a terminal, or a + * non-text segment - addressing restored to the original caller; a + * malformed frame ends the stream in-band. + */ +function decodeEnvelopeFrame(text: string, + cid: string | undefined): [EventEnvelope, boolean] { + let decoded: EventEnvelope; + try { + decoded = EventEnvelope.fromBytes(Buffer.from(text, 'base64')); + } catch { + return [relayGuard(500, 'Invalid event stream - malformed envelope frame', cid), true]; + } + decoded.to = undefined; + decoded.replyTo = undefined; + if (cid) { + decoded.setCorrelationId(cid); + } + const marker = streamSignal(decoded); + return [decoded, marker === EOF || marker === EXCEPTION]; +} + +/** + * Decode a single-shot Event-over-HTTP reply: a serialized envelope + * normally, with the classic tolerant handling of an edge-level REST error + * body ('{"type": "error", "status": n, "message": text}' JSON) and of a + * payload that is not a serialized envelope at all. + */ +function decodeSingleShot(payload: Uint8Array, httpStatus: number): EventEnvelope { + if (!payload.length) { + return new EventEnvelope().setStatus(httpStatus); + } + try { + const reply = EventEnvelope.fromBytes(payload); + reply.replyTo = undefined; + return reply; + } catch (e) { + const restError = restErrorReply(payload, httpStatus); + return restError ?? new EventEnvelope().setStatus(400) + .setBody(`Invalid event-over-http response - ${(e as Error).message}`); + } +} + +/** + * An edge-level REST error arrives as JSON, not as a serialized envelope - + * unwrap it exactly as the classic relay does; null when it is not one. + */ +function restErrorReply(payload: Uint8Array, httpStatus: number): EventEnvelope | null { + if (httpStatus < 400) { + return null; + } + try { + const data: unknown = JSON.parse(Buffer.from(payload).toString('utf-8')); + if (data && typeof data === 'object' && !Array.isArray(data)) { + const record = data as Record; + if (record['type'] === 'error' && typeof record['message'] === 'string') { + return new EventEnvelope().setStatus(httpStatus).setBody(record['message']); + } + } + } catch { + // not a REST error body + } + return null; } diff --git a/src/config.ts b/src/config.ts index 8edce05f..81e21c1b 100644 --- a/src/config.ts +++ b/src/config.ts @@ -118,6 +118,15 @@ export class AppConfig { return value === undefined || value === null ? undefined : asText(value); } + /** + * Resolve ${ENV:default} substitution in a text value - the same rules as + * configuration values (used by companion config files such as + * app-log-context.yaml). + */ + resolveText(value: string): unknown { + return this.substitute(value, undefined); + } + exists(key: string): boolean { return this.overrides.has(key) || this.store.has(key); } diff --git a/src/default-log-context.yaml b/src/default-log-context.yaml new file mode 100644 index 00000000..bfbb79d4 --- /dev/null +++ b/src/default-log-context.yaml @@ -0,0 +1,19 @@ +# +# Built-in default application log context (the engines' default-log-context.yaml twin). +# +# The log-context feature is ON by default using this template. It applies to the +# structured JSON presentations (log.format=json or compact). +# +# To customize the context block, provide your own app-log-context.yaml in the +# application's resources folder (next to application.yml) - it replaces this +# default entirely. +# To turn the feature off, set app.log.context=false in the configuration. +# +context: + cid: $cid + traceId: $traceId + tracePath: $tracePath + spanId: $spanId + parentSpanId: $parentSpanId + service: $service + timestamp: $utc diff --git a/src/envelope.ts b/src/envelope.ts index b16c2056..053a4bf7 100644 --- a/src/envelope.ts +++ b/src/envelope.ts @@ -121,6 +121,11 @@ export class EventEnvelope { this.tracePath = tracePath; return this; } + + setSpanId(spanId: string): this { + this.spanId = spanId; + return this; + } setReplyTo(route?: string): this { this.replyTo = route; return this; } getStatus(): number { return this.status ?? 200; } diff --git a/src/event-stream.ts b/src/event-stream.ts new file mode 100644 index 00000000..3c49cb19 --- /dev/null +++ b/src/event-stream.ts @@ -0,0 +1,387 @@ +/** + * Event streaming: the multi-shot reply contract and the envelope-mode SSE dialect. + * + * The platform's native streaming pattern (all four runtimes): the caller provides + * a reply address; the callee streams events to it until a terminal signal. Each + * segment is one event to the caller's reply_to, marked with the reserved envelope + * header `x-event-stream: data | eof | exception`. On the Event-over-HTTP wire, the + * peer answers the one POST with a Server-Sent Events response in a hybrid dialect: + * envelope frames (the reserved SSE event name "envelope", one base64-encoded + * serialized envelope per frame) wherever envelope semantics matter - the head, the + * terminals and non-text segments - and raw SSE frames for plain text segments, so + * token relays stay near-zero overhead. + * + * EventStreamWriter is the producer helper - the engines' exact API: + * + * const out = EventStreamWriter.fromRequest(event); // an interceptor's envelope + * out.first(200, 'text/event-stream'); + * out.write('hello'); // data segment + * out.writeNamed('tokens', { n: 2 }); // named (typed) SSE event + * out.close({ usage }); // end of transmission + * // or out.fail(e); // in-band failure + * + * Writes after close/fail are dropped (debug log), mirroring the engines. An + * in-band failure body carries the standard error key-values + * '{"type": "error", "status": n, "message": text}'. + */ +import { appConfig } from './config.js'; +import { EventEnvelope } from './envelope.js'; +import { AppException } from './exceptions.js'; +import { getLogger } from './log.js'; +import { getTrace } from './trace.js'; +import { defaultRegistry, FunctionRegistry } from './registry.js'; + +/** reserved envelope header (internal protocol, never on the HTTP wire) */ +export const X_EVENT_STREAM = 'x-event-stream'; +/** optional companion on a data event: maps to the SSE "event:" field */ +export const X_EVENT_NAME = 'x-event-name'; +/** marker vocabulary - deliberately the engines' ObjectStream vocabulary */ +export const DATA = 'data'; +export const EOF = 'eof'; +export const EXCEPTION = 'exception'; +/** + * reserved SSE event name of the envelope-mode wire dialect: a frame with + * this name carries one base64-encoded serialized EventEnvelope + */ +export const ENVELOPE = 'envelope'; + +export const X_TTL = 'x-ttl'; +export const TEXT_EVENT_STREAM = 'text/event-stream'; +export const STREAM_CALLER_REQUIRED = + 'Streaming function requires a caller that accepts text/event-stream'; + +/** reserved envelope headers a raw SSE frame may carry without loss */ +const RESERVED_HEADERS = new Set([X_EVENT_STREAM, X_EVENT_NAME, X_TTL]); + +const log = getLogger('mercury.stream'); + +/** The x-event-stream marker (lowercased), or undefined for an unmarked envelope. */ +export function streamSignal(event: EventEnvelope): string | undefined { + for (const [key, value] of Object.entries(event.headers)) { + if (key.toLowerCase() === X_EVENT_STREAM) { + return value.toLowerCase(); + } + } + return undefined; +} + +/** The x-event-name companion header (the SSE "event:" field), if any. */ +export function streamEventName(event: EventEnvelope): string | undefined { + for (const [key, value] of Object.entries(event.headers)) { + if (key.toLowerCase() === X_EVENT_NAME) { + return value; + } + } + return undefined; +} + +/** The message text of an unmarked error reply (objects render as JSON). */ +export function errorText(body: unknown): string { + if (body === undefined || body === null) { + return 'Stream failed'; + } + return typeof body === 'string' ? body : JSON.stringify(body); +} + +/** The standard error key-values: '{"type": "error", "status": n, "message": text}' */ +export function errorBody(status: number, message: string): Record { + return { type: 'error', status, message }; +} + +/** An in-band exception envelope with the standard error body. */ +export function exceptionEnvelope(status: number, message: string): EventEnvelope { + return new EventEnvelope() + .setHeader(X_EVENT_STREAM, EXCEPTION) + .setStatus(status) + .setBody(errorBody(status, message)); +} + +/** One SSE frame: optional "event:" line, one "data:" line per text line. */ +export function sseFrame(eventName: string | undefined, text: string): Buffer { + const lines: string[] = []; + if (eventName) { + lines.push(`event: ${eventName}\n`); + } + for (const line of text.split('\n')) { + lines.push(`data: ${line}\n`); + } + lines.push('\n'); + return Buffer.from(lines.join(''), 'utf-8'); +} + +/** + * One envelope-mode wire frame: the envelope serialized verbatim - with the + * host-internal addressing cleared, because the consuming relay rewrites + * addressing to the original caller - as base64 under the reserved name. + */ +export function envelopeFrame(event: EventEnvelope): Buffer { + const clone = EventEnvelope.fromMap(event.toMap()); + clone.to = undefined; + clone.replyTo = undefined; + const encoded = Buffer.from(clone.toBytes()).toString('base64'); + return sseFrame(ENVELOPE, encoded); +} + +/** + * A data segment may ride a raw SSE frame only when the frame carries it + * losslessly: a 200 status, no custom envelope headers, a user event name + * clear of the reserved word, and a text (or empty) body without a carriage + * return - SSE normalizes line endings. Everything else takes the + * envelope-frame escape hatch. + */ +export function rawStreamable(event: EventEnvelope): boolean { + if (event.getStatus() !== 200) { + return false; + } + for (const [key, value] of Object.entries(event.headers)) { + const lowered = key.toLowerCase(); + if (!RESERVED_HEADERS.has(lowered)) { + return false; + } + if (lowered === X_EVENT_NAME && value === ENVELOPE) { + return false; + } + } + const body = event.body; + return body === undefined || body === null || + (typeof body === 'string' && !body.includes('\r')); +} + +/** + * One envelope-mode data frame: the first event always rides an envelope + * frame (it carries the head control); a losslessly raw-able text segment + * rides a raw frame; a bare no-op segment carries nothing. + */ +export function dataFrame(event: EventEnvelope, firstFrame: boolean): Buffer { + if (firstFrame || !rawStreamable(event)) { + return envelopeFrame(event); + } + if (event.body === undefined || event.body === null) { + return Buffer.alloc(0); + } + return sseFrame(streamEventName(event), event.body as string); +} + +/** + * SSE keep-alive comment interval in ms (`event.stream.keep.alive`, + * default 30s; 0 disables - the engines' config key). + */ +export function keepAliveMs(): number { + const raw = String(appConfig().getProperty('event.stream.keep.alive', '30s') ?? '30s') + .trim().toLowerCase(); + if (raw === '0' || raw === '0s' || raw === '0ms' || raw === '0m') { + return 0; + } + const parse = (text: string): number => Number.parseInt(text, 10); + let value: number; + if (raw.endsWith('ms')) { + value = parse(raw.slice(0, -2)); + } else if (raw.endsWith('s')) { + value = parse(raw.slice(0, -1)) * 1000; + } else if (raw.endsWith('m')) { + value = parse(raw.slice(0, -1)) * 60_000; + } else { + value = parse(raw) * 1000; + } + return Number.isFinite(value) ? value : 30_000; +} + +/** + * Incremental SSE frame parser: byte-level line split (a newline is a single + * byte, so this is UTF-8 safe), one-leading-space value strip, comment/id/ + * retry suppression, multi-line data joined per the SSE specification. + * Mirrors the engines' parsers. + */ +export class SseParser { + private pending: Buffer = Buffer.alloc(0); + private dataLines: string[] = []; + private eventName: string | undefined; + + /** Feed one body chunk; return the completed [event_name, data] events. */ + feed(chunk: Uint8Array): Array<[string | undefined, string]> { + const buffer = Buffer.concat([this.pending, Buffer.from(chunk)]); + const events: Array<[string | undefined, string]> = []; + let start = 0; + for (let i = 0; i < buffer.length; i++) { + if (buffer[i] !== 0x0a) { // '\n' + continue; + } + const end = i > start && buffer[i - 1] === 0x0d ? i - 1 : i; + this.onLine(buffer.subarray(start, end).toString('utf-8'), events); + start = i + 1; + } + this.pending = Buffer.from(buffer.subarray(start)); + return events; + } + + /** + * One SSE line: a blank line dispatches the pending event; a comment line + * (leading colon) is consumed, never forwarded; id, retry and unknown + * fields are ignored (SSE specification). + */ + private onLine(line: string, events: Array<[string | undefined, string]>): void { + if (!line) { + if (this.dataLines.length) { + events.push([this.eventName, this.dataLines.join('\n')]); + } + this.dataLines = []; + this.eventName = undefined; + return; + } + if (line.startsWith(':')) { + return; + } + const colon = line.indexOf(':'); + const field = colon === -1 ? line : line.slice(0, colon); + let value = colon === -1 ? '' : line.slice(colon + 1); + if (value.startsWith(' ')) { + value = value.slice(1); + } + if (field === 'data') { + this.dataLines.push(value); + } else if (field === 'event') { + this.eventName = value; + } + } +} + +/** + * Producer helper for a multi-shot reply - the engines' exact API. + * + * Only an interceptor function can stream: it receives the raw envelope, so + * the caller-provided reply address travels the engines' way + * (EventStreamWriter.fromRequest(event) reads reply_to and the correlation + * id). Segments route to the LOCAL reply address through the primitive event + * bus - simple routing to a local function or reply sink, never across the + * wire (cross-wire replies ride the Event-over-HTTP SSE response, exactly as + * on the engines). + */ +export class EventStreamWriter { + private readonly registry: FunctionRegistry; + private readonly replyTo: string; + private readonly cid: string | undefined; + private firstStatus = 200; + private firstContentType: string | undefined; + private firstTtlSeconds = 0; + private headSent = false; + private isClosed = false; + + constructor(replyTo: string | undefined, correlationId?: string, + registry: FunctionRegistry = defaultRegistry) { + if (!replyTo) { + throw new AppException(400, 'Streaming producer requires a reply_to address'); + } + this.registry = registry; + this.replyTo = replyTo; + this.cid = correlationId; + } + + /** + * Create a writer from the incoming request envelope (the usual form for + * an interceptor function). + */ + static fromRequest(event: EventEnvelope, + registry: FunctionRegistry = defaultRegistry): EventStreamWriter { + return new EventStreamWriter(event.replyTo, event.cid, registry); + } + + /** + * Optional head control carried by the first outgoing event: response + * status, content type, and an optional idle-allowance override in seconds + * between segments. + */ + first(status: number, contentType: string, ttlSeconds?: number): this { + this.firstStatus = Math.trunc(status); + this.firstContentType = contentType; + if (ttlSeconds !== undefined) { + this.firstTtlSeconds = Math.trunc(ttlSeconds); + } + return this; + } + + /** Send one `data` segment (text, bytes, object, array - any payload). */ + write(segment: unknown): void { + this.send(DATA, segment, undefined); + } + + /** Send one named segment - the name maps to the SSE "event:" field. */ + writeNamed(eventName: string, segment: unknown): void { + this.send(DATA, segment, eventName); + } + + /** Declare end of transmission, with optional trailing metadata. */ + close(trailingMetadata?: unknown): void { + if (this.isClosed) { + return; + } + this.isClosed = true; + this.emit(this.envelope(EOF, trailingMetadata, undefined)); + } + + /** Declare an in-band failure and end the stream. */ + fail(error: Error): void { + if (this.isClosed) { + return; + } + this.isClosed = true; + let status = error instanceof AppException ? error.status : 500; + status = status >= 400 ? status : 500; + const message = error.message || error.name; + const event = this.envelope(EXCEPTION, errorBody(status, message), undefined); + event.setStatus(status); + this.emit(event); + } + + /** True when the stream has been closed or failed. */ + get closed(): boolean { + return this.isClosed; + } + + private send(marker: string, body: unknown, eventName: string | undefined): void { + if (this.isClosed) { + log.debug(`Segment to ${this.replyTo} dropped - stream already closed`); + return; + } + this.emit(this.envelope(marker, body, eventName)); + } + + private envelope(marker: string, body: unknown, eventName: string | undefined): EventEnvelope { + const event = new EventEnvelope(this.replyTo, body).setHeader(X_EVENT_STREAM, marker); + if (this.cid) { + event.setCorrelationId(this.cid); + } + if (eventName) { + event.setHeader(X_EVENT_NAME, eventName); + } + if (!this.headSent) { + this.headSent = true; + event.setStatus(this.firstStatus); + if (this.firstContentType) { + event.setHeader('content-type', this.firstContentType); + } + if (this.firstTtlSeconds > 0) { + event.setHeader(X_TTL, String(this.firstTtlSeconds)); + } + } + // segments inherit the producer's identity, trace and span, so a + // consuming engine's per-segment delivery spans parent onto this + // function (the engines' po.send/touch parity) + const info = getTrace(); + if (info?.route) { + event.setFrom(info.route); + } + if (info?.traceId) { + event.setTrace(info.traceId, info.tracePath ?? this.replyTo); + if (info.spanId) { + event.setSpanId(info.spanId); + } + } + return event; + } + + private emit(event: EventEnvelope): void { + if (!this.registry.sendEvent(event)) { + log.warn(`Event dropped - route ${this.replyTo} not found`); + } + } +} diff --git a/src/index.ts b/src/index.ts index e4c30c83..2a2e7844 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,11 +13,23 @@ export { PostOffice } from './client.js'; export type { CallOptions } from './client.js'; export { AppConfig, appConfig, loadConfig } from './config.js'; export { EventEnvelope, isoUtc } from './envelope.js'; +export { + DATA, + ENVELOPE, + EOF, + EventStreamWriter, + EXCEPTION, + SseParser, + streamEventName, + streamSignal, + X_EVENT_NAME, + X_EVENT_STREAM +} from './event-stream.js'; export { AppException, CompactFormatError } from './exceptions.js'; export { getLogger, Logger } from './log.js'; export { defaultRegistry, FunctionRegistry, preload, validateRoute } from './registry.js'; export type { Handler, ServiceDef } from './registry.js'; export { EventApiServer, Platform, platform } from './server.js'; -export { annotateTrace, getTrace } from './trace.js'; +export { annotateTrace, getTrace, runWithTrace, updateContext } from './trace.js'; export type { TraceInfo } from './trace.js'; export { VERSION } from './version.js'; diff --git a/src/log-context.ts b/src/log-context.ts new file mode 100644 index 00000000..e6ac8371 --- /dev/null +++ b/src/log-context.ts @@ -0,0 +1,184 @@ +/** + * Application log context - the engines' app-log-context feature. + * + * When enabled (`app.log.context`, default true), the structured log + * presentations (log.format json/compact) add a `context` block to every log + * line written inside a traced request, so application logs and the + * distributed-trace telemetry stream correlate end to end in one aggregation. + * + * The context template mirrors the engines' contract exactly: + * - The built-in default template carries the standard trace context + * (cid, traceId, tracePath, spanId, parentSpanId, service, timestamp). + * - An application may replace it entirely with its own app-log-context.yaml + * in the resources folder (next to application.yml), mapping each output + * key to a reserved `$token` - resolved live per log line - or a constant + * (a literal, or `${ENV:default}` resolved once at load). + * - `app.log.context=false` opts out. + * - The `cid` token is the BUSINESS correlation-id only (the engine-managed + * my_cid tag); an internal routing id under the `cid` label would mislead + * log aggregation. + * - Developer-supplied key-values (updateContext) merge into the block; keys + * resolving to null are omitted, never "null". + */ +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parse } from 'yaml'; +import { appConfig } from './config.js'; +import { isoUtc } from './envelope.js'; +import { getLogger } from './log.js'; +import { RESERVED_CONTEXT_TOKENS, TraceInfo } from './trace.js'; + +const FEATURE_FLAG = 'app.log.context'; +const CONFIG_FILE = 'app-log-context.yaml'; +// the built-in default template ships as a packaged resource next to this +// module, exactly like the engines' classpath:/default-log-context.yaml +const DEFAULT_FILE = 'default-log-context.yaml'; + +/** The template's `context:` section, or undefined when absent/malformed. */ +function contextSection(data: unknown): Record | undefined { + const section = data && typeof data === 'object' + ? (data as Record).context : undefined; + if (typeof section === 'object' && section !== null && !Array.isArray(section)) { + return section as Record; + } + return undefined; +} + +/** The built-in default template from the packaged default-log-context.yaml. */ +function defaultTemplate(): Record | undefined { + const candidate = join(dirname(fileURLToPath(import.meta.url)), DEFAULT_FILE); + if (!existsSync(candidate)) { + return undefined; + } + return contextSection(parse(readFileSync(candidate, 'utf-8')) ?? {}); +} + +/** Resolve a reserved token to its live value (undefined when absent). */ +function tokenValue(info: TraceInfo, token: string): unknown { + switch (token) { + case 'cid': return info.myCorrelationId; + case 'traceId': return info.traceId; + case 'tracePath': return info.tracePath; + case 'spanId': return info.spanId; + case 'parentSpanId': return info.parentSpanId; + case 'service': return info.route; + case 'utc': return isoUtc(); + default: return undefined; + } +} + +/** Parsed context template: output key -> reserved token or constant. */ +export class LogContextConfig { + readonly enabled: boolean; + private readonly tokens: Record = {}; + private readonly constants: Record = {}; + + constructor(template: Record | undefined) { + for (const [outputKey, raw] of Object.entries(template ?? {})) { + this.parseEntry(outputKey, typeof raw === 'string' ? raw : String(raw)); + } + this.enabled = Object.keys(this.tokens).length > 0 + || Object.keys(this.constants).length > 0; + } + + /** + * One template entry: a reserved $token, or a constant (env-resolved value + * or literal; an unset ${VAR} with no default resolves to undefined and is + * dropped) - the engines' parseEntry. + */ + private parseEntry(outputKey: string, value: string): void { + if (value.startsWith('$') && !value.startsWith('${')) { + const token = value.slice(1); + if (!RESERVED_CONTEXT_TOKENS.has(token)) { + throw new Error(`Invalid log context token '${value}' for key ` + + `'${outputKey}' - allowed tokens: ` + + [...RESERVED_CONTEXT_TOKENS].sort((a, b) => a.localeCompare(b)).join(', ')); + } + this.tokens[outputKey] = token; + return; + } + const resolved = appConfig().resolveText(value); + if (resolved !== undefined && resolved !== null) { + this.constants[outputKey] = resolved; + } + } + + /** + * The context block for one log line: template tokens resolved live, + * constants, and the developer's custom key-values. Keys resolving to + * null/undefined are omitted. + */ + render(info: TraceInfo): Record { + const out: Record = {}; + for (const [outputKey, token] of Object.entries(this.tokens)) { + const value = tokenValue(info, token); + if (value !== undefined && value !== null) { + out[outputKey] = value; + } + } + Object.assign(out, this.constants); + for (const [key, value] of Object.entries(info.customContext ?? {})) { + if (value !== undefined && value !== null) { + out[key] = value; + } + } + return out; + } +} + +/** + * Resolve the active template; never logs itself - the caller emits the + * warning AFTER installing the config, so the log line (which renders through + * this feature) cannot re-enter. + */ +function load(): { config: LogContextConfig; warning?: string } { + const config = appConfig(); + if ((config.getProperty(FEATURE_FLAG, 'true') ?? 'true').toLowerCase() === 'false') { + return { config: new LogContextConfig(undefined) }; + } + // an application override replaces the default entirely - same resources + // convention as application.yml + const source = config.source; + const folder = source !== 'none' ? dirname(source) : 'resources'; + const candidate = join(folder || 'resources', CONFIG_FILE); + if (existsSync(candidate)) { + const section = contextSection(parse(readFileSync(candidate, 'utf-8')) ?? {}); + if (!section) { + // the engines log a warning and disable; mirror the outcome + return { + config: new LogContextConfig(undefined), + warning: `Log context config has no 'context' section - feature disabled (${candidate})` + }; + } + return { config: new LogContextConfig(section) }; + } + const template = defaultTemplate(); + if (!template) { + return { + config: new LogContextConfig(undefined), + warning: `Built-in ${DEFAULT_FILE} missing - log context feature disabled` + }; + } + return { config: new LogContextConfig(template) }; +} + +let instance: LogContextConfig | undefined; + +/** The shared context template (loaded on first structured log line). */ +export function logContextConfig(): LogContextConfig { + if (!instance) { + const { config, warning } = load(); + instance = config; + if (warning) { + // safe: the instance is installed first, so this line cannot re-enter + getLogger('mercury.log').warn(warning); + } + } + return instance; +} + +/** Test seam: reset so the next structured log line reloads the template. */ +export function resetLogContextForTest(): void { + instance = undefined; +} diff --git a/src/log.ts b/src/log.ts index ba97ae4f..3942f985 100644 --- a/src/log.ts +++ b/src/log.ts @@ -8,11 +8,13 @@ * Level comes from the LOG_LEVEL environment variable when set (mirroring the * 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). + * (pretty-printed) and compact (the same object on a single line - JSONL - + * for log aggregators). Inside a traced request, the JSON presentations add + * the application log "context" block (the engines' app-log-context feature - + * see log-context.ts). */ import { appConfig } from './config.js'; +import { logContextConfig } from './log-context.js'; import { getTrace } from './trace.js'; const LEVELS = ['DEBUG', 'INFO', 'WARN', 'ERROR'] as const; @@ -56,12 +58,25 @@ function callSite(): string { return `${name}:${line}`; } -function write(level: Level, name: string | undefined, message: string, args: unknown[]): void { +type LogMessage = string | Record; + +function renderMessage(message: LogMessage, args: unknown[]): LogMessage { + // a structured (object) message stays structural in the JSON presentations + // and renders as compact JSON in text mode - used by the distributed-trace + // dataset records, which stdout log-ingest agents parse + if (typeof message === 'object' && message !== null && !args.length) { + return message; + } + const head = typeof message === 'string' ? message : JSON.stringify(message); + return args.length + ? `${head} ${args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')}` + : head; +} + +function write(level: Level, name: string | undefined, message: LogMessage, args: unknown[]): void { setup(); if (LEVELS.indexOf(level) < minLevel) return; - const rendered = args.length - ? `${message} ${args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')}` - : message; + const rendered = renderMessage(message, args); const logger = name ?? callSite(); if (logFormat === 'json' || logFormat === 'compact') { const entry: Record = { @@ -70,22 +85,31 @@ function write(level: Level, name: string | undefined, message: string, args: un logger, message: rendered }; + // the application log context (the engines' app-log-context feature): + // a "context" block on every structured line inside a traced request, + // correlating app logs with the distributed-trace telemetry stream const info = getTrace(); - if (info?.traceId) entry.trace_id = info.traceId; + if (info?.traceId) { + const contextConfig = logContextConfig(); + if (contextConfig.enabled) { + entry.context = contextConfig.render(info); + } + } // 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`); + const text = typeof rendered === 'string' ? rendered : JSON.stringify(rendered); + process.stdout.write(`${timestamp()} ${level.padEnd(5)} ${logger} - ${text}\n`); } } export class Logger { constructor(private readonly name?: string) {} - debug(message: string, ...args: unknown[]): void { write('DEBUG', this.name, message, args); } - info(message: string, ...args: unknown[]): void { write('INFO', this.name, message, args); } - warn(message: string, ...args: unknown[]): void { write('WARN', this.name, message, args); } - error(message: string, ...args: unknown[]): void { write('ERROR', this.name, message, args); } + debug(message: LogMessage, ...args: unknown[]): void { write('DEBUG', this.name, message, args); } + info(message: LogMessage, ...args: unknown[]): void { write('INFO', this.name, message, args); } + warn(message: LogMessage, ...args: unknown[]): void { write('WARN', this.name, message, args); } + error(message: LogMessage, ...args: unknown[]): void { write('ERROR', this.name, message, args); } } /** A logger writing engine-consistent log lines. */ diff --git a/src/registry.ts b/src/registry.ts index 473bfccd..78971829 100644 --- a/src/registry.ts +++ b/src/registry.ts @@ -6,12 +6,20 @@ * full control of status and reply headers). */ import { EventBus } from './bus.js'; +import type { EventEnvelope } from './envelope.js'; /** * A function handler returns the reply body, an EventEnvelope for full * control of status and reply headers, or a promise of either - the bus * awaits the result and discriminates with instanceof, so the honest * static type is simply unknown. + * + * An INTERCEPTOR handler (the engines' EventInterceptor contract) receives + * the raw EventEnvelope as its second argument - reply_to and the + * correlation id travel the engines' way - replies manually via reply_to, + * and its return value is discarded. Streaming producers and relay + * functions are interceptors. The runtime discriminates by the service's + * interceptor flag, so one structural type covers both flavors. */ export type Handler = ( headers: Record, @@ -23,6 +31,7 @@ export interface ServiceDef { handler: Handler; instances: number; isPrivate: boolean; + interceptor: boolean; } const ROUTE_PATTERN = /^[a-z0-9][a-z0-9._-]*$/; @@ -44,19 +53,49 @@ export class FunctionRegistry { private readonly services = new Map(); + constructor() { + // reply routing for the bus's interceptor error contract + this.bus.bindRouter((event) => this.sendEvent(event)); + } + register(route: string, handler: Handler, - options: { instances?: number; isPrivate?: boolean } = {}): ServiceDef { + options: { instances?: number; isPrivate?: boolean; + interceptor?: boolean } = {}): ServiceDef { const validated = validateRoute(route); const service: ServiceDef = { route: validated, handler, instances: Math.max(1, Math.trunc(options.instances ?? 10)), - isPrivate: options.isPrivate ?? false + isPrivate: options.isPrivate ?? false, + interceptor: options.interceptor ?? false }; this.services.set(validated, service); return service; } + /** + * The reply_to mechanism: deliver one envelope to a LOCAL reply sink or + * registered function, drop-n-forget (simple routing, never across the + * wire - cross-wire replies ride the Event-over-HTTP SSE response). + * Returns false when the target no longer exists, so a late segment is a + * no-op drop, the engines' semantics. + */ + sendEvent(event: EventEnvelope): boolean { + const route = event.to; + if (!route) { + return false; + } + if (this.bus.offerSink(route, event)) { + return true; + } + const service = this.services.get(route); + if (!service) { + return false; + } + this.bus.publishEnvelope(service, event); + return true; + } + get(route: string): ServiceDef | undefined { return this.services.get(route); } @@ -79,7 +118,8 @@ export const defaultRegistry = new FunctionRegistry(); * preload('hello.node', { instances: 10 }, async (headers, body) => ({ ok: true })); */ export function preload(route: string, - options: { instances?: number; isPrivate?: boolean }, + options: { instances?: number; isPrivate?: boolean; + interceptor?: boolean }, handler: Handler): void { defaultRegistry.register(route, handler, options); } diff --git a/src/server.ts b/src/server.ts index 07854c1c..08c9b9a7 100644 --- a/src/server.ts +++ b/src/server.ts @@ -16,14 +16,31 @@ */ import * as http from 'node:http'; import { Actuator, sendError } from './actuator.js'; -import { DeliveryTimeout } from './bus.js'; +import { DeliveryTimeout, Mailbox, raceMs } from './bus.js'; import { appConfig } from './config.js'; import { EventEnvelope } from './envelope.js'; +import { + DATA, + dataFrame, + envelopeFrame, + EOF, + errorText, + EXCEPTION, + exceptionEnvelope, + keepAliveMs, + STREAM_CALLER_REQUIRED, + streamSignal, + TEXT_EVENT_STREAM, + X_TTL +} from './event-stream.js'; import { CompactFormatError } from './exceptions.js'; import { getLogger } from './log.js'; -import { defaultRegistry, FunctionRegistry } from './registry.js'; +import { defaultRegistry, FunctionRegistry, ServiceDef } from './registry.js'; +import { MY_CID_TAG, MY_CORRELATION_ID } from './trace.js'; const OCTET_STREAM = 'application/octet-stream'; +// the engines' reserved route name for the Event-over-HTTP ingress +const EVENT_API_SERVICE = 'event.api.service'; const log = getLogger('mercury.server'); function transportError(res: http.ServerResponse, status: number, message: string): void { @@ -41,9 +58,9 @@ function handlerHeaders(event: EventEnvelope): Record { headers[k] = v; } } - const myCid = event.tags['my_cid']; + const myCid = event.tags[MY_CID_TAG]; if (myCid) { - headers['my_correlation_id'] = myCid; + headers[MY_CORRELATION_ID] = myCid; } return headers; } @@ -84,9 +101,17 @@ export class EventApiServer { transportError(res, 403, `${event.to} is private`); return; } + if (!event.sender) { + // the engines' EventApiService parity: its PostOffice fills the sender + // with its own route when the wire envelope carries none + event.setFrom(EVENT_API_SERVICE); + } const headers = handlerHeaders(event); const bus = this.registry.bus; - const trace = { traceId: event.traceId, tracePath: event.tracePath, cid: event.cid }; + const trace = { + traceId: event.traceId, tracePath: event.tracePath, cid: event.cid, + envelope: event + }; if (isAsync) { const ack = bus.publish(service, headers, event.body, trace); const bytes = ack.toBytes(); @@ -94,6 +119,14 @@ export class EventApiServer { res.end(bytes); return; } + if (service.interceptor) { + // interceptor dispatch (the reply_to mechanism): the handler receives + // the raw envelope with a per-request reply sink as its reply address + // and answers manually - single-shot or streaming + const capable = String(req.headers['accept'] ?? '').includes(TEXT_EVENT_STREAM); + await this.dispatchInterceptor(res, service, event, headers, ttl, capable); + return; + } try { const reply = await bus.deliver(service, headers, event.body, ttl, trace); log.info(`Handled ${event.to} status=${reply.getStatus()} ` + @@ -111,6 +144,68 @@ export class EventApiServer { } } + /** + * Dispatch to an interceptor and classify its first reply exactly like the + * engines: unmarked = the classic single-shot response, byte-identical; + * marked = the envelope-mode SSE dialect for a caller that accepts + * text/event-stream, or the pinned 406 refusal for one that does not. + */ + private async dispatchInterceptor(res: http.ServerResponse, service: ServiceDef, + event: EventEnvelope, headers: Record, + ttl: number, capable: boolean): Promise { + const bus = this.registry.bus; + const [sinkRoute, queue] = bus.openSink(); + try { + const handlerEvent = new EventEnvelope(event.to, event.body, headers); + handlerEvent.setReplyTo(sinkRoute); + if (Object.keys(event.tags).length) { + // engine-managed tags (e.g. the business correlation-id) ride the + // delivered envelope verbatim, the engines' way + handlerEvent.tags = { ...event.tags }; + } + if (event.cid) { + handlerEvent.setCorrelationId(event.cid); + } + if (event.traceId) { + handlerEvent.setTrace(event.traceId, event.tracePath ?? service.route); + } + if (event.spanId) { + // the caller's span - the handler's span parents onto it + handlerEvent.setSpanId(event.spanId); + } + if (event.sender) { + handlerEvent.setFrom(event.sender); + } + bus.publishEnvelope(service, handlerEvent); + const first = await raceMs(queue.next(), Math.max(100, ttl)); + if (!first) { + log.warn(`Event ${event.to} timeout for ${ttl} ms ` + + `(trace_id=${event.traceId ?? 'none'})`); + transportError(res, 408, `Timeout for ${ttl} ms`); + return; + } + const marker = streamSignal(first); + if (marker === undefined) { + // the classic single-shot reply (a manual answer, or the bus's error + // contract for an uncaught interceptor exception) + log.info(`Handled ${event.to} status=${first.getStatus()} ` + + `exec_time=${first.execTime ?? 0}ms trace_id=${event.traceId ?? 'none'}`); + const bytes = first.toBytes(); + res.writeHead(200, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); + res.end(bytes); + return; + } + if (!capable) { + // a streaming reply cannot ride a single-shot response + transportError(res, 406, STREAM_CALLER_REQUIRED); + return; + } + await streamResponse(res, queue, first, marker, ttl); + } finally { + bus.closeSink(sinkRoute); + } + } + createServer(): http.Server { return http.createServer((req, res) => { const url = new URL(req.url ?? '/', 'http://localhost'); @@ -140,6 +235,117 @@ export class EventApiServer { } } +/** + * Render the envelope-mode SSE dialect: envelope frames for the head, the + * terminals and non-text segments; raw frames for plain text. The x-ttl + * allowance (overridable by the producer's head control, in seconds) is the + * per-segment idle; expiry fails the stream in-band with the standard 408 + * error body. Keep-alive comments ride while the producer is quiet + * (event.stream.keep.alive, the engines' key). + */ +async function streamResponse(res: http.ServerResponse, queue: Mailbox, + first: EventEnvelope, firstMarker: string, + ttl: number): Promise { + let idleMs = ttl; + for (const [key, value] of Object.entries(first.headers)) { + if (key.toLowerCase() === X_TTL) { + const seconds = Number.parseInt(String(value).trim(), 10); + if (Number.isFinite(seconds) && seconds > 0) { + idleMs = seconds * 1000; + } + } + } + res.writeHead(first.getStatus(), { + 'content-type': TEXT_EVENT_STREAM, + 'cache-control': 'no-cache' + }); + res.write(envelopeFrame(first)); + if (firstMarker === DATA) { + await streamSegments(res, queue, idleMs); + } + res.end(); +} + +async function streamSegments(res: http.ServerResponse, queue: Mailbox, + idleMs: number): Promise { + const pingMs = keepAliveMs(); + // a disconnected client ends the stream; late segments are no-op drops + for (;;) { + if (res.writableEnded || res.destroyed) { + log.debug('Client disconnected from event stream'); + return; + } + const event = await nextSegment(res, queue, idleMs, pingMs); + if (!event) { + // idle expiry - fail in-band (the engines' housekeeper parity) + const seconds = Math.trunc(idleMs / 1000); + res.write(envelopeFrame(exceptionEnvelope(408, `Timeout for ${seconds} seconds`))); + return; + } + const action = classifySegment(event); + if (action.warn) { + log.warn('Dropping event - invalid x-event-stream signal'); + } + if (action.frame?.length) { + res.write(action.frame); + } + if (action.end) { + return; + } + } +} + +/** + * The wire consequence of one sink envelope in envelope mode: a data frame + * (raw or escape-hatch), a terminal envelope frame that ends the response + * cleanly (no cosmetic frames on this wire), the in-band terminal for the + * bus's uncaught-interceptor-exception contract, or a warned drop. + */ +function classifySegment(event: EventEnvelope): { frame?: Buffer; end: boolean; warn?: boolean } { + const marker = streamSignal(event); + if (marker === DATA) { + return { frame: dataFrame(event, false), end: false }; + } + if (marker === EOF || marker === EXCEPTION) { + return { frame: envelopeFrame(event), end: true }; + } + if (marker === undefined && event.hasError()) { + // fail in-band with the exact status + const frame = envelopeFrame(exceptionEnvelope(event.getStatus(), errorText(event.body))); + return { frame, end: true }; + } + return { end: false, warn: true }; +} + +/** + * Wait for the next segment within the idle allowance, emitting SSE + * keep-alive comments while the producer is quiet (best-effort; pings never + * extend the idle allowance). + */ +async function nextSegment(res: http.ServerResponse, queue: Mailbox, + idleMs: number, pingMs: number): Promise { + const deadline = Date.now() + idleMs; + // ONE pending waiter reused across ping cycles (see raceMs) + const pending = queue.next(); + for (;;) { + const remaining = deadline - Date.now(); + if (remaining <= 0) { + return null; + } + const wait = pingMs > 0 ? Math.min(remaining, pingMs) : remaining; + const event = await raceMs(pending, wait); + if (event) { + return event; + } + if (Date.now() >= deadline) { + return null; + } + if (!res.writableEnded && !res.destroyed) { + res.write(': ping\n\n'); + } + } +} + export class Platform { constructor(readonly registry: FunctionRegistry = defaultRegistry) {} diff --git a/src/trace.ts b/src/trace.ts index ab8ce02b..7c6ae688 100644 --- a/src/trace.ts +++ b/src/trace.ts @@ -7,11 +7,41 @@ */ import { AsyncLocalStorage } from 'node:async_hooks'; +// The business correlation-id rides an engine-managed envelope tag - never an +// envelope header - and is injected into the receiving function's input header +// copy as a read-only view at delivery (the engines' WorkerHandler contract). +export const MY_CID_TAG = 'my_cid'; +export const MY_CORRELATION_ID = 'my_correlation_id'; +// The engines' RPC round-trip marker tag: an RPC leg emits no trace dataset +// (its metrics fold into the caller's view), so the client stamps it on +// request() calls and the bus honors it at delivery. +export const RPC_TAG = 'rpc'; +// Reserved application log-context tokens (the engines' LogContext contract): +// resolved live per log line; a developer cannot override them via +// updateContext. The output key names in app-log-context.yaml are the +// operator's choice - this set governs the template tokens and developer API. +export const RESERVED_CONTEXT_TOKENS = new Set( + ['cid', 'traceId', 'tracePath', 'spanId', 'parentSpanId', 'service', 'utc']); + export interface TraceInfo { + // the executing function's route - outbound calls fill their sender ("from") + // with it, the engines' PostOffice.touch parity + route?: string; traceId?: string; tracePath?: string; cid?: string; + myCorrelationId?: string; + // span lineage (the engines' model): spanId is THIS execution's span, + // stamped onto outbound events so the receiver stores it as its + // parentSpanId; parentSpanId is the caller's span from the inbound + // envelope. 16-hex (W3C-shaped). + spanId?: string; + parentSpanId?: string; annotations: Record; + // developer-supplied application log-context key-values (updateContext) - + // a logging-only sink, rendered into the "context" block of structured log + // lines; distinct from annotations, which feed the trace telemetry + customContext?: Record; } const storage = new AsyncLocalStorage(); @@ -29,7 +59,42 @@ export function annotateTrace(key: string, value: unknown): void { } } -/** internal - run fn under a trace context */ -export function runWithTrace(info: TraceInfo, fn: () => T): T { - return storage.run(info, fn); +/** + * Add (or remove, when value is null/undefined) a custom key-value in the + * application log context - the engines' PostOffice.updateContext twin. + * + * The key-value is rendered into the "context" block of structured log output + * (log.format json/compact) when the app-log-context feature is enabled. + * Unlike annotateTrace (which feeds the distributed-trace telemetry), this is + * a logging-only sink. No-op outside a hosted request. + * + * @throws Error if key is one of the reserved context tokens + */ +export function updateContext(key: string, value: unknown): void { + if (RESERVED_CONTEXT_TOKENS.has(key)) { + throw new Error(`Cannot override reserved log context key '${key}' - ` + + `reserved keys are ${[...RESERVED_CONTEXT_TOKENS].sort((a, b) => a.localeCompare(b)).join(', ')}`); + } + const info = storage.getStore(); + if (!info) { + return; + } + info.customContext ??= {}; + if (value === null || value === undefined) { + delete info.customContext[key]; + } else { + info.customContext[key] = value; + } +} + +/** + * Run fn under a trace context - the python trace_context twin. Useful for + * callers outside a hosted function (batch jobs, tests) whose PostOffice + * calls should carry a trace: the client inherits the context into the + * outbound envelope, including the business correlation-id as the + * engine-managed my_cid tag. + */ +export function runWithTrace(info: TraceInfo | undefined, fn: () => T): T { + // undefined detaches: long-lived internal tasks run with a clean context + return storage.run(info as TraceInfo, fn); } diff --git a/src/version.ts b/src/version.ts index 2b096a62..1aa6398e 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ /** Package version - the single TS-side source (package.json mirrors it). */ -export const VERSION = '0.1.0'; +export const VERSION = '4.12.0'; diff --git a/test/event-stream.test.ts b/test/event-stream.test.ts new file mode 100644 index 00000000..63902c3e --- /dev/null +++ b/test/event-stream.test.ts @@ -0,0 +1,482 @@ +/** + * Event streaming tests: the multi-shot reply contract and the envelope-mode + * SSE dialect over real HTTP - the wrapper half of the engines' Phase 2/3 + * matrix (Java EventOverHttpStreamTest / python test_event_stream twins). + */ +import assert from 'node:assert/strict'; +import type * as http from 'node:http'; +import { after, before, test } from 'node:test'; +import { PostOffice } from '../src/client.js'; +import { EventEnvelope } from '../src/envelope.js'; +import { + EventStreamWriter, + streamEventName, + streamSignal +} from '../src/event-stream.js'; +import { AppException } from '../src/exceptions.js'; +import { FunctionRegistry } from '../src/registry.js'; +import { EventApiServer } from '../src/server.js'; +import { getTrace, runWithTrace } from '../src/trace.js'; + +const SSE = 'text/event-stream'; +const OCTET = 'application/octet-stream'; +const REFUSAL = 'Streaming function requires a caller that accepts text/event-stream'; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms).unref()); + +// the relay fixture learns its own host URL after the server binds +const relayTarget: { url?: string } = {}; + +function buildRegistry(): FunctionRegistry { + const registry = new FunctionRegistry(); + + registry.register('unit.tokens', async (headers, rawEvent) => { + const event = rawEvent as EventEnvelope; + const out = EventStreamWriter.fromRequest(event, registry); + const mode = headers['mode'] ?? 'tokens'; + if (mode === 'tokens') { + out.first(200, SSE); + out.write('alpha'); + await sleep(250); + out.write('beta'); + await sleep(250); + out.close({ segments: 2 }); + } else if (mode === 'typed') { + // every escape-hatch trigger: an object body, text with a carriage + // return, a user event name colliding with the reserved word, a binary + // body - plus one plain token that rides a raw frame + out.first(200, SSE); + out.write({ n: 1 }); + out.writeNamed('crlf', 'line1\r\nline2'); + out.writeNamed('envelope', 'reserved-name'); + out.write(new Uint8Array([1, 2, 3, 4])); + out.write('plain token'); + out.close({ done: true }); + } else if (mode === 'error-mid') { + out.first(200, SSE); + out.write('partial'); + out.fail(new AppException(503, 'backend on fire')); + } else if (mode === 'error-first') { + out.fail(new AppException(503, 'no backend')); + } else if (mode === 'stall') { + // one-second declared idle allowance, then silence - the host must + // fail the stream in-band + out.first(200, SSE, 1); + out.write('one'); + } else if (mode === 'crash-before') { + throw new Error('kaboom before head'); + } else if (mode === 'crash-mid') { + out.first(200, SSE); + out.write('early'); + throw new Error('kaboom mid-stream'); + } else if (mode === 'manual') { + // a single-shot manual answer from an interceptor + const reply = new EventEnvelope(event.replyTo, { manual: true }); + if (event.cid) { + reply.setCorrelationId(event.cid); + } + registry.sendEvent(reply); + } else if (mode === 'biz') { + // echo the injected business correlation-id view and the span lineage + // of this execution (continuity proof) + const info = getTrace(); + out.first(200, SSE); + out.close({ + my_correlation_id: headers['my_correlation_id'] ?? null, + span_id: info?.spanId ?? null, + parent_span_id: info?.parentSpanId ?? null + }); + } + }, { interceptor: true }); + + registry.register('unit.relay', async (_headers, rawEvent) => { + // the composition: forward MY caller's reply address into a call against + // a remote streaming function - segments flow through verbatim + const event = rawEvent as EventEnvelope; + const po = new PostOffice(undefined, {}, registry); + await po.streamTo('unit.tokens', undefined, event.replyTo ?? '', { + endpoint: relayTarget.url, timeoutMs: 10000, cid: event.cid + }); + }, { interceptor: true }); + + registry.register('unit.echo', async (_headers, body) => ({ echo: body ?? null })); + registry.register('unit.biz', async (headers) => + ({ my_correlation_id: headers['my_correlation_id'] ?? null })); + return registry; +} + +let registry: FunctionRegistry; +let server: http.Server; +let url: string; + +before(async () => { + registry = buildRegistry(); + server = new EventApiServer(registry).createServer(); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address() as { port: number }; + url = `http://127.0.0.1:${address.port}/api/event`; + relayTarget.url = url; +}); + +after(() => { + registry.bus.close(); + return new Promise((resolve) => server.close(() => resolve())); +}); + +async function collect(po: PostOffice, route: string, target: string | undefined, + mode?: string, timeoutMs = 10000, + cid = 'cid-100'): Promise { + const events: EventEnvelope[] = []; + const headers = mode ? { mode } : undefined; + for await (const event of po.stream(route, undefined, + { headers, timeoutMs, endpoint: target, cid })) { + events.push(event); + } + return events; +} + +// ---- the host produces the envelope-mode dialect ---- + +test('streaming target relays progressively to the consumer', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url); + assert.equal(events.length, 3, '2 data envelopes + eof'); + const head = events[0]; + assert.equal(streamSignal(head), 'data'); + assert.equal(head.getStatus(), 200); + assert.equal(head.headers['content-type'], SSE); + assert.equal(head.body, 'alpha'); + assert.equal(head.cid, 'cid-100', 'original correlation id restored'); + assert.equal(events[1].body, 'beta'); + const eof = events[2]; + assert.equal(streamSignal(eof), 'eof'); + assert.deepEqual(eof.body, { segments: 2 }); +}); + +test('the wire is the hybrid dialect', async () => { + // raw wire pin: the head and the terminal ride envelope frames; the plain + // text token rides a raw frame + const event = new EventEnvelope('unit.tokens').setHeader('mode', 'tokens'); + const response = await fetch(url, { + method: 'POST', + headers: { 'content-type': OCTET, 'x-ttl': '10000', 'accept': SSE }, + body: event.toBytes() + }); + assert.equal(response.status, 200); + assert.ok((response.headers.get('content-type') ?? '').startsWith(SSE)); + assert.equal(response.headers.get('cache-control'), 'no-cache'); + const text = await response.text(); + const frames = text.split('\n\n').filter((f) => f.trim()); + assert.ok(frames[0].startsWith('event: envelope\n'), 'head control rides an envelope frame'); + assert.ok(frames.includes('data: beta'), 'a plain token rides a raw frame'); + assert.ok(frames[frames.length - 1].startsWith('event: envelope\n'), + 'the terminal is an envelope frame'); + // the terminal decodes to the eof envelope with its exact metadata + const encoded = frames[frames.length - 1].split('data: ', 2)[1]; + const terminal = EventEnvelope.fromBytes(Buffer.from(encoded, 'base64')); + assert.equal(streamSignal(terminal), 'eof'); + assert.deepEqual(terminal.body, { segments: 2 }); + // host-internal addressing never leaks to the wire + assert.equal(terminal.to, undefined); + assert.equal(terminal.replyTo, undefined); +}); + +test('typed segments round-trip exactly', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'typed'); + assert.equal(events.length, 6, '5 data envelopes + eof'); + assert.deepEqual(events[0].body, { n: 1 }); + const crlf = events[1]; + assert.equal(streamEventName(crlf), 'crlf'); + assert.equal(crlf.body, 'line1\r\nline2', 'carriage return preserved'); + const reserved = events[2]; + assert.equal(streamEventName(reserved), 'envelope', + 'a user event name colliding with the reserved word survives'); + assert.equal(reserved.body, 'reserved-name'); + assert.deepEqual(new Uint8Array(events[3].body as Uint8Array), + new Uint8Array([1, 2, 3, 4]), 'binary body preserved'); + assert.equal(events[4].body, 'plain token'); + const eof = events[5]; + assert.equal(streamSignal(eof), 'eof'); + assert.deepEqual(eof.body, { done: true }); +}); + +test('single-shot over the capable path is classic', async () => { + const po = new PostOffice(); + // an interceptor's manual single-shot answer + let events = await collect(po, 'unit.tokens', url, 'manual'); + assert.equal(events.length, 1); + assert.equal(streamSignal(events[0]), undefined); + assert.deepEqual(events[0].body, { manual: true }); + assert.equal(events[0].cid, 'cid-100'); + // a plain (non-interceptor) function - opting in is always safe + events = await collect(po, 'unit.echo', url); + assert.equal(events.length, 1); + assert.deepEqual(events[0].body, { echo: null }); +}); + +test('the business cid rides the streaming hop', async () => { + // the caller's business correlation-id (the my_cid tag) crosses the HTTP + // hop and is injected as the my_correlation_id header view at delivery + const po = new PostOffice(); + const events = await runWithTrace( + { traceId: 'biz-trace-1', tracePath: 'TEST /stream', myCorrelationId: 'biz-42', annotations: {} }, + () => collect(po, 'unit.tokens', url, 'biz')); + assert.equal(streamSignal(events[events.length - 1]), 'eof'); + const body = events[events.length - 1].body as Record; + assert.equal(body.my_correlation_id, 'biz-42'); +}); + +test('span lineage continues across the hop', async () => { + // the engines' span model: the caller's span rides the outbound envelope; + // the receiving execution mints its own span with the caller's as parent + const callerSpan = 'ab'.repeat(8); + const po = new PostOffice(); + const events = await runWithTrace( + { traceId: '4bf92f3577b34da6a3ce929d0e0e4746', tracePath: 'TEST /lineage', + spanId: callerSpan, annotations: {} }, + () => collect(po, 'unit.tokens', url, 'biz')); + const body = events[events.length - 1].body as Record; + assert.equal(body.parent_span_id, callerSpan); + assert.notEqual(body.span_id, callerSpan); + assert.match(String(body.span_id), /^[0-9a-f]{16}$/, '16-hex W3C-shaped span'); +}); + +test('trace datasets are emitted with the engine shape', async () => { + // non-RPC executions emit the engines' distributed-trace dataset record; + // RPC round-trips are suppressed (their metrics fold into the caller) + const callerSpan = 'cd'.repeat(8); + const lines: string[] = []; + const original = process.stdout.write.bind(process.stdout); + // tee, never swallow: the test runner's own completion records ride this + // stream too - eating them silently drops tests from the run report + process.stdout.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => { + lines.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8')); + return (original as (...a: unknown[]) => boolean)(chunk, ...rest); + }) as typeof process.stdout.write; + try { + const po = new PostOffice(); + await runWithTrace( + { traceId: '4bf92f3577b34da6a3ce929d0e0e4747', tracePath: 'TEST /telemetry', + spanId: callerSpan, annotations: {} }, + async () => { + await collect(po, 'unit.tokens', url, 'biz'); + const rpc = await new PostOffice(undefined, {}, registry) + .request('unit.biz', undefined, { timeoutMs: 5000 }); + assert.equal(rpc.getStatus(), 200); + }); + } finally { + process.stdout.write = original; + } + // text mode renders a dataset as '... distributed.tracing - {json}' + const datasets = lines + .filter((line) => line.includes('distributed.tracing')) + .map((line) => JSON.parse(line.slice(line.indexOf(' - ') + 3)) as + { trace: Record; annotations?: Record }); + const services = datasets.map((d) => d.trace.service); + assert.ok(!services.includes('unit.biz'), 'RPC legs emit no dataset (engine parity)'); + const tokens = datasets.filter((d) => d.trace.service === 'unit.tokens'); + assert.equal(tokens.length, 1); + const trace = tokens[0].trace; + assert.equal(trace.id, '4bf92f3577b34da6a3ce929d0e0e4747'); + assert.equal(trace.path, 'TEST /telemetry'); + assert.equal(trace.parent_span_id, callerSpan); + assert.equal(trace.success, true); + assert.equal(trace.status, 200); + // an anonymous /api/event caller: the host fills the sender with its own + // identity, the engines' EventApiService parity + assert.equal(trace.from, 'event.api.service'); + for (const key of ['origin', 'start', 'exec_time', 'span_id']) { + assert.ok(key in trace, `engine dataset key ${key}`); + } +}); + +test('the business cid is injected on local delivery', async () => { + // engine WorkerHandler parity: local bus deliveries inject the read-only + // view too, and no context means no injection + const po = new PostOffice(undefined, {}, registry); + const reply = await runWithTrace( + { traceId: 'biz-trace-2', tracePath: 'TEST /local', myCorrelationId: 'biz-7', annotations: {} }, + () => po.request('unit.biz', undefined, { timeoutMs: 5000 })); + assert.deepEqual(reply.body, { my_correlation_id: 'biz-7' }); + const plain = await po.request('unit.biz', undefined, { timeoutMs: 5000 }); + assert.deepEqual(plain.body, { my_correlation_id: null }); +}); + +test('streaming target without the opt-in is refused with 406', async () => { + const po = new PostOffice(); + const reply = await po.request('unit.tokens', undefined, + { headers: { mode: 'tokens' }, endpoint: url, timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 406); + assert.equal(reply.body, REFUSAL); +}); + +test('local RPC to a streaming target is refused with 406', async () => { + const po = new PostOffice(undefined, {}, registry); + const reply = await po.request('unit.tokens', undefined, + { headers: { mode: 'tokens' }, timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 406); + assert.equal(reply.body, REFUSAL); +}); + +test('mid-stream failure propagates the exact status', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'error-mid'); + assert.equal(events[0].body, 'partial'); + const error = events[events.length - 1]; + assert.equal(streamSignal(error), 'exception'); + assert.equal(error.getStatus(), 503); + // the standard error key-values: '{"type": "error", "status": n, "message": text}' + assert.deepEqual(error.body, { type: 'error', status: 503, message: 'backend on fire' }); +}); + +test('failure before the first segment arrives as an exception', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'error-first'); + assert.equal(events.length, 1); + assert.equal(streamSignal(events[0]), 'exception'); + assert.equal(events[0].getStatus(), 503); + assert.equal((events[0].body as Record)['message'], 'no backend'); +}); + +test('an interceptor crash before the head is the classic error', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'crash-before'); + assert.equal(events.length, 1); + assert.equal(streamSignal(events[0]), undefined, 'an unstarted stream fails single-shot'); + assert.equal(events[0].getStatus(), 500); + assert.equal(events[0].body, 'kaboom before head'); +}); + +test('an interceptor crash mid-stream fails in-band', async () => { + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'crash-mid'); + assert.equal(events[0].body, 'early'); + const error = events[events.length - 1]; + assert.equal(streamSignal(error), 'exception'); + assert.equal(error.getStatus(), 500); + assert.equal((error.body as Record)['message'], 'kaboom mid-stream'); +}); + +test('an idle stall fails in-band with 408', async () => { + const started = Date.now(); + const po = new PostOffice(); + const events = await collect(po, 'unit.tokens', url, 'stall', 10000); + const elapsed = Date.now() - started; + assert.equal(events[0].body, 'one'); + const error = events[events.length - 1]; + assert.equal(streamSignal(error), 'exception'); + assert.equal(error.getStatus(), 408); + const body = error.body as Record; + assert.equal(body['type'], 'error'); + assert.equal(body['message'], 'Timeout for 1 seconds'); + assert.ok(elapsed < 8000, `the producer's 1s idle allowance governs, took ${elapsed}ms`); +}); + +test('the relay composition streams through', async () => { + // the flagship: unit.relay forwards its caller's reply address into a call + // against the remote streaming function - engine-parity composition + const po = new PostOffice(); + const events = await collect(po, 'unit.relay', url, undefined, 10000, 'cid-relay'); + assert.deepEqual(events.map((e) => e.body), ['alpha', 'beta', { segments: 2 }]); + assert.equal(streamSignal(events[events.length - 1]), 'eof'); + assert.equal(events[0].cid, 'cid-relay', 'the original correlation id rides the chain'); +}); + +test('a local stream uses the same contract', async () => { + const po = new PostOffice(undefined, {}, registry); + const events: EventEnvelope[] = []; + for await (const event of po.stream('unit.tokens', undefined, + { timeoutMs: 10000, cid: 'cid-local' })) { + events.push(event); + } + assert.deepEqual(events.map((e) => e.body), ['alpha', 'beta', { segments: 2 }]); + assert.equal(streamSignal(events[0]), 'data'); + assert.equal(streamSignal(events[events.length - 1]), 'eof'); +}); + +// ---- the client guards the dialect against a misbehaving peer ---- + +import { createServer as createHttpServer } from 'node:http'; + +function envelopeFrameText(event: EventEnvelope): string { + const encoded = Buffer.from(event.toBytes()).toString('base64'); + return `event: envelope\ndata: ${encoded}\n\n`; +} + +const mockHead = () => envelopeFrameText( + new EventEnvelope(undefined, 'mock-head') + .setHeader('x-event-stream', 'data').setHeader('content-type', SSE).setStatus(200)); +const mockEof = () => envelopeFrameText( + new EventEnvelope(undefined, { done: true }).setHeader('x-event-stream', 'eof')); + +let mockPeer: http.Server; +let mockBase: string; + +before(async () => { + mockPeer = createHttpServer((req, res) => { + res.writeHead(200, { 'content-type': SSE }); + if (req.url === '/mock/raw-first') { + res.write('data: hello\n\n'); + res.end(); + } else if (req.url === '/mock/no-terminal') { + res.write(mockHead()); + res.end(); + } else if (req.url === '/mock/foreign-dialect') { + res.write(mockHead() + 'data: mock-token\n\n' + mockEof() + 'data: trailing-noise\n\n'); + res.end(); + } else if (req.url === '/mock/silent') { + res.write(mockHead()); + setTimeout(() => res.end(), 5000).unref(); + } else { + res.end(); + } + }); + await new Promise((resolve) => mockPeer.listen(0, '127.0.0.1', resolve)); + const address = mockPeer.address() as { port: number }; + mockBase = `http://127.0.0.1:${address.port}`; +}); + +after(() => new Promise((resolve) => { + mockPeer.closeAllConnections(); + mockPeer.close(() => resolve()); +})); + +test('a raw first frame from a foreign server is rejected', async () => { + const po = new PostOffice(); + const events = await collect(po, 'any.route', `${mockBase}/mock/raw-first`); + assert.equal(events.length, 1); + assert.equal(streamSignal(events[0]), 'exception'); + assert.equal(events[0].getStatus(), 500); + assert.equal((events[0].body as Record)['message'], + 'Invalid event stream - missing envelope head'); +}); + +test('a transport end without a terminal is a truncation', async () => { + const po = new PostOffice(); + const events = await collect(po, 'any.route', `${mockBase}/mock/no-terminal`); + assert.equal(events[0].body, 'mock-head'); + const error = events[events.length - 1]; + assert.equal(streamSignal(error), 'exception'); + assert.equal(error.getStatus(), 500); + assert.equal((error.body as Record)['message'], + 'Event stream ended without eof'); +}); + +test('a foreign-dialect peer works and trailing frames drop', async () => { + const po = new PostOffice(); + const events = await collect(po, 'any.route', `${mockBase}/mock/foreign-dialect`); + assert.deepEqual(events.map((e) => e.body), ['mock-head', 'mock-token', { done: true }]); + assert.equal(streamSignal(events[1]), 'data', 'a raw token after the head is a data segment'); + assert.equal(streamSignal(events[2]), 'eof'); +}); + +test('the client idle guard fails in-band', async () => { + const po = new PostOffice(); + const events = await collect(po, 'any.route', `${mockBase}/mock/silent`, undefined, 2000); + assert.equal(events[0].body, 'mock-head'); + const error = events[events.length - 1]; + assert.equal(streamSignal(error), 'exception'); + assert.equal(error.getStatus(), 408); + assert.equal((error.body as Record)['message'], 'Timeout for 2 seconds'); +}); diff --git a/test/log-context.test.ts b/test/log-context.test.ts new file mode 100644 index 00000000..fc589b72 --- /dev/null +++ b/test/log-context.test.ts @@ -0,0 +1,89 @@ +/** + * Application log context tests - the engines' app-log-context twin: default + * template rendering, the updateContext developer API and feature gating. + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { appConfig } from '../src/config.js'; +import { + LogContextConfig, + logContextConfig, + resetLogContextForTest +} from '../src/log-context.js'; +import { runWithTrace, TraceInfo, updateContext } from '../src/trace.js'; + +// mirror of the engines' built-in default-log-context.yaml +const DEFAULT_TEMPLATE: Record = { + cid: '$cid', traceId: '$traceId', tracePath: '$tracePath', spanId: '$spanId', + parentSpanId: '$parentSpanId', service: '$service', timestamp: '$utc' +}; + +function infoUnderTest(): TraceInfo { + return { + route: 'llm.chat', + traceId: '4bf92f3577b34da6a3ce929d0e0e4736', + tracePath: 'POST /api/agent/run', + myCorrelationId: 'biz-7788', + spanId: '82d8a6ccd03638fe', + parentSpanId: '00f067aa0ba902b7', + annotations: {} + }; +} + +test('the default template renders the standard trace context', () => { + const context = new LogContextConfig(DEFAULT_TEMPLATE).render(infoUnderTest()); + assert.equal(context.cid, 'biz-7788'); + assert.equal(context.traceId, '4bf92f3577b34da6a3ce929d0e0e4736'); + assert.equal(context.tracePath, 'POST /api/agent/run'); + assert.equal(context.spanId, '82d8a6ccd03638fe'); + assert.equal(context.parentSpanId, '00f067aa0ba902b7'); + assert.equal(context.service, 'llm.chat'); + assert.ok(typeof context.timestamp === 'string'); + // absent values are omitted, never rendered as "null" - and cid is the + // BUSINESS correlation-id only + const bare = new LogContextConfig(DEFAULT_TEMPLATE).render( + { route: 'llm.chat', traceId: 't-1', cid: 'internal-routing-id', annotations: {} }); + assert.ok(!('cid' in bare)); + assert.ok(!('spanId' in bare)); +}); + +test('custom templates carry tokens and constants, and validate tokens', () => { + const config = new LogContextConfig({ trace: '$traceId', deployment: 'blue' }); + const context = config.render(infoUnderTest()); + assert.deepEqual(context, { + trace: '4bf92f3577b34da6a3ce929d0e0e4736', deployment: 'blue' + }); + assert.throws(() => new LogContextConfig({ x: '$bogus' }), + /Invalid log context token/); +}); + +test('updateContext merges custom keys and guards reserved keys', () => { + const config = new LogContextConfig(DEFAULT_TEMPLATE); + const info: TraceInfo = { ...infoUnderTest() }; + runWithTrace(info, () => { + updateContext('tenant', 'acme'); + assert.equal(config.render(info).tenant, 'acme'); + updateContext('tenant', null); + assert.ok(!('tenant' in config.render(info))); + assert.throws(() => updateContext('cid', 'nope'), /reserved/); + }); + // outside a hosted request: a silent no-op, the engines' semantics + updateContext('tenant', 'ignored'); +}); + +test('the app.log.context flag disables the feature', () => { + try { + appConfig().set('app.log.context', 'false'); + resetLogContextForTest(); + assert.equal(logContextConfig().enabled, false); + } finally { + appConfig().set('app.log.context', 'true'); + resetLogContextForTest(); + } + assert.equal(logContextConfig().enabled, true); + // and the packaged default-log-context.yaml is what loaded - the engines' + // resource-file twin, not a code constant + const rendered = logContextConfig().render(infoUnderTest()); + assert.equal(rendered.service, 'llm.chat'); + assert.equal(rendered.cid, 'biz-7788'); +});