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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@

## Unreleased

### Fixed

1. **The answer of a function that answers for itself carries its execution.** An interceptor answers through its
reply address, and the caller writes the trace record of a request-response call from that answer. An answer that
a handler built and sent with `registry.sendEvent()` carried nothing of the execution: the record held no
`exec_time`, no `span_id` and no annotations, and an engine that called the function through `/api/event` read an
answer without them. The answer carried no trace either, so a function that received it through a reply route ran
untraced. An unmarked envelope sent from inside an interceptor's execution to the request's reply address now
takes the execution's span, its annotations and the time since the execution started, and the sender and the trace
where it has none; the error envelope of an uncaught exception takes them too. An envelope to another route is not
touched, a stream's segments stay the stream writer's, and an answer passed on from another function keeps that
function's `exec_time` and sender. For a request-response call that arrives at `/api/event`, the host now writes
the function's round-trip record for an interceptor as it does for a function that returns its answer, also when
the call times out; a call without the `rpc` tag keeps the one record its execution writes. The twin of the
engines' fix for their HTTP client (mercury-composable #715 and #716). Not covered: a handler that returns before
its answer is sent - the worker's own record, written for a call with a reply route, holds the time until the
handler returned. **Upgrade note:** read - the record of a request-response call to an interceptor gains
`exec_time`, `span_id` and its annotations; a wire request-response call to an interceptor leaves one more record,
the function's; a function that an interceptor answers through a reply route is traced, as the child of the
interceptor's span.

### Changed

1. **Git ignores the package tarball that `npm pack` writes.** Packing a release writes
Expand Down
7 changes: 7 additions & 0 deletions docs/guides/config-logging-actuators.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ follows the engines' rules, so a span lineage stays continuous from an engine in
`InboxBase`): the `PostOffice` records a local call with the responder's span, which rides
the reply, the caller's span as parent, the responder's `exec_time` and the `round_trip`
it measured;
- a function that answers for itself, an interceptor that sends its answer to the request's
reply address, is recorded by the same rules. The answer takes the execution's span, its
annotations and the time since the execution started when it is sent, so the caller's
record of a request-response call holds them; it takes the sender and the trace too, so a
function that receives the answer through a reply route runs under the trace, as the child
of that execution. An answer passed on from another function keeps that function's
`exec_time` and sender, and a stream's segments are the stream writer's;
- a traced call arriving at `/api/event` leaves what a Java or Rust callee leaves for it:
`http.request` (`POST /api/event`, the edge's round trip, parented onto the caller's span —
the envelope's span, else the `traceparent` header's; the backend's SERVER span),
Expand Down
9 changes: 6 additions & 3 deletions docs/guides/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ 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.
`event.replyTo` yourself through `registry.sendEvent()`. That answer takes the
execution's span, its trace annotations and its execution time when it is sent, as a
returned answer does, so the caller's trace record of the call is complete; an answer
you pass on from another function keeps that function's execution time. 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

Expand Down
70 changes: 63 additions & 7 deletions src/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { EventEnvelope, isoUtc } from './envelope.js';
import { AppException } from './exceptions.js';
import { getLogger } from './log.js';
import type { ServiceDef } from './registry.js';
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomBytes } from 'node:crypto';
import { appOrigin } from './actuator.js';
import { DISTRIBUTED_TRACE_FORWARDER, MY_CID_TAG, MY_CORRELATION_ID, RPC_TAG, runWithTrace, TraceInfo } from './trace.js';
Expand All @@ -54,6 +55,54 @@ export class DeliveryTimeout extends Error {
}
}

/** One execution of an interceptor: what its answer takes from it. */
interface Execution {
info: TraceInfo;
replyTo: string | undefined;
started: bigint;
}

// The interceptor execution that the current code runs in. An interceptor answers for itself,
// so no worker shapes its answer: the answer takes the execution's context when it is sent.
const executions = new AsyncLocalStorage<Execution | undefined>();

/** True for a stream's segment (event-stream.ts imports this module, so the marker is read here). */
function isStreamSegment(event: EventEnvelope): boolean {
return Object.keys(event.headers).some((key) => key.toLowerCase() === 'x-event-stream');
}

/**
* Give the answer of an interceptor what a worker gives the reply of a function that returns
* it: the execution's span, its annotations and the time it took - the caller writes the
* record of a request-response call from them - and the sender and the trace, so a function
* that receives the answer through a reply route runs under the trace, as the child of this
* execution.
*
* The answer is an unmarked envelope sent from inside the execution to the request's reply
* address. An envelope to another route is not one, and a stream's segments are the stream
* writer's. An answer that another function wrote keeps that function's sender and time.
*/
export function stampAnswer(event: EventEnvelope,
execution: Execution | undefined = executions.getStore()): void {
if (!execution?.replyTo || event.to !== execution.replyTo || isStreamSegment(event)) {
return;
}
const info = execution.info;
if (!event.sender && info.route) {
event.setFrom(info.route);
}
if (info.traceId && !event.traceId) {
event.setTrace(info.traceId, info.tracePath ?? execution.replyTo);
}
if (info.spanId) {
event.setSpanId(info.spanId);
}
if (Object.keys(info.annotations).length) {
event.annotations = { ...info.annotations, ...event.annotations };
}
event.execTime ??= Math.round(Number(process.hrtime.bigint() - execution.started) / 1000) / 1000;
}

/** The 202 drop-n-forget acknowledgement (EventApiService shape). */
export function asyncAck(): EventEnvelope {
return new EventEnvelope().setStatus(202)
Expand Down Expand Up @@ -309,7 +358,8 @@ export class EventBus {
// 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));
// a worker is created by whoever calls first: it runs with a clean context
void executions.run(undefined, () => runWithTrace(undefined, () => this.runWorker(created)));
}
}
return mailbox;
Expand Down Expand Up @@ -446,13 +496,15 @@ export class EventBus {
const info = traceInfoOf(delivery, myCid);
const startIso = isoUtc();
const start = process.hrtime.bigint();
// the answer that the handler sends to its reply address takes this execution's context
const execution: Execution = { info, replyTo: event.replyTo, started: start };
let error: unknown;
try {
await runWithTrace(info, async () =>
await delivery.service.handler(headers, event));
await executions.run(execution, () => runWithTrace(info, async () =>
await delivery.service.handler(headers, event)));
} catch (e) {
error = e;
this.replyInterceptorError(delivery.service.route, event, e);
this.replyInterceptorError(delivery.service.route, event, e, execution);
}
let status = 200;
if (error instanceof AppException) {
Expand Down Expand Up @@ -495,7 +547,8 @@ export class EventBus {
this.router(new EventEnvelope(DISTRIBUTED_TRACE_FORWARDER, dataset));
}

private replyInterceptorError(route: string, event: EventEnvelope, e: unknown): void {
private replyInterceptorError(route: string, event: EventEnvelope, e: unknown,
execution: Execution): void {
let error: EventEnvelope;
if (e instanceof AppException) {
error = new EventEnvelope().setStatus(e.status).setBody(e.message);
Expand All @@ -510,8 +563,11 @@ export class EventBus {
if (event.cid) {
error.setCorrelationId(event.cid);
}
const delivered = Boolean(
event.replyTo && this.router?.(error.setTo(event.replyTo)));
if (event.replyTo) {
// the handler's context has ended, so the error takes the execution's here
stampAnswer(error.setTo(event.replyTo), execution);
}
const delivered = Boolean(event.replyTo && this.router?.(error));
if (!delivered) {
log.warn(`Interceptor ${route} ended with status ` +
`${error.getStatus()} - ${error.body}`);
Expand Down
4 changes: 3 additions & 1 deletion src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* TypedLambdaFunction — and return the reply body (or an EventEnvelope for
* full control of status and reply headers).
*/
import { EventBus } from './bus.js';
import { EventBus, stampAnswer } from './bus.js';
import type { EventEnvelope } from './envelope.js';

/**
Expand Down Expand Up @@ -109,6 +109,8 @@ export class FunctionRegistry {
if (!route) {
return false;
}
// the answer of a function that answers for itself carries its execution
stampAnswer(event);
if (this.bus.offerSink(route, event)) {
return true;
}
Expand Down
12 changes: 11 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import { enabled as logContextEnabled } from './log-context.js';
import { activate as activateOtelForwarder } from './otel/index.js';
import { defaultRegistry, FunctionRegistry, ServiceDef } from './registry.js';
import { readBody, RestAutomation, restError, unrendered } from './rest-automation.js';
import { MY_CID_TAG, MY_CORRELATION_ID } from './trace.js';
import { MY_CID_TAG, MY_CORRELATION_ID, RPC_TAG } from './trace.js';

const OCTET_STREAM = 'application/octet-stream';
// the engines' reserved route name for the Event-over-HTTP ingress
Expand Down Expand Up @@ -371,6 +371,12 @@ export class EventApiServer {
const bus = this.registry.bus;
const [sinkRoute, queue] = bus.openSink();
const capable = String(req.headers['accept'] ?? '').includes(TEXT_EVENT_STREAM);
// the execution of a request-response call writes no record of its own (the rpc tag), so
// the host writes the function's round trip, as it does for a function that returns its
// answer; any other call leaves the record its execution writes
const rpc = event.tags[RPC_TAG] ? edge : undefined;
const dispatched = isoUtc();
const started = process.hrtime.bigint();
try {
const handlerEvent = new EventEnvelope(event.to, event.body, headers);
handlerEvent.setReplyTo(sinkRoute);
Expand Down Expand Up @@ -398,6 +404,8 @@ export class EventApiServer {
if (!first) {
log.warn(`Event ${event.to} timeout for ${ttl} ms ` +
`(trace_id=${event.traceId ?? 'none'})`);
rpc?.recordFunction(event.sender,
new EventEnvelope().setStatus(408).setBody(`Timeout for ${ttl} ms`), dispatched, started);
edge?.recordEdge(408, `Timeout for ${ttl} ms`);
transportError(res, 408, `Timeout for ${ttl} ms`);
return;
Expand All @@ -409,6 +417,8 @@ export class EventApiServer {
log.info(`Handled ${event.to} status=${first.getStatus()} ` +
`exec_time=${first.execTime ?? 0}ms trace_id=${event.traceId ?? 'none'}`);
const [status, error] = relay(res, event.to, first);
// the function answered - its own record stands whatever becomes of the reply
rpc?.recordFunction(event.sender, first, dispatched, started);
edge?.recordEdge(status, error);
return;
}
Expand Down
Loading
Loading