diff --git a/CHANGELOG.md b/CHANGELOG.md index 7603eb9..323d420 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,13 +7,42 @@ is `0`, minor versions may carry breaking changes — they are called out here. ## [Unreleased] +### Added +- **One trace per business event** (ADR-0034, lot A). The runtime carries a W3C + `traceparent` in a NATS header on every message it publishes, so the spans of + one event, from the source or webhook through each flow and `invoke` to the + sink, form one trace with parent links. `http-in` and `api` flows continue a + caller's trace, and `http-in` answers with the trace id. `http-out` and + `slack-out` send `traceparent` downstream, and an `exec` sink gets it as + `TRACEPARENT`. A dead letter keeps its trace and a replay continues it. The + event ring and the `dead-lettered` event show the trace id. Transport test T6 + checks the chain in CI against a stub collector, a graceful stop included. +- **The OTLP exporter reads the standard variables:** the traces endpoint, + headers (never logged) and timeout, `OTEL_RESOURCE_ATTRIBUTES`, the six + samplers of `OTEL_TRACES_SAMPLER`, and the batch variables `OTEL_BSP_*`. It + retries connection errors, 429, 502, 503 and 504 with backoff, flushes its + queue on a graceful stop, and counts on `/metrics` what it sends and what it + loses (`vejas_spans_exported_total`, `vejas_spans_dropped_total{reason}`). + +### Changed +- Spans have a new shape. The name is still the unit and the old attributes + stay, but the kind now says what the hop was (`SERVER`, `PRODUCER`, + `CONSUMER`, `CLIENT`, `INTERNAL` instead of `CONSUMER` everywhere), new + attributes follow the OpenTelemetry semantic conventions (`messaging.*`, + `error.type`) and carry the flow version, and a success leaves the status + unset instead of `OK`. A query or dashboard that filters on kind or status + may need updating. +- The trace context travels even without an exporter, so a downstream system + and the event ring get it. It costs about 3 µs of CPU per flow hop; exporting + every span about 10 µs (see the benchmarks page). + ### Corrected - The observability guide said an end-to-end request shows up as a trace across the pipeline. It does not: every span carries a fresh trace id and no parent, so a request that crosses three flows is three unrelated traces in the collector. The guide now says so, and says the cost of the OTLP exporter and of the event ring has - not been measured separately. ADR-0034 (Proposed) decides how one trace per event - gets built; the guide will claim it once its CI test passes. + not been measured separately. ADR-0034 decided how one trace per event gets + built, and it is built in this release: see Added. ### Security - **url 2.5.8 → 2.5.9** in the runtime and in the `mq` and `amqp` connectors, for diff --git a/bench/README.md b/bench/README.md index 4d5bde4..c6bb353 100644 --- a/bench/README.md +++ b/bench/README.md @@ -151,6 +151,44 @@ harness and the same program: **18 643 evt/s** at 16 publishers (17 265 at about 20 µs per event under load and under 10 µs in isolation (its own `throughput_probe`). Same consumer path, same publish-before-ack barrier. +## What tracing costs (ADR-0034, `bench/trace-cost.sh`) + +`bench/trace-cost.sh` runs the isolated flow hop above in each tracing +configuration, interleaved, five times each (20 000 events, four +publishers), and reads the runtime's own CPU time from `/proc`. With four +publishers the rate is theirs; the CPU time is the runtime's. Spans go to a +collector that only counts them (`bench/otlp-discard.py`). 2026-11-26, same +machine; the runtime from before tracing is master at `491ba69`, passed as +`BASE_BIN`: + +| Configuration | Flow-hop rate | Runtime CPU per event | RSS | +|---|---|---|---| +| Before tracing | 9 390/s | 72.5 µs | 9.7 MB | +| Context propagated, no exporter | 9 403/s | 74.0 µs | 10.4 MB | +| Every span exported | 9 166/s | 83.0 µs | 12.3 MB | +| One trace in ten exported | 9 204/s | 76.5 µs | 12.0 MB | +| Before tracing, events carrying `traceparent` | 8 718/s | 71.0 µs | 9.5 MB | +| No exporter, events carrying `traceparent` | 8 632/s | 78.5 µs | 10.5 MB | +| Every span exported, events carrying `traceparent` | 8 669/s | 88.0 µs | 12.6 MB | + +The 200 000 spans of the "every span" runs all reached the collector, and +10 023 of the 100 000 events sampled at one in ten. Over four series the +context alone measured between 1.5 and 4.5 µs; over three, export held at 10 +to 10.5 µs over the runtime from before tracing. Events that carry a header slow the +publishers (the `nats` CLI sends it) as much before tracing as after. + +Two findings on the way, both fixed before the numbers above: + +- **#8 One HTTP request per handful of spans.** The first exporter posted + whatever its queue held and built a JSON tree per span: export cost 63 µs + of CPU per event over the same runtime without an exporter. Batching as + the OpenTelemetry SDKs do (512 spans or 1 s, `OTEL_BSP_*`) and writing the + JSON directly brought it to 28 µs. +- **#9 Waking the exporter for every span.** An exporter that waits on its + queue has every producer wake it, a futex call and a context switch per + span. Reading the queue on a 25 ms tick while spans are pending brought + export to between 5.5 and 9 µs. + ## The true hop ceiling and multi-flow scaling With parallel publishers, the single-flow hop tops out around **14–16 k/s** diff --git a/bench/flow-only.sh b/bench/flow-only.sh index 2300e99..719d44d 100755 --- a/bench/flow-only.sh +++ b/bench/flow-only.sh @@ -4,13 +4,17 @@ # plain NATS subscription. This is the interpreter + JetStream number — what # the end-to-end pipeline can hope for once the I/O ceilings fall. # bench/flow-only.sh [count] (needs the `nats` CLI) +# BIN= runs another binary (a before/after comparison). With +# BENCH_TRACEPARENT= the events carry that header, so the flow +# continues a trace instead of starting one; OTEL_EXPORTER_OTLP_ENDPOINT, if +# set, reaches the runtime and turns span export on (ADR-0034, point 6). set -euo pipefail cd "$(dirname "$0")/.." N="${1:-20000}" PUBS="${PUBS:-4}" # parallel publishers — one sequential publisher caps ~2.8k/s N=$(( (N / PUBS) * PUBS )) # keep the count exactly divisible -BIN="core/target/release/vejas-runtime" +BIN="${BIN:-core/target/release/vejas-runtime}" NATS_PORT=4224 STORE=$(mktemp -d) ROOT=$(mktemp -d) @@ -45,10 +49,13 @@ SUB_PID=$! sleep 0.5 EVENT=$(tr -d '\n' < bench/root/flows/fixtures/bench_orders.json) +HEADER=() +[ -n "${BENCH_TRACEPARENT:-}" ] && HEADER=(-H "traceparent:$BENCH_TRACEPARENT") T0=$(date +%s%N) PUB_PIDS=() for _ in $(seq "$PUBS"); do - nats -s nats://127.0.0.1:$NATS_PORT pub vx.bench.orders --count=$((N / PUBS)) "$EVENT" > /dev/null 2>&1 & + nats -s nats://127.0.0.1:$NATS_PORT pub vx.bench.orders --count=$((N / PUBS)) \ + ${HEADER[@]+"${HEADER[@]}"} "$EVENT" > /dev/null 2>&1 & PUB_PIDS+=($!) done wait "${PUB_PIDS[@]}" @@ -57,10 +64,13 @@ PUB_MS=$(( ($(date +%s%N) - T0) / 1000000 )) wait $SUB_PID TOTAL_MS=$(( ($(date +%s%N) - T0) / 1000000 )) RSS_KB=$(ps -o rss= -p $RUNTIME_PID | tr -d ' ') +# The runtime's own CPU time (user + system, Linux): what a change costs the +# runtime, apart from the publishers and the server it shares the machine with. +CPU_MS=$(awk -v hz="$(getconf CLK_TCK)" '{printf "%d", ($14 + $15) * 1000 / hz}' "/proc/$RUNTIME_PID/stat" 2>/dev/null || echo 0) -python3 - "$N" "$PUB_MS" "$TOTAL_MS" "$RSS_KB" << 'PY' +python3 - "$N" "$PUB_MS" "$TOTAL_MS" "$RSS_KB" "$CPU_MS" << 'PY' import json, sys -n, pub_ms, total_ms, rss = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]) +n, pub_ms, total_ms, rss, cpu_ms = (int(a) for a in sys.argv[1:6]) print(json.dumps({ "scenario": "bus -> flow (lookup + conversions + projection loop) -> bus, no HTTP anywhere", "events": n, @@ -68,5 +78,7 @@ print(json.dumps({ "done_ms": total_ms, "flow_rate_per_s": round(n / (total_ms / 1000)), "runtime_rss_mb": round(rss / 1024, 1), + "runtime_cpu_ms": cpu_ms, + "runtime_cpu_us_per_event": round(cpu_ms * 1000 / n, 1), }, indent=2)) PY diff --git a/bench/otlp-discard.py b/bench/otlp-discard.py new file mode 100644 index 0000000..7ae85f6 --- /dev/null +++ b/bench/otlp-discard.py @@ -0,0 +1,34 @@ +"""A collector that accepts OTLP/HTTP JSON, keeps nothing, and counts spans. + + python3 bench/otlp-discard.py + +bench/trace-cost.sh points the runtime at it, so the cost measured is the +runtime's, not a real collector's. +""" +import http.server +import sys +import threading + +port, count_file = int(sys.argv[1]), sys.argv[2] +lock = threading.Lock() +spans = 0 + + +class Discard(http.server.BaseHTTPRequestHandler): + def do_POST(self): + global spans + body = self.rfile.read(int(self.headers.get("content-length") or 0)) + with lock: + spans += body.count(b'"spanId"') + with open(count_file, "w") as f: + f.write(str(spans)) + self.send_response(200) + self.send_header("content-type", "application/json") + self.end_headers() + self.wfile.write(b"{}") + + def log_message(self, *args): + pass + + +http.server.ThreadingHTTPServer(("127.0.0.1", port), Discard).serve_forever() diff --git a/bench/trace-cost.sh b/bench/trace-cost.sh new file mode 100755 index 0000000..6880556 --- /dev/null +++ b/bench/trace-cost.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# What tracing costs on the flow hop (ADR-0034, point 6). Runs +# bench/flow-only.sh RUNS times per configuration, interleaved so that drift +# hits every configuration alike, and prints the medians: throughput, and the +# runtime's own CPU time per event (the better measure, since four publishers +# bound the throughput). +# bench/trace-cost.sh [runs] [events] (needs the `nats` CLI) +# BIN is the runtime under test (core/target/release/vejas-runtime). BASE_BIN, +# if set, is a runtime from before tracing (v0.6.0): the difference is what +# propagation costs with no exporter. Spans go to bench/otlp-discard.py, which +# only counts them. +set -euo pipefail +cd "$(dirname "$0")/.." +RUNS="${1:-5}" +N="${2:-20000}" +BIN="${BIN:-core/target/release/vejas-runtime}" +BASE_BIN="${BASE_BIN:-}" +COL_P="${COL_P:-4399}" +OUT=$(mktemp) +COUNT=$(mktemp) +TP="00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" +EP="http://127.0.0.1:$COL_P" +python3 bench/otlp-discard.py "$COL_P" "$COUNT" & +COL=$! +trap 'kill $COL 2>/dev/null || true; rm -f "$OUT" "$COUNT"' EXIT +sleep 0.5 + +one() { # a label, then the environment of that configuration + local label="$1"; shift + local json + json=$(env "$@" bench/flow-only.sh "$N" 2>/dev/null) + python3 -c 'import json, sys; print(json.dumps({"config": sys.argv[1], "result": json.loads(sys.argv[2])}))' \ + "$label" "$json" >>"$OUT" + echo " $label done" >&2 +} +for r in $(seq "$RUNS"); do + echo "run $r/$RUNS" >&2 + if [ -n "$BASE_BIN" ]; then + one "before tracing" BIN="$BASE_BIN" + one "before, caller header" BIN="$BASE_BIN" BENCH_TRACEPARENT="$TP" + fi + one "no exporter" BIN="$BIN" + one "no exporter, caller header" BIN="$BIN" BENCH_TRACEPARENT="$TP" + one "export all" BIN="$BIN" OTEL_EXPORTER_OTLP_ENDPOINT="$EP" + one "export all, caller header" BIN="$BIN" BENCH_TRACEPARENT="$TP" OTEL_EXPORTER_OTLP_ENDPOINT="$EP" + one "export 1 in 10" BIN="$BIN" OTEL_EXPORTER_OTLP_ENDPOINT="$EP" \ + OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.1 +done +python3 - "$OUT" <<'PY' +import json, statistics, sys +by = {} +for line in open(sys.argv[1]): + row = json.loads(line) + by.setdefault(row["config"], []).append(row["result"]) +ref = "before tracing" if "before tracing" in by else "no exporter" +med = lambda rows, k: statistics.median(r[k] for r in rows) +base_rate = med(by[ref], "flow_rate_per_s") +base_cpu = med(by[ref], "runtime_cpu_us_per_event") +print(f"{'configuration':<28}{'events/s':>9}{'':>9}{'CPU µs/event':>14}{'':>9}{'RSS MB':>8}") +for name, rows in by.items(): + rate, cpu = med(rows, "flow_rate_per_s"), med(rows, "runtime_cpu_us_per_event") + print(f"{name:<28}{rate:>9.0f}{(rate / base_rate - 1) * 100:>+8.1f}%" + f"{cpu:>14.1f}{(cpu / base_cpu - 1) * 100:>+8.1f}%{med(rows, 'runtime_rss_mb'):>8}") +print(f"(medians of {len(by[ref])} runs; percentages against '{ref}')") +PY +echo "spans received by the collector: $(cat "$COUNT")" diff --git a/core/Cargo.lock b/core/Cargo.lock index 999766b..5548823 100644 --- a/core/Cargo.lock +++ b/core/Cargo.lock @@ -1586,6 +1586,7 @@ dependencies = [ "bytes", "ctrlc", "futures-util", + "getrandom 0.2.17", "rustls", "serde_json", "tiny_http", diff --git a/core/Cargo.toml b/core/Cargo.toml index 1d464f1..5514f5c 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -24,6 +24,9 @@ ureq = "2" # the hand-rolled MQTT client can wrap its stream in TLS. No new binary weight. rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] } webpki-roots = "0.26" +# Seeds the trace and span ids (ADR-0034). Already in the tree through ring, so +# no new binary weight. +getrandom = "0.2" # The Varpulis CEP engine, embedded as a library (ADR-0031): compile a VPL # program, feed it events, publish its emits. No async runtime in its tree — # its own CI (scripts/check-engine-deps.py) fails if one ever appears. diff --git a/core/src/bus.rs b/core/src/bus.rs index 6e75c7f..8227118 100644 --- a/core/src/bus.rs +++ b/core/src/bus.rs @@ -17,6 +17,9 @@ // two thousand sockets. // * What the sync client gave for free is rebuilt here on purpose, because // `async-nats` does not give it: see `Batch::confirm`. +// +// The AMQP and MQ connectors compile this file as it is (`#[path]`), so it +// names no other module of the runtime: no `crate::` import. use std::cell::RefCell; use std::collections::HashMap; @@ -28,7 +31,9 @@ use std::time::{Duration, Instant}; use async_nats::client::{Request, Statistics}; use async_nats::connection::State; use async_nats::jetstream::{self, kv, object_store}; -use async_nats::{Client, ConnectOptions, Event, ServerAddr, StatusCode, Subject, Subscriber}; +use async_nats::{ + Client, ConnectOptions, Event, HeaderMap, HeaderName, ServerAddr, StatusCode, Subject, Subscriber, +}; use bytes::Bytes; use futures_util::{FutureExt, StreamExt}; use serde_json::{json, Value}; @@ -285,6 +290,20 @@ impl Bus { wait(sent(client.publish(subject.to_string(), payload))) } + /// The same, carrying the trace it belongs to (ADR-0034). + pub fn publish_traced( + &self, + subject: &str, + payload: impl Into, + trace: &impl TraceContext, + ) -> Result<(), String> { + let (client, payload) = (&self.0.link.client, payload.into()); + match trace_headers_within(trace, payload.len(), client.max_payload()) { + Some(headers) => wait(sent(client.publish_with_headers(subject.to_string(), headers, payload))), + None => wait(sent(client.publish(subject.to_string(), payload))), + } + } + /// A batch of publishes that leave together, see [`Batch`]. pub fn batch(&self) -> Batch { Batch { @@ -359,7 +378,7 @@ impl Bus { /// whatever has arrived, so a quiet flow's emit leaves as soon as it is made. pub struct Batch { bus: Bus, - held: Vec<(Subject, Bytes)>, + held: Vec<(Subject, Option, Bytes)>, } impl Batch { @@ -367,19 +386,36 @@ impl Batch { /// protocol cannot carry, a payload over the server's limit), and only this /// one: the caller treats its source message as a failed run, and the rest of /// the batch goes on. + /// Without a trace: every publish of the runtime carries one now (ADR-0034), + /// so only the tests hold these. + #[cfg(test)] pub fn publish(&mut self, subject: &str, payload: impl Into) -> Result<(), String> { + self.hold(subject, None, payload.into()) + } + + /// The same, carrying the trace it belongs to (ADR-0034). + pub fn publish_traced( + &mut self, + subject: &str, + payload: impl Into, + trace: &impl TraceContext, + ) -> Result<(), String> { let payload = payload.into(); + let limit = self.bus.0.link.client.max_payload(); + self.hold(subject, trace_headers_within(trace, payload.len(), limit), payload) + } + + fn hold(&mut self, subject: &str, headers: Option, payload: Bytes) -> Result<(), String> { if subject.is_empty() || subject.contains([' ', '\t', '\r', '\n']) { return Err(format!("invalid subject {subject:?}")); } + // The server's limit covers the headers too. + let size = payload.len() + headers.as_ref().map(headers_len).unwrap_or(0); let limit = self.bus.0.link.client.max_payload(); - if payload.len() > limit { - return Err(format!( - "{} bytes is over the server's limit of {limit}", - payload.len() - )); + if size > limit { + return Err(format!("{size} bytes is over the server's limit of {limit}")); } - self.held.push((subject.to_string().into(), payload)); + self.held.push((subject.to_string().into(), headers, payload)); Ok(()) } @@ -410,8 +446,11 @@ impl Batch { let epoch = link.epoch(); let held = &mut self.held; wait(async { - for (subject, payload) in held.drain(..) { - sent(link.client.publish(subject, payload)).await?; + for (subject, headers, payload) in held.drain(..) { + match headers { + Some(headers) => sent(link.client.publish_with_headers(subject, headers, payload)).await?, + None => sent(link.client.publish(subject, payload)).await?, + } } link.barrier_since(epoch).await }) @@ -444,6 +483,7 @@ pub struct Message { pub subject: String, pub data: Bytes, reply: Option, + headers: Option, link: Arc, } @@ -461,10 +501,17 @@ impl Message { subject: message.subject.to_string(), data: message.payload, reply: message.reply, + headers: message.headers, link, } } + /// A header of this message, whatever the case of its name: a producer + /// outside Vejas may write `TraceParent` (ADR-0034). + pub fn header(&self, name: &str) -> Option<&str> { + header(self.headers.as_ref()?, name) + } + /// The JetStream delivery behind this message, if it is one. pub fn delivery(&self) -> Option { parse_ack_subject(self.reply.as_deref()?) @@ -491,6 +538,61 @@ impl Message { } } +/// What a traced publish takes from a trace context: its two W3C headers +/// (ADR-0034). The runtime's `trace::Context` implements it, and reads a +/// consumed message back with [`Message::header`]. +pub trait TraceContext { + fn traceparent(&self) -> String; + fn tracestate(&self) -> Option<&str>; +} + +/// The headers that carry a trace on the bus (ADR-0034). +fn trace_headers(trace: &impl TraceContext) -> HeaderMap { + // Constant names: no allocation for the name on every publish. + const TRACEPARENT: HeaderName = HeaderName::from_static("traceparent"); + const TRACESTATE: HeaderName = HeaderName::from_static("tracestate"); + let mut headers = HeaderMap::new(); + headers.insert(TRACEPARENT, trace.traceparent()); + if let Some(state) = trace.tracestate() { + headers.insert(TRACESTATE, state); + } + headers +} + +/// The trace headers of a payload, or none when they would push the message +/// past the server's limit. A trace is never the reason a publish fails: that +/// message goes untraced, and the next hop starts a trace (ADR-0034). +fn trace_headers_within(trace: &impl TraceContext, payload_len: usize, limit: usize) -> Option { + let headers = trace_headers(trace); + (payload_len + headers_len(&headers) <= limit).then_some(headers) +} + +/// What headers add to a message on the wire: the `NATS/1.0` line, each +/// `name: value` line, and the blank line that ends them. +fn headers_len(headers: &HeaderMap) -> usize { + let lines: usize = headers + .iter() + .map(|(name, values)| { + let name: &str = name.as_ref(); + values.iter().map(|v| name.len() + v.as_str().len() + 4).sum::() + }) + .sum(); + 10 + lines + 2 +} + +/// A header's first value. NATS keeps the case a header was written with, so a +/// name is matched without regard to case; the exact spelling is tried first. +fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + if let Some(value) = headers.get(name) { + return Some(value.as_str()); + } + headers + .iter() + .find(|(k, _)| AsRef::::as_ref(*k).eq_ignore_ascii_case(name)) + .and_then(|(_, values)| values.first()) + .map(|v| v.as_str()) +} + /// `$JS.ACK.......`, /// or the same with `.` in front and a token behind. fn parse_ack_subject(reply: &str) -> Option { @@ -713,6 +815,11 @@ impl JetStream { &(self.0).0 } + /// The largest message the server takes, headers included. + pub fn max_payload(&self) -> usize { + self.shared().link.client.max_payload() + } + /// The JetStream API, as the server speaks it: a request and a JSON reply. /// Administration goes this way rather than through the client's typed /// configs because each of those is free to carry defaults of its own, and @@ -746,6 +853,26 @@ impl JetStream { }) } + /// The same, carrying the trace it belongs to (ADR-0034). + pub fn publish_traced( + &self, + subject: &str, + payload: impl AsRef<[u8]>, + trace: &impl TraceContext, + ) -> Result { + let bytes = Bytes::copy_from_slice(payload.as_ref()); + let headers = trace_headers_within(trace, bytes.len(), self.max_payload()); + wait(async { + let js = &self.shared().js; + let ack = match headers { + Some(headers) => js.publish_with_headers(subject.to_string(), headers, bytes).await, + None => js.publish(subject.to_string(), bytes).await, + }; + let ack = ack.map_err(|e| e.to_string())?.await; + ack.map(|ack| ack.sequence).map_err(|e| e.to_string()) + }) + } + /// Create a stream, or leave it as it is: one that exists is never changed, /// and a different config on it is an error the caller may ignore. pub fn add_stream(&self, config: &StreamConfig) -> Result<(), String> { @@ -1148,6 +1275,36 @@ mod tests { assert!(servers_of("http://a:4222").is_err()); } + /// A trace context as a connector would hold one: the two header values. + pub(super) struct Carried(pub &'static str, pub Option<&'static str>); + impl TraceContext for Carried { + fn traceparent(&self) -> String { + self.0.to_string() + } + fn tracestate(&self) -> Option<&str> { + self.1 + } + } + + #[test] + fn a_trace_header_is_read_whatever_its_case() { + let tp = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + let written = trace_headers(&Carried(tp, Some("k=v"))); + assert_eq!(header(&written, "traceparent"), Some(tp)); + assert_eq!(header(&written, "tracestate"), Some("k=v")); + // "NATS/1.0\r\n" + "traceparent: <55>\r\n" + "tracestate: k=v\r\n" + "\r\n" + assert_eq!(headers_len(&written), 10 + (11 + 55 + 4) + (10 + 3 + 4) + 2); + // Near the server's limit the message goes untraced rather than fail. + let carried = Carried(tp, Some("k=v")); + let room = headers_len(&written); + assert!(trace_headers_within(&carried, 1000 - room, 1000).is_some()); + assert!(trace_headers_within(&carried, 1001 - room, 1000).is_none()); + let mut foreign = HeaderMap::new(); + foreign.insert("TraceParent", tp); + assert_eq!(header(&foreign, "traceparent"), Some(tp)); + assert_eq!(header(&foreign, "tracestate"), None); + } + #[test] fn statuses_end_a_round_or_a_consumer() { let status = |code: StatusCode, description: &str| async_nats::Message { @@ -1200,6 +1357,7 @@ mod tests { /// `cargo test bus::live -- --ignored` #[cfg(test)] mod live { + use super::tests::Carried; use super::*; use std::path::PathBuf; use std::process::{Child, Command, Stdio}; @@ -1278,6 +1436,46 @@ mod live { } } + #[test] + #[ignore] + fn every_publish_carries_its_trace_to_the_consumer() { + let server = Server::start(); + let bus = connect(&server.url()).unwrap(); + let tp = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + let context = Carried(tp, Some("vendor=1")); + let carries = |m: &Message| { + m.header("traceparent") == Some(tp) && m.header("tracestate") == Some("vendor=1") + }; + // Core publish and confirmed batch, read on a subscription. + let mut sub = bus.subscribe("t.core").unwrap(); + bus.publish_traced("t.core", "one", &context).unwrap(); + let mut batch = bus.batch(); + batch.publish_traced("t.core", "two", &context).unwrap(); + batch.publish("t.core", "three").unwrap(); + batch.confirm().unwrap(); + for _ in 0..2 { + let message = sub.next_timeout(Duration::from_secs(5)).unwrap(); + assert!(carries(&message), "the trace headers arrive"); + } + let untraced = sub.next_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(untraced.header("traceparent"), None, "no header written"); + // JetStream publish, read by a pull consumer: the stream keeps it. + let js = bus.jetstream(); + js.add_stream(&StreamConfig { + name: "T".into(), + subjects: vec!["t.js".into()], + ..Default::default() + }) + .unwrap(); + let filter = ["t.js".to_string()]; + js.create_pull_consumer("T", "d", &filter, Duration::ZERO, None).unwrap(); + let puller = js.pull_durable("T", "d", Some("t.js")).unwrap(); + js.publish_traced("t.js", "four", &context).unwrap(); + let pulled: Vec = puller.round().unwrap().collect(); + assert_eq!(pulled.len(), 1); + assert!(carries(&pulled[0]), "the stream keeps the headers"); + } + #[test] #[ignore] fn the_barrier_comes_back_after_everything_published_before_it() { diff --git a/core/src/connectors.rs b/core/src/connectors.rs index 8e4aa79..1725001 100644 --- a/core/src/connectors.rs +++ b/core/src/connectors.rs @@ -25,6 +25,8 @@ use std::time::{Duration, Instant}; use serde_json::{Map, Value}; use crate::bus; +use crate::metrics::{self, Kind, Span}; +use crate::trace; // ───────────────────────── config & context ───────────────────────── @@ -412,15 +414,19 @@ fn handle_http_in( ("403 Forbidden", format!("{{\"error\":\"subject {suffix:?} not permitted by ALLOW\"}}")) } else { let subject = format!("{subj_root}.{suffix}"); - match js.publish(&subject, body) { - Ok(_) => { - trace_pub(name, &subject, body); - ("202 Accepted", format!("{{\"published\":\"{subject}\"}}")) - } - Err(e) => { - trace_fail(name, &subject, format!("publish: {e}")); - ("502 Bad Gateway", format!("{{\"error\":\"{e}\"}}")) - } + // A caller that traces sends its context; the event's trace + // then starts in the caller's (ADR-0034). + // (The head is decoded on its own: an index into the lossy + // text of the whole buffer could fall inside a character.) + let head = String::from_utf8_lossy(&buf[..header_end.unwrap_or(0).min(buf.len())]); + let incoming = header_value(&head, trace::TRACEPARENT) + .and_then(|tp| trace::Context::parse(tp, header_value(&head, trace::TRACESTATE))); + match source_publish(name, js, &subject, body, incoming, Kind::Server) { + (hop, Ok(_)) => ( + "202 Accepted", + format!("{{\"published\":\"{subject}\",\"trace_id\":\"{}\"}}", hop.trace_hex()), + ), + (_, Err(e)) => ("502 Bad Gateway", format!("{{\"error\":\"{e}\"}}")), } } } @@ -438,6 +444,14 @@ fn handle_http_in( } } +/// A request header's value, its name matched without regard to case. +fn header_value<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.split("\r\n").skip(1).find_map(|line| { + let (k, v) = line.split_once(':')?; + k.trim().eq_ignore_ascii_case(name).then(|| v.trim()) + }) +} + fn content_length(head: &str) -> usize { for line in head.lines() { if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { @@ -489,10 +503,9 @@ impl Driver for Timer { waited = 0; let bytes = serde_json::to_vec(&stamp_ts(&payload, crate::now_secs())) .unwrap_or_default(); - if let Err(e) = js.publish(&subject, &bytes) { + if let (_, Err(e)) = source_publish(&ctx.name, &js, &subject, &bytes, None, Kind::Producer) { return Err(format!("publish: {e}")); } - trace_pub(&ctx.name, &subject, &bytes); } } } @@ -547,8 +560,7 @@ impl Driver for HttpPoll { } else { raw.clone() }; - let _ = js.publish(&subject, &bytes); - trace_pub(&ctx.name, &subject, &bytes); + let _ = source_publish(&ctx.name, &js, &subject, &bytes, None, Kind::Producer); } Err(_) => eprintln!("[{}] poll: non-JSON body, skipped", ctx.name), }, @@ -890,10 +902,9 @@ impl Driver for OAuthPoll { "body": parsed, }); let bytes = serde_json::to_vec(&envelope).unwrap_or_default(); - if let Err(e) = js.publish(&subject, &bytes) { + if let (_, Err(e)) = source_publish(&ctx.name, js, &subject, &bytes, None, Kind::Producer) { return Err(format!("publish: {e}")); } - trace_pub(&ctx.name, &subject, &bytes); Ok(()) }; for ep in &endpoints { @@ -1119,17 +1130,55 @@ pub fn trace_preview(bytes: &[u8]) -> String { String::from_utf8_lossy(bytes).chars().take(160).collect() } -/// A source publish, in the trace ring (the panel's "is it flowing?"). +/// A reply that went out, in the trace ring (the panel's "is it flowing?"). fn trace_pub(name: &str, subject: &str, bytes: &[u8]) { crate::record_trace_full( name, subject, true, None, - vec![subject.to_string()], trace_preview(bytes), None, None, + vec![subject.to_string()], trace_preview(bytes), None, None, None, ); } /// A source-side failure worth showing in the panel. fn trace_fail(name: &str, subject: &str, err: String) { - crate::record_trace_full(name, subject, false, Some(err), vec![], String::new(), None, None); + crate::record_trace_full(name, subject, false, Some(err), vec![], String::new(), None, None, None); +} + +/// Publish what a source let in, as the first hop of its trace (ADR-0034): a +/// new trace, or the caller's when the request carried one. The message +/// carries the trace on; the hop's span is a PRODUCER (a SERVER for http-in), +/// and the trace ring records the publish or its failure. +fn source_publish( + name: &str, + js: &bus::JetStream, + subject: &str, + bytes: &[u8], + incoming: Option, + kind: Kind, +) -> (trace::Hop, Result) { + let hop = trace::Hop::begin(incoming); + let start_nanos = metrics::now_nanos(); + let published = js.publish_traced(subject, bytes, &hop.context()); + if metrics::wants(hop.sampled, published.is_err()) { + let mut span = Span::hop(&hop, kind, name, start_nanos).messaging("send", subject); + if kind == Kind::Server { + span = span.attr("http.request.method", "POST"); + } + metrics::span(match &published { + Ok(_) => span, + Err(e) => span.failed(format!("publish: {e}")), + }); + } + match &published { + Ok(_) => crate::record_trace_full( + name, subject, true, None, + vec![subject.to_string()], trace_preview(bytes), None, None, Some(&hop), + ), + Err(e) => crate::record_trace_full( + name, subject, false, Some(format!("publish: {e}")), + vec![], String::new(), None, None, Some(&hop), + ), + } + (hop, published) } /// A sink's response-body summary (what the downstream API answered). @@ -1190,10 +1239,11 @@ pub fn to_dlq( last_error: &str, payload: &[u8], version: &str, + trace: Option<&trace::Context>, ) -> Result<(), String> { ensure_dlq_stream(js); let now = epoch_secs(); - let body = serde_json::to_vec(&serde_json::json!({ + let mut envelope = serde_json::json!({ "original_subject": subject, "unit": unit, "attempts": attempts, @@ -1207,11 +1257,22 @@ pub fn to_dlq( // Raw text of the original message — replayed verbatim, so JSON and // non-JSON alike re-inject faithfully; the panel pretty-prints it if JSON. "payload": String::from_utf8_lossy(payload), - })) - .map_err(|e| e.to_string())?; + }); + // The trace the message died in (ADR-0034): a replay continues it, so the + // death and the second chance read as one story. Never at the cost of the + // letter: if its 70 bytes push the envelope past the server's limit, the + // letter goes without it. + let mut body = serde_json::to_vec(&envelope).map_err(|e| e.to_string())?; + if let Some(t) = trace { + envelope["traceparent"] = t.traceparent().into(); + let traced = serde_json::to_vec(&envelope).map_err(|e| e.to_string())?; + if traced.len() <= js.max_payload() { + body = traced; + } + } let dlq_subject = format!("{DLQ_ROOT}.{}", dlq_unit_token(unit)); js.publish(&dlq_subject, body).map_err(|e| e.to_string())?; - announce_dead_letter(js, unit, subject, attempts, version); + announce_dead_letter(js, unit, subject, attempts, version, trace); Ok(()) } @@ -1233,6 +1294,9 @@ struct DlqAnnouncement { subject: String, attempts: i64, version: String, + /// The trace of the last letter: the event continues it, so whatever it + /// wakes shows up in that trace. + trace: Option, } static DLQ_ANNOUNCEMENTS: OnceLock>> = OnceLock::new(); @@ -1259,7 +1323,7 @@ fn take_due_dlq_events( pending: &mut HashMap, now: u64, gap: u64, -) -> Vec { +) -> Vec<(Value, Option)> { pending .iter_mut() .filter(|(_, a)| a.count > 0 && now.saturating_sub(a.last_sent) >= gap) @@ -1268,29 +1332,42 @@ fn take_due_dlq_events( "transition": "dead-lettered", "ts": now, "unit": unit, "subject": a.subject, "attempts": a.attempts, "version": a.version, "count": a.count, + "trace_id": a.trace.as_ref().map(|t| format!("{:032x}", t.trace_id)), }); a.last_sent = now; a.count = 0; - event + (event, a.trace.take()) }) .collect() } /// Best-effort, like the proposal events: the letter is stored and the caller /// goes on to ack, whatever happens to its announcement. -fn publish_dlq_event(js: &bus::JetStream, event: &Value) { +fn publish_dlq_event(js: &bus::JetStream, (event, trace): &(Value, Option)) { let body = serde_json::to_vec(event).unwrap_or_default(); - if let Err(e) = js.publish(&dlq_events_subject(), body) { + let published = match trace { + Some(trace) => js.publish_traced(&dlq_events_subject(), body, trace), + None => js.publish(&dlq_events_subject(), body), + }; + if let Err(e) = published { eprintln!("[vejas] dead-letter event not published: {e}"); } } +/// What the announcement keeps of a letter's trace: the ids, not the caller's +/// `tracestate`. That is text from outside, and the event holds only what the +/// runtime wrote. +fn announced_trace(trace: Option<&trace::Context>) -> Option { + trace.map(|t| trace::Context { state: None, ..t.clone() }) +} + fn announce_dead_letter( js: &bus::JetStream, unit: &str, subject: &str, attempts: i64, version: &str, + trace: Option<&trace::Context>, ) { // A reader of these events that keeps failing dead-letters them in turn. If // that were announced too, the reader would feed itself forever. @@ -1305,6 +1382,7 @@ fn announce_dead_letter( a.subject = subject.to_string(); a.attempts = attempts; a.version = version.to_string(); + a.trace = announced_trace(trace); take_due_dlq_events(&mut pending, epoch_secs(), gap) }; for event in &due { @@ -1416,10 +1494,14 @@ pub fn audit_recent( /// Shared sink loop: durable pull consumer -> handler; ack on Ok, nak on Err. /// The handler may return a response summary, recorded in the trace ring so /// the panel shows what the downstream answered (rejected facts, skips…). +/// The sink loop. `handler` does the side effect for one message and gets the +/// trace context to hand on (ADR-0034): an HTTP sink sends it as `traceparent`, +/// an exec sink as `TRACEPARENT` in the child's environment, so a downstream +/// system that traces hangs its spans under the sink's. fn run_sink( ctx: &Ctx, subject: &str, - handler: impl Fn(&[u8]) -> Result, String>, + handler: impl Fn(&[u8], &trace::Context) -> Result, String>, ) -> Result<(), String> { let js = ctx.jetstream()?; let durable = ctx.name.replace([':', '.', '-'], "_"); @@ -1427,6 +1509,17 @@ fn run_sink( let _ = js.create_pull_consumer(&ctx.stream, &durable, &filter, ack_wait(), None); let sub = js.pull_durable(&ctx.stream, &durable, Some(subject))?; eprintln!("[{}] consuming {subject}", ctx.name); + // The span of one delivery: kind CLIENT, as the runtime is the client of + // the system the sink delivers to. + let sink_span = |hop: &trace::Hop, msg: &bus::Message, start_nanos: u128| { + let mut span = Span::hop(hop, Kind::Client, &ctx.name, start_nanos).messaging("process", &msg.subject); + if let Some(d) = msg.delivery() { + span = span + .attr("messaging.message.id", d.stream_seq.to_string()) + .attr("vejas.delivery.attempt", d.delivered); + } + span + }; loop { if !ctx.alive() { return Ok(()); @@ -1436,41 +1529,40 @@ fn run_sink( // stopped mid-batch: leave the message un-acked, it redelivers return Ok(()); } + let hop = trace::Hop::begin(trace::of(&msg)); + let carried = hop.context(); let preview = trace_preview(&msg.data); let t0 = Instant::now(); - let start_nanos = crate::metrics::now_nanos(); - match handler(&msg.data) { + let start_nanos = metrics::now_nanos(); + match handler(&msg.data, &carried) { Ok(response) => { - crate::metrics::observe(&ctx.name, true, 0, t0.elapsed().as_secs_f64()); - crate::metrics::span(crate::metrics::Span { - unit: ctx.name.clone(), subject: subject.to_string(), ok: true, - error: None, start_nanos, end_nanos: crate::metrics::now_nanos(), emits: 0, - }); + metrics::observe(&ctx.name, true, 0, t0.elapsed().as_secs_f64()); + if metrics::wants(hop.sampled, false) { + metrics::span(sink_span(&hop, &msg, start_nanos)); + } crate::record_trace_full( - &ctx.name, subject, true, None, vec![], preview, None, response, + &ctx.name, subject, true, None, vec![], preview, None, response, Some(&hop), ); let _ = msg.ack(); } Err(e) => { - crate::metrics::observe(&ctx.name, false, 0, t0.elapsed().as_secs_f64()); - crate::metrics::span(crate::metrics::Span { - unit: ctx.name.clone(), subject: subject.to_string(), ok: false, - error: Some(e.clone()), start_nanos, end_nanos: crate::metrics::now_nanos(), emits: 0, - }); + metrics::observe(&ctx.name, false, 0, t0.elapsed().as_secs_f64()); // poison guard: give up after MAX_DELIVERIES attempts let delivered = msg.delivery().map(|i| i.delivered).unwrap_or(1); + let mut dead_lettered = false; if delivered >= crate::MAX_DELIVERIES { // Poison: park it in the DLQ, then ack — publish before ack // so it is never lost (ADR-0015). On DLQ failure, nak. - match to_dlq(&js, &ctx.name, subject, delivered, &e, &msg.data, "") { + match to_dlq(&js, &ctx.name, subject, delivered, &e, &msg.data, "", Some(&carried)) { Ok(()) => { - crate::metrics::inc_dead_letter(&ctx.name); + dead_lettered = true; + metrics::inc_dead_letter(&ctx.name); eprintln!("[{}] {e} -> DLQ after {delivered} deliveries", ctx.name); crate::record_trace_full( &ctx.name, subject, false, Some(format!("{e} — dead-lettered after {delivered} deliveries")), - vec![], preview, None, None, + vec![], preview, None, None, Some(&hop), ); let _ = msg.ack(); } @@ -1479,7 +1571,7 @@ fn run_sink( crate::record_trace_full( &ctx.name, subject, false, Some(format!("{e} — DLQ publish failed: {de}")), - vec![], preview, None, None, + vec![], preview, None, None, Some(&hop), ); let _ = msg.nak(); } @@ -1487,10 +1579,15 @@ fn run_sink( } else { eprintln!("[{}] {e} -> nak", ctx.name); crate::record_trace_full( - &ctx.name, subject, false, Some(e), vec![], preview, None, None, + &ctx.name, subject, false, Some(e.clone()), vec![], preview, None, None, Some(&hop), ); let _ = msg.nak(); } + if metrics::tracing() { + let span = sink_span(&hop, &msg, start_nanos); + let span = if dead_lettered { span.attr("vejas.dlq", true) } else { span }; + metrics::span(span.failed(e)); + } } } } @@ -1513,7 +1610,7 @@ impl Driver for SlackOut { .or_else(|| std::env::var("SLACK_WEBHOOK_URL").ok()) .unwrap_or_default(); let name = ctx.name.clone(); - run_sink(ctx, &subject, move |data| { + run_sink(ctx, &subject, move |data, trace| { let text = serde_json::from_slice::(data) .ok() .and_then(|v| v["text"].as_str().map(|s| s.to_string())) @@ -1524,7 +1621,7 @@ impl Driver for SlackOut { } else { let payload = serde_json::json!({ "text": text }).to_string(); let headers = [("Content-Type".to_string(), "application/json".to_string())]; - http_post(&webhook, &headers, payload.as_bytes()).map(|b| summarize(&b)) + http_post(&webhook, &headers, payload.as_bytes(), Some(trace)).map(|b| summarize(&b)) } }) } @@ -1570,7 +1667,9 @@ impl Driver for HttpOut { if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { headers.push(("Content-Type".into(), "application/json".into())); } - run_sink(ctx, &subject, move |data| http_post(&url, &headers, data).map(|b| summarize(&b))) + run_sink(ctx, &subject, move |data, trace| { + http_post(&url, &headers, data, Some(trace)).map(|b| summarize(&b)) + }) } } @@ -1619,8 +1718,7 @@ impl Driver for ExecSource { continue; } if serde_json::from_slice::(line).is_ok() { - let _ = js.publish(&subject, line); - trace_pub(&ctx.name, &subject, line); + let _ = source_publish(&ctx.name, &js, &subject, line, None, Kind::Producer); } else { eprintln!("[{}] exec: non-JSON line skipped", ctx.name); } @@ -1643,9 +1741,13 @@ impl Driver for ExecSink { let subject = ctx.subject(&ctx.config.str("SUBJECT").ok_or("SUBJECT required")?); let name = ctx.name.clone(); let env = ctx.config.env_vars(); - run_sink(ctx, &subject, move |data| { + run_sink(ctx, &subject, move |data, trace| { let mut child = shell(&cmd) .envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str()))) + // The OpenTelemetry carrier for a child process: a program that + // traces picks its parent up from here (ADR-0034). + .env("TRACEPARENT", trace.traceparent()) + .env("TRACESTATE", trace.state.as_deref().unwrap_or("")) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) @@ -1766,9 +1868,8 @@ impl Driver for ExecStreamSource { continue; } if let Ok(rec) = serde_json::from_str::(line) { - match js.publish(&subject, line) { + match source_publish(&ctx.name, &js, &subject, line.as_bytes(), None, Kind::Producer).1 { Ok(_) => { - trace_pub(&ctx.name, &subject, line.as_bytes()); // publish-before-commit: advance the offset in // MEMORY only after the record is on the bus; the // cadence loop (above) writes it to KV. No KV put @@ -1781,9 +1882,8 @@ impl Driver for ExecStreamSource { } } } - Err(e) => { - trace_fail(&ctx.name, &subject, format!("publish: {e}")) - } + // recorded in the ring by source_publish + Err(_) => {} } } else { eprintln!("[{}] stream: non-JSON line skipped", ctx.name); @@ -1940,9 +2040,9 @@ impl Driver for MqttIn { // publish-before-ack: bus first (await JetStream pub-ack), // THEN PUBACK — a crash before the bus write re-delivers // from the broker (ADR-0025). - js.publish(&subject, &payload) + source_publish(&ctx.name, &js, &subject, &payload, None, Kind::Producer) + .1 .map_err(|e| format!("bus publish: {e}"))?; - trace_pub(&ctx.name, &subject, &payload); if pq > 0 { client.puback(pid)?; } @@ -1992,7 +2092,8 @@ impl Driver for MqttOut { // one MQTT session, reconnected on error (Mutex> for the Fn handler) let slot: std::sync::Mutex>> = std::sync::Mutex::new(None); - run_sink(ctx, &subject, move |data| { + // MQTT 3.1.1 has no headers: the trace stops at the broker. + run_sink(ctx, &subject, move |data, _trace| { let mut guard = slot.lock().unwrap(); if guard.is_none() { *guard = Some(mqtt_connect( @@ -2197,7 +2298,31 @@ fn http_get(url: &str, headers: &[(String, String)]) -> Result, String> } } -fn http_post(url: &str, headers: &[(String, String)], body: &[u8]) -> Result, String> { +/// POST for the sinks. With a trace, the request carries it as `traceparent` +/// (and `tracestate`), replacing any the manifest set (ADR-0034). +fn http_post( + url: &str, + headers: &[(String, String)], + body: &[u8], + trace: Option<&trace::Context>, +) -> Result, String> { + let traced: Vec<(String, String)>; + let headers = match trace { + Some(trace) => { + let is_trace = |k: &str| { + k.eq_ignore_ascii_case(trace::TRACEPARENT) || k.eq_ignore_ascii_case(trace::TRACESTATE) + }; + let mut h: Vec<(String, String)> = + headers.iter().filter(|(k, _)| !is_trace(k)).cloned().collect(); + h.push((trace::TRACEPARENT.into(), trace.traceparent())); + if let Some(state) = &trace.state { + h.push((trace::TRACESTATE.into(), state.clone())); + } + traced = h; + &traced[..] + } + None => headers, + }; match http_request("POST", url, headers, Some(body))? { (code, out) if (200..300).contains(&code) => Ok(out), (code, out) => Err(format!( @@ -2283,16 +2408,44 @@ mod tests { letter(&mut pending, "flow:a"); let first = take_due_dlq_events(&mut pending, 1000, 60); assert_eq!(first.len(), 1, "the first letter is news at once"); - assert_eq!(first[0]["count"], 1); + assert_eq!(first[0].0["count"], 1); for _ in 0..3 { letter(&mut pending, "flow:a"); } assert!(take_due_dlq_events(&mut pending, 1030, 60).is_empty(), "inside the window"); let held = take_due_dlq_events(&mut pending, 1060, 60); - assert_eq!(held[0]["count"], 3, "the window delays news, it loses none"); + assert_eq!(held[0].0["count"], 3, "the window delays news, it loses none"); assert!(take_due_dlq_events(&mut pending, 2000, 60).is_empty(), "nothing pending"); } + #[test] + fn the_event_carries_the_trace_of_the_last_letter() { + let mut pending = HashMap::new(); + letter(&mut pending, "flow:t"); + let tp = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + let caller = trace::Context::parse(tp, Some("vendor=text from outside")).unwrap(); + let kept = announced_trace(Some(&caller)).unwrap(); + assert_eq!((kept.trace_id, kept.span_id), (caller.trace_id, caller.span_id)); + assert_eq!(kept.state, None, "the caller's tracestate is not announced"); + pending.get_mut("flow:t").unwrap().trace = Some(kept); + let due = take_due_dlq_events(&mut pending, 1000, 0); + assert_eq!(due[0].0["trace_id"], "4bf92f3577b34da6a3ce929d0e0e4736"); + assert_eq!(due[0].1.as_ref().map(|t| t.traceparent()).as_deref(), Some(tp)); + letter(&mut pending, "flow:t"); + let next = take_due_dlq_events(&mut pending, 2000, 0); + assert!(next[0].1.is_none() && next[0].0["trace_id"].is_null(), "taken once, not repeated"); + } + + #[test] + fn a_request_header_is_found_whatever_its_case() { + let head = "POST /ingest/orders HTTP/1.1\r\nHost: x\r\nTraceParent: 00-ab \r\nContent-Length: 2\r\n\r\n"; + assert_eq!(header_value(head, "traceparent"), Some("00-ab")); + assert_eq!(header_value(head, "content-length"), Some("2")); + assert_eq!(header_value(head, "tracestate"), None); + // The request line is not a header, whatever it holds. + assert_eq!(header_value("GET /a:b HTTP/1.1\r\n\r\n", "get /a"), None); + } + #[test] fn units_are_windowed_apart_and_zero_means_every_letter() { let mut pending = HashMap::new(); @@ -2302,7 +2455,7 @@ mod tests { letter(&mut pending, "flow:b"); let due = take_due_dlq_events(&mut pending, 1001, 60); assert_eq!(due.len(), 1); - assert_eq!(due[0]["unit"], "flow:b"); + assert_eq!(due[0].0["unit"], "flow:b"); assert_eq!(take_due_dlq_events(&mut pending, 1001, 0).len(), 1, "gap 0 lets flow:a through"); } diff --git a/core/src/control.rs b/core/src/control.rs index 321e7d9..94eeca1 100644 --- a/core/src/control.rs +++ b/core/src/control.rs @@ -80,7 +80,7 @@ fn supervise(registry: Registry, root: PathBuf, tenant: String) { crate::record_trace_full( "control", &cmd_subj, ok, (!ok).then(|| reply["error"].as_str().unwrap_or("error").to_string()), - vec![], format!("{cmd} {summary}"), None, None, + vec![], format!("{cmd} {summary}"), None, None, None, ); let _ = nc.publish( &audit_subj, diff --git a/core/src/main.rs b/core/src/main.rs index e36394f..d3a6587 100644 --- a/core/src/main.rs +++ b/core/src/main.rs @@ -32,6 +32,7 @@ mod metrics; mod mqtt; mod proposals; mod secrets; +mod trace; mod versions; mod vjs; @@ -123,6 +124,7 @@ fn clear_rotation(reference: &str) { .remove(reference); } +#[allow(clippy::too_many_arguments)] pub fn record_trace( flow: &str, subject: &str, @@ -131,8 +133,9 @@ pub fn record_trace( emits: Vec, preview: String, event: Option, + trace: Option<&trace::Hop>, ) { - record_trace_full(flow, subject, ok, error, emits, preview, event, None) + record_trace_full(flow, subject, ok, error, emits, preview, event, None, trace) } /// Full form: `response` carries a sink's response-body summary (what the @@ -148,14 +151,21 @@ pub fn record_trace_full( preview: String, event: Option, response: Option, + trace: Option<&trace::Hop>, ) { + // The trace this hop belongs to (ADR-0034): what an operator copies into + // the tracing backend to see the whole path of this event. + let (trace_id, span_id) = match trace { + Some(hop) => (Some(hop.trace_hex()), Some(format!("{:016x}", hop.span_id))), + None => (None, None), + }; let seq = TRACE_SEQ.fetch_add(1, Ordering::SeqCst); let mut map = TRACES.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap(); let ring = map.entry(unit.to_string()).or_default(); ring.push_back(json!({ "seq": seq, "ts": now_secs(), "flow": unit, "subject": subject, "ok": ok, "error": error, "emits": emits, "preview": preview, - "response": response, + "response": response, "trace_id": trace_id, "span_id": span_id, // the full event, kept for shadow-replay; stripped from /events output "event": event, })); @@ -1120,6 +1130,9 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { // Cluster-wide overlay (ADR-0021): a promoted version overrides the // file iff it forked from exactly this baseline; a stale overlay // (baseline advanced / flow git-deleted) is evicted here — git wins. + // The git baseline's hash when a promoted version overrides it: the + // spans carry both (ADR-0034), the version being the provenance key. + let mut overlay_of: Option = None; let src = { let vconn = bus::connect(&url).ok().map(|bus| bus.jetstream()); let vstore = vconn.as_ref().and_then(versions::open_store); @@ -1131,6 +1144,7 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { ); match outcome { versions::Outcome::Overlay => { + overlay_of = Some(versions::hash_content(&baseline)); eprintln!("[vejas] {} on a promoted version (overlay)", handle.spec.name) } versions::Outcome::Evicted { parent, baseline: base_hash } => { @@ -1239,6 +1253,14 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { // redelivers to whoever holds the durable next return Ok(()); } + // The hop continues the trace the message carries, or starts + // one; its emits and its dead letter carry it on (ADR-0034). + let hop = trace::Hop::begin(trace::of(&msg)); + let carried = hop.context(); + let exporting = metrics::tracing(); + // A sampled-out hop builds no span, unless it fails. + let traced = exporting && hop.sampled; + let start_nanos = metrics::now_nanos(); let event: Value = match serde_json::from_slice(&msg.data) { Ok(v) => v, Err(e) => { @@ -1251,24 +1273,30 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { let prev: String = String::from_utf8_lossy(&msg.data).chars().take(160).collect(); metrics::observe(&handle.spec.name, false, 0, 0.0); - match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &err, &msg.data, &flow_version) { + let dead = connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &err, &msg.data, &flow_version, Some(&carried)); + match &dead { Ok(()) => { metrics::inc_dead_letter(&handle.spec.name); record_trace(&handle.spec.name, &msg.subject, false, - Some(format!("{err} — dead-lettered")), vec![], prev, None); + Some(format!("{err} — dead-lettered")), vec![], prev, None, Some(&hop)); let _ = msg.ack(); } Err(de) => { record_trace(&handle.spec.name, &msg.subject, false, - Some(format!("{err} — DLQ publish failed: {de}")), vec![], prev, None); + Some(format!("{err} — DLQ publish failed: {de}")), vec![], prev, None, Some(&hop)); let _ = msg.nak(); } } + if exporting { + let span = hop_span(&hop, &handle.spec.name, &msg, &flow_version, overlay_of.as_deref(), start_nanos); + metrics::span(if dead.is_ok() { span.attr("vejas.dlq", true) } else { span }.failed(err)); + } continue; } }; let t0 = Instant::now(); - let start_nanos = metrics::now_nanos(); + // Each `invoke` leaves a span under the hop, while spans are exported. + engine.trace_under(traced.then_some(&hop)); // Holding an emit is local, so a refusal is final for this message: // it can never leave, however often it redelivers. That makes it // a failed run, capped by MAX_DELIVERIES and dead-lettered. @@ -1276,23 +1304,27 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { for (subj, payload) in &ctx.emits { let bytes = serde_json::to_vec(payload).unwrap_or_default(); // held; sent and confirmed once per batch below - batch.publish(subj, bytes).map_err(|e| format!("publish {subj}: {e}"))?; + batch + .publish_traced(subj, bytes, &carried) + .map_err(|e| format!("publish {subj}: {e}"))?; } Ok(ctx) }); + if traced { + for invoked in engine.take_spans() { + metrics::span(invoke_span(&handle.spec.name, invoked)); + } + } match outcome { Ok(ctx) => { let emits = ctx.emits.len() as u64; metrics::observe(&handle.spec.name, true, emits, t0.elapsed().as_secs_f64()); - metrics::span(metrics::Span { - unit: handle.spec.name.clone(), - subject: msg.subject.clone(), - ok: true, - error: None, - start_nanos, - end_nanos: metrics::now_nanos(), - emits, - }); + if traced { + metrics::span( + hop_span(&hop, &handle.spec.name, &msg, &flow_version, overlay_of.as_deref(), start_nanos) + .attr("vejas.emits", emits), + ); + } record_trace( &handle.spec.name, &msg.subject, @@ -1304,47 +1336,46 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { // message a second walk of its JSON. String::new(), Some(event), + Some(&hop), ); to_ack.push(msg); // acked after the batch flush } Err(e) => { eprintln!("[vejas] {}: {e}", handle.spec.name); metrics::observe(&handle.spec.name, false, 0, t0.elapsed().as_secs_f64()); - metrics::span(metrics::Span { - unit: handle.spec.name.clone(), - subject: msg.subject.clone(), - ok: false, - error: Some(e.clone()), - start_nanos, - end_nanos: metrics::now_nanos(), - emits: 0, - }); // poison guard: past MAX_DELIVERIES the message is // dead-lettered (ADR-0015) rather than dropped; publish // before ack, nak if the DLQ write fails. let delivered = msg.delivery().map(|i| i.delivered).unwrap_or(1); + let mut dead_lettered = false; if delivered >= MAX_DELIVERIES { - match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &e, &msg.data, &flow_version) { + match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &e, &msg.data, &flow_version, Some(&carried)) { Ok(()) => { + dead_lettered = true; metrics::inc_dead_letter(&handle.spec.name); record_trace(&handle.spec.name, &msg.subject, false, Some(format!("{e} — dead-lettered after {delivered} deliveries")), - vec![], String::new(), Some(event.clone())); + vec![], String::new(), Some(event.clone()), Some(&hop)); let _ = msg.ack(); } Err(de) => { record_trace(&handle.spec.name, &msg.subject, false, Some(format!("{e} — DLQ publish failed: {de}")), - vec![], String::new(), Some(event.clone())); + vec![], String::new(), Some(event.clone()), Some(&hop)); let _ = msg.nak(); } } } else { record_trace(&handle.spec.name, &msg.subject, false, Some(e.clone()), - vec![], String::new(), Some(event.clone())); + vec![], String::new(), Some(event.clone()), Some(&hop)); // no ack -> redelivery after ack_wait } + if exporting { + let span = hop_span(&hop, &handle.spec.name, &msg, &flow_version, overlay_of.as_deref(), start_nanos); + let span = if dead_lettered { span.attr("vejas.dlq", true) } else { span }; + metrics::span(span.failed(e.clone())); + } set_state(&handle, |st| st.last_error = Some(e)); } } @@ -1395,6 +1426,46 @@ fn supervise_vjs(handle: Arc, root: PathBuf) { }); } +/// The span of one hop of a flow or detect unit on the bus (ADR-0034): kind +/// CONSUMER, its parent the span that published the message. +fn hop_span( + hop: &trace::Hop, + unit: &str, + msg: &bus::Message, + version: &str, + baseline: Option<&str>, + start_nanos: u128, +) -> metrics::Span { + let mut span = metrics::Span::hop(hop, metrics::Kind::Consumer, unit, start_nanos) + .messaging("process", &msg.subject); + if !version.is_empty() { + span = span.attr("vejas.flow.version", version); + } + if let Some(baseline) = baseline { + span = span.attr("vejas.flow.baseline", baseline); + } + if let Some(d) = msg.delivery() { + span = span + .attr("messaging.message.id", d.stream_seq.to_string()) + .attr("vejas.delivery.attempt", d.delivered); + } + span +} + +/// An `invoke` a hop made, as a span under the hop (or under the invoke that +/// made it). +fn invoke_span(unit: &str, invoked: vjs::InvokeSpan) -> metrics::Span { + let mut span = metrics::Span::hop(&invoked.hop, metrics::Kind::Internal, unit, invoked.start_nanos) + .attr("code.function.name", invoked.service.clone()) + .attr("code.file.path", invoked.file); + span.name = format!("invoke {}", invoked.service); + span.end_nanos = invoked.end_nanos; + match invoked.error { + Some(e) => span.failed(e), + None => span, + } +} + /// Where a detect unit publishes an emit: the subject its `.to()` names, else /// `.detect..`. fn emit_subject(emit: &varpulis_engine::Emit, subj_root: &str, stem: &str) -> String { @@ -1630,13 +1701,25 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { if idle_grace.is_some() { match program.tick() { Ok(emits) if !emits.is_empty() => { + // No message stands behind a window that time + // closed: each tick that emits starts a trace. + let hop = trace::Hop::begin(None); + let carried = hop.context(); + let start_nanos = metrics::now_nanos(); for emit in &emits { let subject = emit_subject(emit, &subj_root, &stem); - if let Err(e) = nc.publish(&subject, emit.to_payload()) { + if let Err(e) = nc.publish_traced(&subject, emit.to_payload(), &carried) { eprintln!("[vejas] {}: publish {subject}: {e}", handle.spec.name); } } metrics::observe_tick_emits(&handle.spec.name, emits.len() as u64); + if metrics::tracing() && hop.sampled { + metrics::span( + metrics::Span::hop(&hop, metrics::Kind::Producer, &handle.spec.name, start_nanos) + .attr("vejas.flow.version", version.as_str()) + .attr("vejas.emits", emits.len() as u64), + ); + } } Ok(_) => {} Err(e) => eprintln!("[vejas] {}: tick: {e}", handle.spec.name), @@ -1676,6 +1759,13 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { )); }; let t0 = Instant::now(); + // The hop continues the trace of the message that closed + // or fed a window; what it emits carries it on (ADR-0034). + let hop = trace::Hop::begin(trace::of(&msg)); + let carried = hop.context(); + let exporting = metrics::tracing(); + let traced = exporting && hop.sampled; + let start_nanos = metrics::now_nanos(); // The program decodes the payload itself: its decoder // interns field names and event types once per program, // not once per message (21.6 → 5.4 µs an event). @@ -1689,7 +1779,8 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { let delivered = msg.delivery().map(|i| i.delivered).unwrap_or(1); metrics::observe(&handle.spec.name, false, 0, 0.0); - match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &err, &msg.data, &version) { + let dead = connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &err, &msg.data, &version, Some(&carried)); + match &dead { Ok(()) => { metrics::inc_dead_letter(&handle.spec.name); let _ = msg.ack(); @@ -1700,19 +1791,28 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { retrying.insert(seq); } } + if exporting { + let span = hop_span(&hop, &handle.spec.name, &msg, &version, None, start_nanos); + metrics::span(if dead.is_ok() { span.attr("vejas.dlq", true) } else { span }.failed(err)); + } } Ok(emits) => { let mut ok = true; let mut subjects = Vec::with_capacity(emits.len()); for emit in &emits { let subject = emit_subject(emit, &subj_root, &stem); - if let Err(e) = outbox.publish(&subject, emit.to_payload()) { + if let Err(e) = outbox.publish_traced(&subject, emit.to_payload(), &carried) { eprintln!("[vejas] {}: publish {subject}: {e}", handle.spec.name); ok = false; } subjects.push(subject); } metrics::observe(&handle.spec.name, ok, emits.len() as u64, t0.elapsed().as_secs_f64()); + if traced || (exporting && !ok) { + let span = hop_span(&hop, &handle.spec.name, &msg, &version, None, start_nanos) + .attr("vejas.emits", emits.len() as u64); + metrics::span(if ok { span } else { span.failed("publish failed (will redeliver)") }); + } record_trace( &handle.spec.name, &msg.subject, @@ -1721,6 +1821,7 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { subjects, connectors::trace_preview(&msg.data), None, + Some(&hop), ); if ok { to_ack.push((msg, seq)); @@ -1732,9 +1833,11 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { metrics::observe(&handle.spec.name, false, 0, t0.elapsed().as_secs_f64()); let delivered = msg.delivery().map(|i| i.delivered).unwrap_or(1); + let mut dead_lettered = false; if delivered >= MAX_DELIVERIES { - match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &e, &msg.data, &version) { + match connectors::to_dlq(&js, &handle.spec.name, &msg.subject, delivered, &e, &msg.data, &version, Some(&carried)) { Ok(()) => { + dead_lettered = true; metrics::inc_dead_letter(&handle.spec.name); let _ = msg.ack(); retrying.remove(&seq); @@ -1747,8 +1850,13 @@ fn supervise_detect(handle: Arc, _root: PathBuf) { } else { retrying.insert(seq); // left un-acked: redelivers after ack_wait } + if exporting { + let span = hop_span(&hop, &handle.spec.name, &msg, &version, None, start_nanos); + let span = if dead_lettered { span.attr("vejas.dlq", true) } else { span }; + metrics::span(span.failed(e.clone())); + } record_trace(&handle.spec.name, &msg.subject, false, Some(e.clone()), - vec![], connectors::trace_preview(&msg.data), None); + vec![], connectors::trace_preview(&msg.data), None, Some(&hop)); set_state(&handle, |st| st.last_error = Some(e)); } } @@ -3079,12 +3187,14 @@ fn dlq_audit( /// all (both None). fn dlq_replay(seq: Option, unit: Option<&str>, actor: &str) -> Result { let js = dlq_js()?; - let mut targets: Vec<(u64, String, Vec)> = Vec::new(); - let take = |env: &Value| -> (u64, String, Vec) { + let mut targets: Vec<(u64, String, Vec, Option)> = Vec::new(); + let take = |env: &Value| -> (u64, String, Vec, Option) { ( env["seq"].as_u64().unwrap_or(0), env["original_subject"].as_str().unwrap_or("").to_string(), env["payload"].as_str().unwrap_or("").as_bytes().to_vec(), + // The trace the letter died in (ADR-0034): the replay continues it. + env["traceparent"].as_str().and_then(|tp| trace::Context::parse(tp, None)), ) }; if let Some(s) = seq { @@ -3102,11 +3212,23 @@ fn dlq_replay(seq: Option, unit: Option<&str>, actor: &str) -> Result span, + Err(e) => span.failed(e.clone()), + }); + } + match published { Ok(_) => { let _ = js.delete_message(connectors::DLQ_STREAM, s); n += 1; @@ -3356,16 +3478,9 @@ fn parse_query(url: &str) -> Value { } /// Run a flow and return its full context (emits + response). -fn run_flow_ctx(root: &Path, file: &str, input: &Value) -> Result { - let path = guard_path(root, file).ok_or("path not allowed")?; - let src = fs::read_to_string(&path).map_err(|e| e.to_string())?; - let prog = vjs::parse(&src)?; - let mut engine = vjs::Engine::live(root.to_path_buf(), pkg_of_path(&path)); - vjs::run(&prog, input, &mut engine) -} - -/// Publish an API flow's side-effect emits to the bus (best-effort). -fn publish_emits(emits: &[(String, Value)]) { +/// Publish an API flow's side-effect emits to the bus (best-effort), carrying +/// the request's trace. +fn publish_emits(emits: &[(String, Value)], carried: &trace::Context) { if emits.is_empty() { return; } @@ -3373,12 +3488,24 @@ fn publish_emits(emits: &[(String, Value)]) { if let Ok(nc) = bus::connect(&url) { let mut batch = nc.batch(); for (subj, payload) in emits { - let _ = batch.publish(subj, serde_json::to_vec(payload).unwrap_or_default()); + let _ = batch.publish_traced(subj, serde_json::to_vec(payload).unwrap_or_default(), carried); } let _ = batch.confirm(); } } +/// The trace context an HTTP request carries, if any (ADR-0034). +fn request_trace(request: &tiny_http::Request) -> Option { + let header = |name: &'static str| { + request + .headers() + .iter() + .find(|h| h.field.equiv(name)) + .map(|h| h.value.as_str()) + }; + trace::Context::parse(header(trace::TRACEPARENT)?, header(trace::TRACESTATE)) +} + /// Run an API flow on the request event; map its `respond` to (status, body). /// Does the /api flow at `file` write to the bus (an `emit`, or an `invoke` of a /// service that may emit)? Used to gate read-method routes that write (Finding A, @@ -3394,32 +3521,52 @@ fn flow_writes_bus(root: &Path, file: &str) -> bool { .unwrap_or(false) } -fn run_api_flow(root: &Path, file: &str, input: &Value) -> (u16, String) { +fn run_api_flow( + root: &Path, + file: &str, + input: &Value, + method: &str, + incoming: Option, +) -> (u16, String) { // Instrument the synchronous /api path like the bus hot path (ADR-0016 // follow-up): a run-time error is `ok:false`; a `respond 4xx/5xx` is a valid // business outcome, so the flow still counts as processed. let unit = guard_path(root, file) .map(|p| flow_proc_name(&p)) .unwrap_or_else(|| file.to_string()); + // The request's trace, honoured when it carries one (ADR-0034): the flow's + // span hangs under the caller's, and its emits carry the trace on. + let hop = trace::Hop::begin(incoming); + let traced = metrics::tracing() && hop.sampled; let t0 = Instant::now(); let start_nanos = metrics::now_nanos(); - let result = run_flow_ctx(root, file, input); + let mut version = String::new(); + let mut route = String::new(); + let mut invoked = Vec::new(); + let result = (|| -> Result { + let path = guard_path(root, file).ok_or("path not allowed")?; + let src = fs::read_to_string(&path).map_err(|e| e.to_string())?; + version = versions::hash_content(&src); + let prog = vjs::parse(&src)?; + route = prog + .api + .as_deref() + .and_then(|spec| spec.split_whitespace().nth(1)) + .unwrap_or_default() + .to_string(); + let mut engine = vjs::Engine::live(root.to_path_buf(), pkg_of_path(&path)); + engine.trace_under(traced.then_some(&hop)); + let run = vjs::run(&prog, input, &mut engine); + invoked = engine.take_spans(); + run + })(); let ok = result.is_ok(); let emits = result.as_ref().map(|c| c.emits.len() as u64).unwrap_or(0); metrics::observe(&unit, ok, emits, t0.elapsed().as_secs_f64()); - metrics::span(metrics::Span { - unit: unit.clone(), - subject: format!("api:{file}"), - ok, - error: result.as_ref().err().cloned(), - start_nanos, - end_nanos: metrics::now_nanos(), - emits, - }); - match result { + let (code, body) = match &result { Ok(ctx) => { - publish_emits(&ctx.emits); - match ctx.response { + publish_emits(&ctx.emits, &hop.context()); + match &ctx.response { Some((status, body)) => { let code = status .as_u64() @@ -3434,7 +3581,27 @@ fn run_api_flow(root: &Path, file: &str, input: &Value) -> (u16, String) { } } Err(e) => (500, json!({"error": e}).to_string()), + }; + if traced || (metrics::tracing() && result.is_err()) { + for span in invoked { + metrics::span(invoke_span(&unit, span)); + } + let mut span = metrics::Span::hop(&hop, metrics::Kind::Server, &unit, start_nanos) + .attr("http.request.method", method) + .attr("http.response.status_code", code as i64) + .attr("vejas.emits", emits); + if !route.is_empty() { + span = span.attr("http.route", route); + } + if !version.is_empty() { + span = span.attr("vejas.flow.version", version); + } + if let Err(e) = result { + span = span.failed(e); + } + metrics::span(span); } + (code, body) } /// The OpenAPI 3.0 document for every `api` flow. Info configurable via env. @@ -3934,7 +4101,8 @@ fn handle_request(mut request: tiny_http::Request, registry: Registry, root: Pat ev.insert(k, Value::String(v)); } ev.insert("query".into(), parse_query(&url)); - let (code, out) = run_api_flow(&root, &file, &Value::Object(ev)); + let incoming = request_trace(&request); + let (code, out) = run_api_flow(&root, &file, &Value::Object(ev), &m, incoming); respond(request, code, out, "application/json") } None => respond( @@ -4715,6 +4883,8 @@ fn main() { } drop(reg); thread::sleep(Duration::from_millis(800)); + // The units have stopped: what they traced last leaves before the process. + metrics::otlp_flush(Duration::from_secs(3)); } #[cfg(test)] @@ -4805,8 +4975,8 @@ mod tests { "source \"vx.rp.test\"\nTH = 500\nif amount > TH:\n emit \"vx.out\", {a: amount}\nend\n", ) .unwrap(); - record_trace("flow:replay_probe", "vx.rp.test", true, None, vec!["vx.out".into()], "{}".into(), Some(json!({"amount": 700}))); - record_trace("flow:replay_probe", "vx.rp.test", true, None, vec![], "{}".into(), Some(json!({"amount": 300}))); + record_trace("flow:replay_probe", "vx.rp.test", true, None, vec!["vx.out".into()], "{}".into(), Some(json!({"amount": 700})), None); + record_trace("flow:replay_probe", "vx.rp.test", true, None, vec![], "{}".into(), Some(json!({"amount": 300})), None); let diff = replay_literal(&root, "flows/replay_probe.vjs", "TH", "-", &json!(200), 20).unwrap(); assert_eq!(diff["events"], 2); // 700 emitted before and after; 300 emits only after the change @@ -4984,7 +5154,7 @@ mod tests { #[test] fn events_json_strips_the_full_event() { - record_trace("flow:strip_probe", "vx.sp.test", true, None, vec![], "{\"a\":1}".into(), Some(json!({"a": 1}))); + record_trace("flow:strip_probe", "vx.sp.test", true, None, vec![], "{\"a\":1}".into(), Some(json!({"a": 1})), None); let out: Value = serde_json::from_str(&events_json(Some("flow:strip_probe"))).unwrap(); let entry = &out["events"][0]; assert_eq!(entry["flow"], "flow:strip_probe"); diff --git a/core/src/metrics.rs b/core/src/metrics.rs index d23b04e..438f978 100644 --- a/core/src/metrics.rs +++ b/core/src/metrics.rs @@ -1,14 +1,15 @@ //! Observability: a Prometheus `/metrics` exposition and an OTLP/HTTP-JSON span //! exporter — both hand-rolled so the runtime keeps its single-digit-MB RSS and -//! tiny binary (no `opentelemetry` crate tree). Metrics are pull-scraped; traces -//! are pushed to an OTLP collector ONLY when `OTEL_EXPORTER_OTLP_ENDPOINT` is set -//! (zero cost, no exporter thread, when it is not). +//! tiny binary (no `opentelemetry` crate tree). Metrics are pull-scraped; spans +//! are pushed to an OTLP collector ONLY when an endpoint is set +//! (`OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`): no +//! exporter thread and no span built when it is not. use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::mpsc::{sync_channel, SyncSender}; +use std::sync::mpsc::{sync_channel, RecvTimeoutError, SyncSender}; use std::sync::{Mutex, OnceLock}; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; // Histogram bucket upper bounds (seconds). A flow hop is ms-scale, so the // buckets crowd the low end; the last (+Inf) is implicit in rendering. @@ -285,6 +286,23 @@ pub fn render(gauges: &[(String, String, u64)]) -> String { )); } + out.push_str("# HELP vejas_spans_exported_total Spans the OTLP exporter delivered to the collector.\n"); + out.push_str("# TYPE vejas_spans_exported_total counter\n"); + out.push_str(&format!( + "vejas_spans_exported_total {}\n", + SPANS_EXPORTED.load(Ordering::Relaxed) + )); + out.push_str("# HELP vejas_spans_dropped_total Spans lost before the collector had them: the export queue was full, or the export failed after its retries.\n"); + out.push_str("# TYPE vejas_spans_dropped_total counter\n"); + out.push_str(&format!( + "vejas_spans_dropped_total{{reason=\"queue_full\"}} {}\n", + SPANS_DROPPED_QUEUE.load(Ordering::Relaxed) + )); + out.push_str(&format!( + "vejas_spans_dropped_total{{reason=\"export_failed\"}} {}\n", + SPANS_DROPPED_EXPORT.load(Ordering::Relaxed) + )); + out.push_str("# HELP vejas_event_duration_seconds In-process per-event processing time.\n"); out.push_str("# TYPE vejas_event_duration_seconds histogram\n"); for (unit, u) in map.iter() { @@ -314,126 +332,551 @@ pub fn render(gauges: &[(String, String, u64)]) -> String { } // ───────────────────────── OTLP/HTTP-JSON trace export ───────────────────────── +// +// One span per hop, with the parent the trace context names (ADR-0034): the +// source that let an event in, each flow it crossed, each `invoke`, each sink +// that delivered it, all under one trace id. Spans are built only while an +// exporter is configured (`tracing()`), so the hot path pays nothing for them +// otherwise; the context itself travels either way (see `trace.rs`). + +/// OpenTelemetry span kinds, numbered as OTLP numbers them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Internal = 1, + Server = 2, + Client = 3, + Producer = 4, + Consumer = 5, +} + +pub enum Attr { + Str(String), + /// A constant: no allocation on the hot path. + Static(&'static str), + Int(i64), + Bool(bool), +} + +impl From<&str> for Attr { + fn from(v: &str) -> Attr { + Attr::Str(v.to_string()) + } +} +impl From for Attr { + fn from(v: String) -> Attr { + Attr::Str(v) + } +} +impl From for Attr { + fn from(v: i64) -> Attr { + Attr::Int(v) + } +} +impl From for Attr { + fn from(v: u64) -> Attr { + Attr::Int(v.min(i64::MAX as u64) as i64) + } +} +impl From for Attr { + fn from(v: bool) -> Attr { + Attr::Bool(v) + } +} /// One finished span, queued for the background exporter. pub struct Span { - pub unit: String, - pub subject: String, - pub ok: bool, - pub error: Option, + pub name: String, + pub kind: Kind, + pub trace_id: u128, + pub span_id: u64, + pub parent: Option, + pub sampled: bool, pub start_nanos: u128, pub end_nanos: u128, - pub emits: u64, + /// The failure, if the hop failed; a success leaves the status unset, as the + /// semantic conventions ask of instrumentation. + pub error: Option, + pub attrs: Vec<(&'static str, Attr)>, +} + +impl Span { + /// The span of `hop`, named after the unit that ran it, from `start_nanos` + /// to now. + pub fn hop(hop: &crate::trace::Hop, kind: Kind, unit: &str, start_nanos: u128) -> Span { + Span { + name: unit.to_string(), + kind, + trace_id: hop.trace_id, + span_id: hop.span_id, + parent: hop.parent, + sampled: hop.sampled, + start_nanos, + end_nanos: now_nanos(), + error: None, + attrs: { + let mut attrs = Vec::with_capacity(10); + attrs.push(("vejas.unit", Attr::Str(unit.to_string()))); + attrs + }, + } + } + + pub fn attr(mut self, key: &'static str, value: impl Into) -> Span { + self.attrs.push((key, value.into())); + self + } + + /// The messaging attributes of a hop on the bus: `operation` is `process` + /// for a consumer, `send` for a producer. + pub fn messaging(mut self, operation: &'static str, subject: &str) -> Span { + self.attrs.push(("messaging.system", Attr::Static("nats"))); + self.attrs.push(("messaging.operation.type", Attr::Static(operation))); + self.attr("messaging.destination.name", subject) + } + + pub fn failed(mut self, error: impl Into) -> Span { + self.error = Some(error.into()); + self + } } static TX: OnceLock>> = OnceLock::new(); -static SPAN_SEQ: AtomicU64 = AtomicU64::new(1); - -fn id_hex(bytes: usize) -> String { - let seq = SPAN_SEQ.fetch_add(1, Ordering::Relaxed); - let n = now_nanos(); - if bytes == 16 { - // 128-bit trace id: nanos in the high half, a mixed counter in the low. - let lo = (seq).wrapping_mul(0x9E37_79B9_7F4A_7C15); - format!("{:016x}{:016x}", n as u64, lo) +static SPANS_EXPORTED: AtomicU64 = AtomicU64::new(0); +static SPANS_DROPPED_QUEUE: AtomicU64 = AtomicU64::new(0); +static SPANS_DROPPED_EXPORT: AtomicU64 = AtomicU64::new(0); + +/// Is an exporter configured? Call sites test this before building a span, so +/// that without one the hot path builds nothing (ADR-0016). +pub fn tracing() -> bool { + matches!(TX.get(), Some(Some(_))) +} + +/// Is this hop's span worth building: an exporter is configured, and the +/// sampler kept the trace or the hop failed (errors are always exported). +pub fn wants(sampled: bool, failed: bool) -> bool { + (sampled || failed) && tracing() +} + +/// Where and how spans go: the OTEL_* variables the specification defines for +/// an OTLP/HTTP exporter, the traces-specific ones first. +struct ExportConfig { + url: String, + headers: Vec<(String, String)>, + timeout: Duration, + resource: Vec<(String, String)>, + /// The batch span processor's knobs, under the specification's names. + delay: Duration, + batch: usize, + queue: usize, +} + +fn export_config(env: impl Fn(&str) -> Option) -> Option { + let var = |k: &str| env(k).filter(|v| !v.trim().is_empty()); + // The traces endpoint is used as given; the generic one gets the signal path. + let url = match var("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") { + Some(url) => url.trim().to_string(), + None => format!( + "{}/v1/traces", + var("OTEL_EXPORTER_OTLP_ENDPOINT")?.trim().trim_end_matches('/') + ), + }; + let headers = ["OTEL_EXPORTER_OTLP_TRACES_HEADERS", "OTEL_EXPORTER_OTLP_HEADERS"] + .into_iter() + .find_map(|name| var(name).map(|h| sendable_headers(key_values(&h, name), name))) + .unwrap_or_default(); + let timeout = var("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT") + .or_else(|| var("OTEL_EXPORTER_OTLP_TIMEOUT")) + .and_then(|ms| ms.trim().parse::().ok()) + .unwrap_or(10_000); + let mut resource: Vec<(String, String)> = var("OTEL_RESOURCE_ATTRIBUTES") + .map(|r| key_values(&r, "OTEL_RESOURCE_ATTRIBUTES")) + .unwrap_or_default(); + let service = var("OTEL_SERVICE_NAME") + .or_else(|| resource.iter().find(|(k, _)| k == "service.name").map(|(_, v)| v.clone())) + .unwrap_or_else(|| "vejas".to_string()); + resource.retain(|(k, _)| k != "service.name" && k != "service.version"); + resource.insert(0, ("service.name".into(), service)); + resource.insert(1, ("service.version".into(), env!("CARGO_PKG_VERSION").into())); + let number = |k: &str, default: u64| var(k).and_then(|v| v.trim().parse::().ok()).unwrap_or(default); + // 1 s rather than the specification's 5 s, so that a trace shows up while + // its sender still looks; under load a full batch leaves at once anyway. + let delay = Duration::from_millis(number("OTEL_BSP_SCHEDULE_DELAY", 1000)); + let queue = number("OTEL_BSP_MAX_QUEUE_SIZE", 4096).clamp(1, 1 << 20) as usize; + let batch = (number("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", 512).max(1) as usize).min(queue); + Some(ExportConfig { + url, + headers, + timeout: Duration::from_millis(timeout.max(1)), + resource, + delay, + batch, + queue, + }) +} + +/// `k=v,k2=v2` with percent-encoded values, the format of the OTEL_* lists. A +/// malformed entry is skipped with a warning that names the variable, never +/// the value: header values are credentials. +fn key_values(list: &str, variable: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + for entry in list.split(',').map(str::trim).filter(|e| !e.is_empty()) { + match entry.split_once('=') { + Some((k, v)) if !k.trim().is_empty() => { + out.push((percent_decode(k.trim()), percent_decode(v.trim()))) + } + _ => eprintln!("[vejas] {variable}: an entry without `key=` is skipped"), + } + } + out +} + +/// The headers an HTTP request can carry (a token for a name, visible ASCII +/// for a value). Any other is skipped here, once, with a warning that names +/// the variable and the entry's position only: sent, it would fail every +/// export, and the client's error quotes the whole header line. +fn sendable_headers(headers: Vec<(String, String)>, variable: &str) -> Vec<(String, String)> { + let token = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b); + let visible = |b: u8| b == b'\t' || (0x20..=0x7e).contains(&b); + let mut kept = Vec::with_capacity(headers.len()); + for (n, (k, v)) in headers.into_iter().enumerate() { + if !k.is_empty() && k.bytes().all(token) && v.bytes().all(visible) { + kept.push((k, v)); + } else { + eprintln!( + "[vejas] {variable}: entry {} is not a valid HTTP header and is skipped (not shown: it may hold a credential)", + n + 1 + ); + } + } + kept +} + +/// Where spans go, for the log: scheme, host and path, without the user +/// info or query that may carry a credential. +fn shown(url: &str) -> String { + let (scheme, rest) = url.split_once("://").map_or(("", url), |(s, r)| (s, r)); + let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let (authority, path) = rest.split_at(end); + let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h); + let path = path.split(['?', '#']).next().unwrap_or(""); + if scheme.is_empty() { + format!("{host}{path}") } else { - // 64-bit span id. - format!("{:016x}", (seq ^ (n as u64)).wrapping_mul(0xD6E8_FEB8_6659_FD93)) + format!("{scheme}://{host}{path}") + } +} + +fn percent_decode(s: &str) -> String { + let hex = |c: u8| (c as char).to_digit(16).map(|d| d as u8); + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + if let (Some(hi), Some(lo)) = (hex(b[i + 1]), hex(b[i + 2])) { + out.push(hi << 4 | lo); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; } + String::from_utf8_lossy(&out).into_owned() } -/// Spawn the exporter thread iff `OTEL_EXPORTER_OTLP_ENDPOINT` is set. Idempotent -/// (the OnceLock guards it). When unset, TX holds None and `span()` is a no-op. +/// Spawn the exporter thread iff an OTLP endpoint is configured. Idempotent +/// (the OnceLock guards it). Without one, TX holds None, `tracing()` is false +/// and `span()` is a no-op. pub fn otlp_init() { TX.get_or_init(|| { - let endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok()?; - let endpoint = endpoint.trim_end_matches('/').to_string(); - let url = format!("{endpoint}/v1/traces"); - let service = - std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| "vejas".to_string()); - // Bounded queue: if the collector stalls, spans are dropped (a metric - // path must never block the flow hot loop), never buffered unboundedly. - let (tx, rx) = sync_channel::(4096); - eprintln!("[vejas] OTLP traces -> {url}"); - std::thread::spawn(move || { - let agent = ureq::AgentBuilder::new() - .timeout(std::time::Duration::from_secs(5)) - .build(); - let mut batch: Vec = Vec::with_capacity(512); + let config = export_config(|k| std::env::var(k).ok())?; + // Bounded queue: if the collector stalls, spans are dropped (and + // counted), never buffered without bound, and the hot loop never waits. + let (tx, rx) = sync_channel::(config.queue); + eprintln!("[vejas] OTLP traces -> {}", shown(&config.url)); + let spawned = std::thread::Builder::new().name("otlp-export".into()).spawn(move || { + let agent = ureq::AgentBuilder::new().timeout(config.timeout).build(); + let mut batch: Vec = Vec::with_capacity(config.batch); + let mut oldest: Option = None; + let mut last_report: Option = None; loop { - // Block for the first span, then drain whatever else is queued. - match rx.recv() { - Ok(s) => batch.push(s), - Err(_) => break, // sender gone: shutdown + let flush = FLUSH_ASKED.load(Ordering::SeqCst); + if batch.is_empty() && flush <= FLUSH_DONE.load(Ordering::SeqCst) { + // Nothing pending: wait on the queue itself, so an idle + // runtime leaves this thread asleep. Only the first span + // after a quiet spell pays for waking it. + match rx.recv_timeout(IDLE_WAIT) { + Ok(s) => { + batch.push(s); + oldest = Some(Instant::now()); + } + Err(RecvTimeoutError::Timeout) => continue, + Err(RecvTimeoutError::Disconnected) => break, + } } - while batch.len() < 512 { - match rx.try_recv() { - Ok(s) => batch.push(s), - Err(_) => break, + // While spans are pending, take what is queued without waiting + // on the queue: a producer + // never has to wake this thread, so a span costs the hot path + // one push. A full batch leaves at once. + while let Ok(s) = rx.try_recv() { + batch.push(s); + oldest.get_or_insert_with(Instant::now); + if batch.len() >= config.batch { + ship(&agent, &config, &mut batch, &mut last_report); + oldest = None; } } - let body = otlp_payload(&service, &batch); - let _ = agent - .post(&url) - .set("content-type", "application/json") - .send_string(&body); - batch.clear(); + let flushing = flush > FLUSH_DONE.load(Ordering::SeqCst); + let due = oldest.is_some_and(|t| t.elapsed() >= config.delay); + if !batch.is_empty() && (flushing || due) { + ship(&agent, &config, &mut batch, &mut last_report); + oldest = None; + } + if flushing { + FLUSH_DONE.store(flush, Ordering::SeqCst); + } + std::thread::sleep(EXPORT_TICK); } }); - Some(tx) + match spawned { + Ok(_) => Some(tx), + Err(e) => { + eprintln!("[vejas] OTLP exporter not started: {e}"); + None + } + } }); } -/// Queue a finished span for export. No-op unless the exporter is enabled; never -/// blocks — a full queue drops the span rather than stalling the caller. +/// How often the exporter looks at its queue while spans are pending. At +/// 25 ms a 4096-span queue holds 160 000 spans a second. +const EXPORT_TICK: Duration = Duration::from_millis(25); +/// How long an idle exporter sleeps on its queue before it looks for a flush +/// request: a graceful stop with nothing to export waits at most this long. +const IDLE_WAIT: Duration = Duration::from_millis(250); +static FLUSH_ASKED: AtomicU64 = AtomicU64::new(0); +static FLUSH_DONE: AtomicU64 = AtomicU64::new(0); + +/// Export what is queued now and wait for it, at most `within`. Called on a +/// graceful stop: the spans of the last moments before a restart are the +/// ones an operator comes looking for. +pub fn otlp_flush(within: Duration) { + if !tracing() { + return; + } + let ticket = FLUSH_ASKED.fetch_add(1, Ordering::SeqCst) + 1; + let start = Instant::now(); + while FLUSH_DONE.load(Ordering::SeqCst) < ticket && start.elapsed() < within { + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// Export one batch, count the outcome, and say so in the log at most once a +/// minute: a dead collector must not flood it. +fn ship(agent: &ureq::Agent, config: &ExportConfig, batch: &mut Vec, last_report: &mut Option) { + let body = otlp_payload(&config.resource, batch); + let n = batch.len() as u64; + batch.clear(); + let failure = match export(agent, config, &body) { + Ok(0) => { + SPANS_EXPORTED.fetch_add(n, Ordering::Relaxed); + None + } + Ok(rejected) => { + let rejected = rejected.min(n); + SPANS_EXPORTED.fetch_add(n - rejected, Ordering::Relaxed); + SPANS_DROPPED_EXPORT.fetch_add(rejected, Ordering::Relaxed); + Some(format!("the collector rejected {rejected} of {n} spans")) + } + Err(e) => { + SPANS_DROPPED_EXPORT.fetch_add(n, Ordering::Relaxed); + Some(format!("{e}; {n} spans dropped")) + } + }; + if let Some(why) = failure { + if last_report.is_none_or(|t| t.elapsed() >= Duration::from_secs(60)) { + eprintln!("[vejas] OTLP export: {why} (vejas_spans_dropped_total counts them all)"); + *last_report = Some(Instant::now()); + } + } +} + +/// One POST, retried with backoff on what the OTLP specification calls +/// retryable (connection errors, 429, 502, 503, 504) and honouring +/// `Retry-After`. Ok carries the spans the collector said it rejected. +fn export(agent: &ureq::Agent, config: &ExportConfig, body: &str) -> Result { + const ATTEMPTS: u32 = 4; + let mut backoff = Duration::from_millis(500); + for attempt in 1..=ATTEMPTS { + let mut request = agent.post(&config.url).set("content-type", "application/json"); + for (k, v) in &config.headers { + request = request.set(k, v); + } + let wait = match request.send_string(body) { + Ok(response) => return Ok(rejected_spans(&response.into_string().unwrap_or_default())), + Err(ureq::Error::Status(code, response)) if matches!(code, 429 | 502 | 503 | 504) => { + if attempt == ATTEMPTS { + return Err(format!("HTTP {code} after {ATTEMPTS} attempts")); + } + response + .header("retry-after") + .and_then(|s| s.trim().parse::().ok()) + .map(|secs| Duration::from_secs(secs.min(30))) + .unwrap_or(backoff) + } + Err(ureq::Error::Status(code, _)) => return Err(format!("HTTP {code}")), + Err(ureq::Error::Transport(t)) => { + use ureq::ErrorKind::{ConnectionFailed, Dns, Io, ProxyConnect}; + // Only the network clears on its own; a bad header or URL does + // not, so it is not retried. + let transient = matches!(t.kind(), ConnectionFailed | Dns | Io | ProxyConnect); + if !transient || attempt == ATTEMPTS { + // The kind, and the detail only where it is the network's: + // a bad header's detail is the whole header line, which may + // be a credential, and the Display prints the URL. + return Err(match (transient, t.message()) { + (true, Some(detail)) => format!("{:?}: {detail} after {ATTEMPTS} attempts", t.kind()), + (true, None) => format!("{:?} after {ATTEMPTS} attempts", t.kind()), + (false, _) => format!("{:?}", t.kind()), + }); + } + backoff + } + }; + let jitter = Duration::from_millis(crate::trace::span_id() % 250); + std::thread::sleep(wait + jitter); + backoff *= 2; + } + unreachable!("the last attempt returns") +} + +/// `partialSuccess.rejectedSpans` of an OTLP answer, 0 when absent. +fn rejected_spans(answer: &str) -> u64 { + let Ok(v) = serde_json::from_str::(answer) else { + return 0; + }; + let r = &v["partialSuccess"]["rejectedSpans"]; + r.as_u64().or_else(|| r.as_str().and_then(|s| s.parse().ok())).unwrap_or(0) +} + +/// Queue a finished span for export. A no-op without an exporter; never +/// blocks: a full queue drops the span (counted) rather than stall the caller. +/// A span the sampler left out is not exported, unless it failed: errors and +/// dead letters are always exported, whatever the ratio. pub fn span(s: Span) { if let Some(Some(tx)) = TX.get() { - let _ = tx.try_send(s); - } -} - -fn otlp_payload(service: &str, spans: &[Span]) -> String { - let spans_json: Vec = spans - .iter() - .map(|s| { - let mut attrs = vec![ - serde_json::json!({"key":"vejas.unit","value":{"stringValue": s.unit}}), - serde_json::json!({"key":"messaging.destination.name","value":{"stringValue": s.subject}}), - serde_json::json!({"key":"vejas.emits","value":{"intValue": s.emits}}), - ]; - if let Some(e) = &s.error { - attrs.push( - serde_json::json!({"key":"error.message","value":{"stringValue": e}}), - ); + if !s.sampled && s.error.is_none() { + return; + } + if tx.try_send(s).is_err() { + SPANS_DROPPED_QUEUE.fetch_add(1, Ordering::Relaxed); + } + } +} + +/// The OTLP/HTTP JSON body for a batch, written straight into one string: the +/// exporter thread runs this for every span, and a `serde_json::Value` tree per +/// span cost several times the write. +fn otlp_payload(resource: &[(String, String)], spans: &[Span]) -> String { + use std::fmt::Write as _; + let mut out = String::with_capacity(256 + spans.len() * 640); + out.push_str(r#"{"resourceSpans":[{"resource":{"attributes":["#); + for (i, (k, v)) in resource.iter().enumerate() { + if i > 0 { + out.push(','); + } + attribute(&mut out, k, &Attr::Str(v.clone())); + } + out.push_str(r#"]},"scopeSpans":[{"scope":{"name":"vejas.runtime","version":"#); + json_string(&mut out, env!("CARGO_PKG_VERSION")); + out.push_str(r#"},"spans":["#); + for (i, s) in spans.iter().enumerate() { + if i > 0 { + out.push(','); + } + let _ = write!(out, r#"{{"traceId":"{:032x}","spanId":"{:016x}""#, s.trace_id, s.span_id); + if let Some(parent) = s.parent { + let _ = write!(out, r#","parentSpanId":"{parent:016x}""#); + } + out.push_str(r#","name":"#); + json_string(&mut out, &s.name); + let _ = write!( + out, + r#","kind":{},"startTimeUnixNano":"{}","endTimeUnixNano":"{}","attributes":["#, + s.kind as u8, + s.start_nanos, + s.end_nanos.max(s.start_nanos) + ); + for (j, (k, v)) in s.attrs.iter().enumerate() { + if j > 0 { + out.push(','); } - serde_json::json!({ - "traceId": id_hex(16), - "spanId": id_hex(8), - "name": s.unit, - // SPAN_KIND_CONSUMER: this unit consumed a message off the bus. - "kind": 5, - "startTimeUnixNano": s.start_nanos.to_string(), - "endTimeUnixNano": s.end_nanos.to_string(), - "attributes": attrs, - // status: 2 = ERROR, 1 = OK. - "status": {"code": if s.ok { 1 } else { 2 }}, - }) - }) - .collect(); - serde_json::json!({ - "resourceSpans": [{ - "resource": { - "attributes": [ - {"key":"service.name","value":{"stringValue": service}} - ] - }, - "scopeSpans": [{ - "scope": {"name": "vejas.runtime"}, - "spans": spans_json - }] - }] - }) - .to_string() + attribute(&mut out, k, v); + } + match &s.error { + Some(e) => { + let message: String = e.chars().take(1024).collect(); + if !s.attrs.is_empty() { + out.push(','); + } + attribute(&mut out, "error.type", &Attr::Static("_OTHER")); + out.push(','); + attribute(&mut out, "error.message", &Attr::Str(message.clone())); + // status code 2 = ERROR; a success leaves it unset. + out.push_str(r#"],"status":{"code":2,"message":"#); + json_string(&mut out, &message); + out.push_str("}}"); + } + None => out.push_str("]}"), + } + } + out.push_str("]}]}]}"); + out +} + +fn attribute(out: &mut String, key: &str, value: &Attr) { + out.push_str(r#"{"key":"#); + json_string(out, key); + out.push_str(r#","value":{"#); + match value { + Attr::Str(s) => { + out.push_str(r#""stringValue":"#); + json_string(out, s); + } + Attr::Static(s) => { + out.push_str(r#""stringValue":"#); + json_string(out, s); + } + // int64 travels as a decimal string in OTLP/JSON (proto3 mapping). + Attr::Int(n) => { + out.push_str(r#""intValue":""#); + out.push_str(&n.to_string()); + out.push('"'); + } + Attr::Bool(b) => out.push_str(if *b { r#""boolValue":true"# } else { r#""boolValue":false"# }), + } + out.push_str("}}"); +} + +/// A JSON string literal, escaped as RFC 8259 requires. +fn json_string(out: &mut String, s: &str) { + use std::fmt::Write as _; + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); } #[cfg(test)] @@ -467,21 +910,143 @@ mod tests { #[test] fn otlp_payload_is_valid_otlp_json() { - let s = Span { - unit: "flow:x".into(), - subject: "vx.a.b".into(), - ok: false, - error: Some("boom".into()), - start_nanos: 1, - end_nanos: 2, - emits: 3, - }; - let body = otlp_payload("vejas", &[s]); + let incoming = crate::trace::Context::parse( + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + None, + ); + let hop = crate::trace::Hop::begin(incoming); + let failed = Span::hop(&hop, Kind::Consumer, "flow:x", 1) + .messaging("process", "vx.a.b") + .attr("vejas.emits", 3u64) + .failed("boom"); + let child = hop.child(); + let ok = Span::hop(&child, Kind::Internal, "invoke p:s", 2); + let resource = vec![("service.name".to_string(), "vejas".to_string())]; + let body = otlp_payload(&resource, &[failed, ok]); let v: serde_json::Value = serde_json::from_str(&body).unwrap(); - let span = &v["resourceSpans"][0]["scopeSpans"][0]["spans"][0]; - assert_eq!(span["name"], "flow:x"); - assert_eq!(span["status"]["code"], 2); - assert_eq!(span["traceId"].as_str().unwrap().len(), 32); - assert_eq!(span["spanId"].as_str().unwrap().len(), 16); + let spans = &v["resourceSpans"][0]["scopeSpans"][0]["spans"]; + let (first, second) = (&spans[0], &spans[1]); + assert_eq!(first["name"], "flow:x"); + assert_eq!(first["kind"], 5); + assert_eq!(first["status"]["code"], 2); + assert_eq!(first["traceId"], "4bf92f3577b34da6a3ce929d0e0e4736"); + assert_eq!(first["parentSpanId"], "00f067aa0ba902b7"); + assert_eq!(first["spanId"].as_str().unwrap().len(), 16); + let attr = |span: &serde_json::Value, key: &str| { + span["attributes"] + .as_array() + .unwrap() + .iter() + .find(|a| a["key"] == key) + .map(|a| a["value"].clone()) + }; + assert_eq!(attr(first, "messaging.destination.name").unwrap()["stringValue"], "vx.a.b"); + assert_eq!(attr(first, "vejas.emits").unwrap()["intValue"], "3"); + assert_eq!(attr(first, "error.message").unwrap()["stringValue"], "boom"); + // The child hangs under the hop, in the same trace; a success leaves + // the status unset. + assert_eq!(second["traceId"], first["traceId"]); + assert_eq!(second["parentSpanId"], first["spanId"]); + assert!(second.get("status").is_none()); + assert_eq!(v["resourceSpans"][0]["resource"]["attributes"][0]["value"]["stringValue"], "vejas"); + } + + #[test] + fn the_payload_stays_json_whatever_the_strings_hold() { + let hop = crate::trace::Hop::begin(None); + let nasty = "a \"quoted\" \\ back\nline\ttab\u{1}ctl é ✓"; + let span = Span::hop(&hop, Kind::Client, nasty, 5) + .attr("vejas.note", nasty) + .attr("vejas.ok", true) + .attr("vejas.n", -3i64) + .failed(nasty); + let body = otlp_payload(&[("service.name".into(), nasty.into())], &[span]); + let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON"); + let s = &v["resourceSpans"][0]["scopeSpans"][0]["spans"][0]; + assert_eq!(s["name"], nasty); + assert_eq!(s["status"]["message"], nasty); + assert!(s.get("parentSpanId").is_none(), "a root has no parent"); + let attrs = s["attributes"].as_array().unwrap(); + let value = |k: &str| attrs.iter().find(|a| a["key"] == k).unwrap()["value"].clone(); + assert_eq!(value("vejas.note")["stringValue"], nasty); + assert_eq!(value("vejas.ok")["boolValue"], true); + assert_eq!(value("vejas.n")["intValue"], "-3"); + assert_eq!(value("error.type")["stringValue"], "_OTHER"); + assert_eq!(v["resourceSpans"][0]["resource"]["attributes"][0]["value"]["stringValue"], nasty); + // An empty batch is still a valid request body. + let empty: serde_json::Value = serde_json::from_str(&otlp_payload(&[], &[])).unwrap(); + assert_eq!(empty["resourceSpans"][0]["scopeSpans"][0]["spans"], serde_json::json!([])); + } + + #[test] + fn neither_a_bad_header_nor_a_credential_in_a_url_reaches_the_log() { + let config = export_config(|k: &str| match k { + "OTEL_EXPORTER_OTLP_ENDPOINT" => Some("http://c:4318".into()), + // a colon where `=` belongs, a control byte, then a good one + "OTEL_EXPORTER_OTLP_HEADERS" => { + Some("Authorization: Basic dXNlcjpwYXNzd29yZA==,x-bad=a%0Ab,api-key=s%3Dcret".into()) + } + _ => None, + }) + .unwrap(); + assert_eq!(config.headers, vec![("api-key".to_string(), "s=cret".to_string())]); + assert_eq!(shown("https://user:tok@collector:4318/v1/traces?key=abc"), "https://collector:4318/v1/traces"); + assert_eq!(shown("http://c:4318/v1/traces"), "http://c:4318/v1/traces"); + assert_eq!(shown("c:4318"), "c:4318"); + } + + #[test] + fn the_exporter_reads_the_otel_variables() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()) + }; + assert!(export_config(env(&[])).is_none(), "no endpoint, no exporter"); + let generic = export_config(env(&[("OTEL_EXPORTER_OTLP_ENDPOINT", "http://c:4318/")])).unwrap(); + assert_eq!(generic.url, "http://c:4318/v1/traces"); + assert_eq!(generic.timeout, Duration::from_secs(10)); + assert_eq!((generic.delay, generic.batch, generic.queue), (Duration::from_secs(1), 512, 4096)); + let tuned = export_config(env(&[ + ("OTEL_EXPORTER_OTLP_ENDPOINT", "http://c:4318"), + ("OTEL_BSP_SCHEDULE_DELAY", "200"), + ("OTEL_BSP_MAX_QUEUE_SIZE", "100"), + ("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "1000"), + ])) + .unwrap(); + assert_eq!(tuned.delay, Duration::from_millis(200)); + assert_eq!((tuned.batch, tuned.queue), (100, 100), "a batch never exceeds the queue"); + let specific = export_config(env(&[ + ("OTEL_EXPORTER_OTLP_ENDPOINT", "http://c:4318"), + ("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "https://t.example/otlp/traces"), + ("OTEL_EXPORTER_OTLP_HEADERS", "x-generic=no"), + ("OTEL_EXPORTER_OTLP_TRACES_HEADERS", "authorization=Basic%20abc%3D,x-team = ops ,broken"), + ("OTEL_EXPORTER_OTLP_TIMEOUT", "2500"), + ("OTEL_RESOURCE_ATTRIBUTES", "service.name=from-resource,deployment.environment=prod"), + ("OTEL_SERVICE_NAME", "cell-a"), + ])) + .unwrap(); + assert_eq!(specific.url, "https://t.example/otlp/traces", "the traces endpoint is used as given"); + assert_eq!( + specific.headers, + vec![("authorization".to_string(), "Basic abc=".to_string()), ("x-team".to_string(), "ops".to_string())] + ); + assert_eq!(specific.timeout, Duration::from_millis(2500)); + assert_eq!(specific.resource[0], ("service.name".to_string(), "cell-a".to_string())); + assert_eq!(specific.resource[1].0, "service.version"); + assert!(specific.resource.contains(&("deployment.environment".to_string(), "prod".to_string()))); + assert_eq!(specific.resource.iter().filter(|(k, _)| k == "service.name").count(), 1); + assert_eq!(rejected_spans(r#"{"partialSuccess":{"rejectedSpans":"3"}}"#), 3); + assert_eq!(rejected_spans(r#"{"partialSuccess":{}}"#), 0); + assert_eq!(rejected_spans(""), 0); + assert_eq!(percent_decode("a%2Cb%zz%4"), "a,b%zz%4"); + } + + #[test] + fn spans_are_neither_built_nor_counted_without_an_exporter() { + // No endpoint in the test environment: span() is a no-op. + assert!(!tracing()); + span(Span::hop(&crate::trace::Hop::begin(None), Kind::Producer, "connector:t", 0)); + let text = render(&[]); + assert!(text.contains("vejas_spans_dropped_total{reason=\"queue_full\"} 0")); + assert!(text.contains("vejas_spans_dropped_total{reason=\"export_failed\"} 0")); } } diff --git a/core/src/trace.rs b/core/src/trace.rs new file mode 100644 index 0000000..14a0287 --- /dev/null +++ b/core/src/trace.rs @@ -0,0 +1,361 @@ +//! Trace context (ADR-0034, lot A): one business event is one trace, from the +//! source that let it in to the last sink that delivered it. +//! +//! The context is the W3C `traceparent`, with `tracestate` passed on as it was +//! received. It rides every message the runtime publishes as a NATS header +//! (written and read in `bus.rs` only), every outgoing HTTP call of a connector +//! as an HTTP header, and the environment of an exec sink as `TRACEPARENT`. A +//! message that arrives without one starts a new trace, so a foreign producer +//! keeps working as it did and a foreign consumer sees a header it can ignore. +//! +//! Ids come from a splitmix64 sequence seeded once from the OS: unique within +//! a process, unpredictable across processes, and they say nothing about when +//! or where they were made. They are not secrets either: whoever reads the bus +//! reads them. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +/// The header names, as W3C Trace Context spells them. NATS keeps the case a +/// header was written with, so a reader matches them without regard to case. +pub const TRACEPARENT: &str = "traceparent"; +pub const TRACESTATE: &str = "tracestate"; + +/// What one hop hands the next: the trace, the span to hang under, and the +/// sampling decision the entry hop took. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Context { + pub trace_id: u128, + pub span_id: u64, + pub sampled: bool, + /// `tracestate` as received: a participant passes it on unchanged. + pub state: Option, +} + +impl Context { + /// Read a `traceparent` (and its `tracestate`). Version 00 exactly; a later + /// version is read for its first four fields, as the specification asks of + /// a version-00 reader. Anything else, an all-zero id included, is no + /// context at all: the hop starts a new trace. + pub fn parse(traceparent: &str, tracestate: Option<&str>) -> Option { + let s = traceparent.trim(); + if !s.is_ascii() || s.len() < 55 { + return None; + } + let b = s.as_bytes(); + let version = &s[0..2]; + if !lower_hex(version) || version == "ff" { + return None; + } + if version == "00" && s.len() != 55 { + return None; + } + if s.len() > 55 && b[55] != b'-' { + return None; + } + if b[2] != b'-' || b[35] != b'-' || b[52] != b'-' { + return None; + } + let (trace, span, flags) = (&s[3..35], &s[36..52], &s[53..55]); + if !lower_hex(trace) || !lower_hex(span) || !lower_hex(flags) { + return None; + } + let trace_id = u128::from_str_radix(trace, 16).ok()?; + let span_id = u64::from_str_radix(span, 16).ok()?; + if trace_id == 0 || span_id == 0 { + return None; + } + let flags = u8::from_str_radix(flags, 16).ok()?; + // A list over 512 characters may be cut (W3C); dropping it whole is the + // bluntest cut. The list goes on into NATS and HTTP headers and an exec + // sink's environment, so it keeps to what the W3C grammar allows there: + // printable ASCII and tabs. A line break would split a header in two, a + // NUL would make the exec sink fail to start. + let state = tracestate + .map(str::trim) + .filter(|v| { + !v.is_empty() && v.len() <= 512 && v.bytes().all(|b| b == b'\t' || (0x20..=0x7e).contains(&b)) + }) + .map(str::to_string); + Some(Context { trace_id, span_id, sampled: flags & 1 == 1, state }) + } + + pub fn traceparent(&self) -> String { + format!("00-{:032x}-{:016x}-{:02x}", self.trace_id, self.span_id, self.sampled as u8) + } +} + +fn lower_hex(s: &str) -> bool { + s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +/// The bus writes a context as its two headers (ADR-0035 keeps `bus.rs` free +/// of runtime types, so the trait lives there). +impl crate::bus::TraceContext for Context { + fn traceparent(&self) -> String { + Context::traceparent(self) + } + fn tracestate(&self) -> Option<&str> { + self.state.as_deref() + } +} + +/// The trace a consumed message belongs to, from its headers. None when it +/// has no valid `traceparent`: the hop then starts a trace. +pub fn of(message: &crate::bus::Message) -> Option { + Context::parse(message.header(TRACEPARENT)?, message.header(TRACESTATE)) +} + +/// The span of one hop: its id, the trace it belongs to, and the span it hangs +/// under (none on the hop that starts the trace). +#[derive(Clone, Debug)] +pub struct Hop { + pub trace_id: u128, + pub span_id: u64, + pub parent: Option, + pub sampled: bool, + pub state: Option, +} + +impl Hop { + /// Continue the trace `incoming` names, or start one. Sampling is decided + /// here: at the entry hop for a new trace, from the parent's flag for one + /// that continues (with the default, parent-based sampler). + pub fn begin(incoming: Option) -> Hop { + let sampler = sampler(); + match incoming { + Some(c) => Hop { + trace_id: c.trace_id, + span_id: span_id(), + parent: Some(c.span_id), + sampled: sampler.continues(c.trace_id, c.sampled), + state: c.state, + }, + None => { + let trace_id = trace_id(); + Hop { trace_id, span_id: span_id(), parent: None, sampled: sampler.starts(trace_id), state: None } + } + } + } + + /// A span under this one, in the same trace (an `invoke`). + pub fn child(&self) -> Hop { + Hop { + trace_id: self.trace_id, + span_id: span_id(), + parent: Some(self.span_id), + sampled: self.sampled, + state: self.state.clone(), + } + } + + /// What this hop hands on, to what it publishes or calls. + pub fn context(&self) -> Context { + Context { + trace_id: self.trace_id, + span_id: self.span_id, + sampled: self.sampled, + state: self.state.clone(), + } + } + + pub fn trace_hex(&self) -> String { + format!("{:032x}", self.trace_id) + } +} + +// ───────────────────────── ids ───────────────────────── + +static STATE: OnceLock = OnceLock::new(); +const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15; + +/// splitmix64 over a shared counter: distinct states give distinct outputs, so +/// no id repeats within a process before 2^64 draws. +fn next() -> u64 { + let state = STATE.get_or_init(|| AtomicU64::new(seed())); + let mut z = state.fetch_add(GAMMA, Ordering::Relaxed).wrapping_add(GAMMA); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +fn seed() -> u64 { + let mut bytes = [0u8; 8]; + if getrandom::getrandom(&mut bytes).is_ok() { + return u64::from_le_bytes(bytes); + } + // No OS randomness: the clock and the pid still keep two runtimes apart. + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0); + nanos ^ ((std::process::id() as u64) << 32) +} + +/// A span id, never zero (W3C: an all-zero id is invalid). +pub fn span_id() -> u64 { + loop { + let id = next(); + if id != 0 { + return id; + } + } +} + +/// A trace id, never zero: its low half is a span id. +pub fn trace_id() -> u128 { + ((next() as u128) << 64) | span_id() as u128 +} + +// ───────────────────────── sampling ───────────────────────── + +/// `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`, read once. The default +/// is the specification's, `parentbased_always_on`. The decision rides the +/// `sampled` flag, so every hop of a trace agrees with the entry hop; errors and +/// dead letters are exported whatever it says (see `metrics::wants`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sampler { + /// Follow the parent's flag when there is a parent. + parent_based: bool, + /// The share of new traces kept, 0.0 to 1.0. + ratio: f64, +} + +impl Sampler { + pub fn from_env(name: Option<&str>, arg: Option<&str>) -> Sampler { + let ratio = || { + arg.and_then(|a| a.trim().parse::().ok()) + .filter(|r| (0.0..=1.0).contains(r)) + .unwrap_or(1.0) + }; + match name.map(str::trim).unwrap_or("parentbased_always_on") { + "always_on" => Sampler { parent_based: false, ratio: 1.0 }, + "always_off" => Sampler { parent_based: false, ratio: 0.0 }, + "traceidratio" => Sampler { parent_based: false, ratio: ratio() }, + "parentbased_always_off" => Sampler { parent_based: true, ratio: 0.0 }, + "parentbased_traceidratio" => Sampler { parent_based: true, ratio: ratio() }, + "parentbased_always_on" | "" => Sampler { parent_based: true, ratio: 1.0 }, + other => { + eprintln!("[vejas] OTEL_TRACES_SAMPLER={other:?} is not supported; using parentbased_always_on"); + Sampler { parent_based: true, ratio: 1.0 } + } + } + } + + /// A new trace. The test is the one the OpenTelemetry SDKs make (the low + /// 64 bits of the trace id against the ratio), so a service downstream with + /// the same ratio keeps the same traces. + pub fn starts(&self, trace_id: u128) -> bool { + if self.ratio >= 1.0 { + return true; + } + if self.ratio <= 0.0 { + return false; + } + let bound = (self.ratio * (1u64 << 63) as f64) as u64; + ((trace_id as u64) >> 1) < bound + } + + pub fn continues(&self, trace_id: u128, parent_sampled: bool) -> bool { + if self.parent_based { + parent_sampled + } else { + self.starts(trace_id) + } + } +} + +fn sampler() -> Sampler { + static SAMPLER: OnceLock = OnceLock::new(); + *SAMPLER.get_or_init(|| { + Sampler::from_env( + std::env::var("OTEL_TRACES_SAMPLER").ok().as_deref(), + std::env::var("OTEL_TRACES_SAMPLER_ARG").ok().as_deref(), + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TP: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + + #[test] + fn traceparent_round_trips() { + let c = Context::parse(TP, Some("congo=t61rcWkgMzE")).expect("valid"); + assert_eq!(c.trace_id, 0x4bf92f3577b34da6a3ce929d0e0e4736); + assert_eq!(c.span_id, 0x00f067aa0ba902b7); + assert!(c.sampled); + assert_eq!(c.state.as_deref(), Some("congo=t61rcWkgMzE")); + assert_eq!(c.traceparent(), TP); + let unsampled = Context::parse(&TP.replace("-01", "-00"), None).unwrap(); + assert!(!unsampled.sampled); + assert!(unsampled.traceparent().ends_with("-00")); + } + + #[test] + fn a_bad_traceparent_is_no_context() { + for bad in [ + "", + "garbage", + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0", + "00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01", // upper case + "00-00000000000000000000000000000000-00f067aa0ba902b7-01", // zero trace + "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01", // zero span + "ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", // forbidden version + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra", // 00 has no tail + "00_4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0é", // not ASCII + ] { + assert!(Context::parse(bad, None).is_none(), "{bad:?} must not parse"); + } + // A later version is read for its first four fields. + let later = "cc-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-what-the-future-holds"; + assert_eq!(Context::parse(later, None).unwrap().span_id, 0x00f067aa0ba902b7); + // A tracestate that would break the header line is dropped, not passed on. + assert_eq!(Context::parse(TP, Some("a=1\r\nb: 2")).unwrap().state, None); + assert_eq!(Context::parse(TP, Some("a=1\0")).unwrap().state, None, "a NUL never reaches an env"); + assert_eq!(Context::parse(TP, Some("a=é")).unwrap().state, None); + assert_eq!(Context::parse(TP, Some("a=1,\tb=2")).unwrap().state.as_deref(), Some("a=1,\tb=2")); + } + + #[test] + fn a_hop_continues_or_starts_a_trace() { + let incoming = Context::parse(TP, None).unwrap(); + let hop = Hop::begin(Some(incoming.clone())); + assert_eq!(hop.trace_id, incoming.trace_id); + assert_eq!(hop.parent, Some(incoming.span_id)); + assert_ne!(hop.span_id, incoming.span_id); + let child = hop.child(); + assert_eq!((child.trace_id, child.parent), (hop.trace_id, Some(hop.span_id))); + let root = Hop::begin(None); + assert_eq!(root.parent, None); + assert_ne!(root.trace_id, 0); + assert_ne!(root.trace_id, hop.trace_id); + assert_eq!(Context::parse(&root.context().traceparent(), None), Some(root.context())); + } + + #[test] + fn ids_do_not_repeat() { + let mut seen = std::collections::HashSet::new(); + for _ in 0..10_000 { + assert!(seen.insert(span_id())); + } + } + + #[test] + fn the_sampler_follows_the_specification() { + let default = Sampler::from_env(None, None); + assert!(default.starts(trace_id())); + assert!(!default.continues(trace_id(), false), "parent-based: an unsampled parent wins"); + let off = Sampler::from_env(Some("always_off"), None); + assert!(!off.starts(trace_id()) && !off.continues(trace_id(), true)); + let half = Sampler::from_env(Some("parentbased_traceidratio"), Some("0.5")); + let kept = (0..10_000).filter(|_| half.starts(trace_id())).count(); + assert!((4_000..6_000).contains(&kept), "kept {kept} of 10000 at 0.5"); + assert!(half.continues(trace_id(), true)); + // Out of range falls back to 1.0, like an unset argument. + assert_eq!(Sampler::from_env(Some("traceidratio"), Some("7")).ratio, 1.0); + } +} diff --git a/core/src/vjs.rs b/core/src/vjs.rs index 18ce902..7af9897 100644 --- a/core/src/vjs.rs +++ b/core/src/vjs.rs @@ -1324,6 +1324,28 @@ pub struct Engine { exports: HashMap>, secrets: Arc, depth: usize, + /// While spans are exported: the hop a run belongs to and the `invoke` + /// spans it left (ADR-0034). None otherwise, so an untraced run pays one + /// test per invoke. + trace: Option, +} + +struct InvokeTrace { + /// The hop, then each invoke in progress: the last is the parent of the next. + stack: Vec, + done: Vec, +} + +/// One `invoke`, timed, under the hop or the invoke that made it. +pub struct InvokeSpan { + pub hop: crate::trace::Hop, + /// `package:service`. + pub service: String, + /// The service file, relative to the project root. + pub file: String, + pub start_nanos: u128, + pub end_nanos: u128, + pub error: Option, } impl Engine { @@ -1353,8 +1375,29 @@ impl Engine { exports: HashMap::new(), secrets, depth: 0, + trace: None, + } + } + /// Record a span per `invoke` under `hop` in the runs that follow, or stop + /// recording (None). What was recorded and not taken is dropped. + pub fn trace_under(&mut self, hop: Option<&crate::trace::Hop>) { + match (hop, &mut self.trace) { + // Once per message: keep the allocations of the last one. + (Some(hop), Some(t)) => { + t.stack.clear(); + t.stack.push(hop.clone()); + t.done.clear(); + } + (Some(hop), None) => { + self.trace = Some(InvokeTrace { stack: vec![hop.clone()], done: Vec::new() }) + } + (None, _) => self.trace = None, } } + /// The `invoke` spans recorded since `trace_under`, oldest first. + pub fn take_spans(&mut self) -> Vec { + self.trace.as_mut().map(|t| std::mem::take(&mut t.done)).unwrap_or_default() + } pub fn invalidate(&mut self) { self.cache.clear(); self.exports.clear(); @@ -1468,6 +1511,15 @@ fn run_service( return Err(e); } }; + // A span for this invoke, under whatever is running it (ADR-0034). + let span = engine.trace.as_mut().map(|t| { + let hop = t.stack.last().expect("the hop is at the bottom").child(); + t.stack.push(hop.clone()); + (hop, crate::metrics::now_nanos()) + }); + let names = span.is_some().then(|| { + (format!("{pkg}:{svc}"), engine.pkg_dir(&pkg).join("services").join(format!("{svc}.vjs"))) + }); // The invoked service's own invokes resolve within ITS package. let saved_pkg = std::mem::replace(&mut engine.caller_pkg, pkg); let mut ctx = Ctx { vars: args.clone(), emits: Vec::new(), response: None }; @@ -1475,6 +1527,19 @@ fn run_service( let result = exec_block(&stmts, &mut ctx, engine); engine.caller_pkg = saved_pkg; engine.depth -= 1; + if let (Some((hop, start_nanos)), Some((service, file))) = (span, names) { + let file = file.strip_prefix(&engine.project_root).unwrap_or(&file).display().to_string(); + let t = engine.trace.as_mut().expect("a span was opened, so the engine traces"); + t.stack.pop(); + t.done.push(InvokeSpan { + hop, + service, + file, + start_nanos, + end_nanos: crate::metrics::now_nanos(), + error: result.as_ref().err().cloned(), + }); + } result?; emits.append(&mut ctx.emits); ctx.vars.remove("event"); diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 76ed5e6..cc59984 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -76,10 +76,10 @@ What turns "nice project" into "I can run this in production": re-injected explicitly after the fix. The sister loop of ADR-0005. 2. **Real observability** · built (ADR-0016): OTLP/HTTP-JSON traces + a Prometheus `/metrics` endpoint, hand-rolled to keep the footprint. The - manifesto claims it again now that it ships. Every span is still its own - trace: one trace per event across hops, and an end-to-end view in the - panel that links each hop to its version, approval and replay evidence, - is ADR-0034 (proposed, not built). + manifesto claims it again now that it ships. One trace per business + event across hops is built (ADR-0034 lot A, transport test T6 in CI). The + end-to-end view in the panel that links each hop to its version, approval + and replay evidence is lot B (proposed, not built). 3. **Full shadow-replay** · built (ADR-0018): JetStream-hydrated history, promote audit trail (git + `VEJAS_AUDIT`), forward-only rollback. 4. **Published, reproducible benchmarks**: throughput, memory, image size, diff --git a/docs/adr/0034-observability-as-the-trust-surface.md b/docs/adr/0034-observability-as-the-trust-surface.md index 8032e29..12f223f 100644 --- a/docs/adr/0034-observability-as-the-trust-surface.md +++ b/docs/adr/0034-observability-as-the-trust-surface.md @@ -1,8 +1,9 @@ # 0034 — Observability as the trust surface -- Status: Proposed (founder-directed, 2026-10-24; nothing built yet. The guide - correction in point 12 ships with this ADR) -- Date: 2026-10-24; measured state re-read on v0.6.0 on 2026-11-26 +- Status: Accepted (partial): lot A is built and T6 gates it in CI (points 1 + to 6, and 12 with them); lot B (points 7 to 11) is not +- Date: 2026-10-24; measured state re-read on v0.6.0 on 2026-11-26; lot A + built 2026-11-26 ## Context @@ -192,6 +193,77 @@ MANIFESTO (the monitoring screen draws nothing) hold throughout. ADR: today every span is its own trace. The guide claims end-to-end traces only when T6 is green, and the ROADMAP points here from Phase 5. +## What is built (2026-11-26): lot A + +Points 1 to 6 are built, point 12 with them, and T6 gates them in CI. Where +the build departs from the text above, the reason is stated here. + +- **No span per emit.** An emit is a buffered publish, confirmed once per + batch (ADR-0002): its own span would last a few microseconds, measure + nothing, and double the volume of a one-emit flow. The emit carries the + context of the hop that made it, and the downstream span names its subject + and hangs under that hop. Fan-out stays readable: one child per subject. +- **No CLIENT span inside a sink hop.** The sink hop's span is itself of kind + `CLIENT`, since the runtime is the client of the system it delivers to, and + its id is the one the HTTP call carries. A second span covering the same + call would repeat the first. +- **Spans are named after their unit** (`flow:order_sync`), as before, rather + than `process `: the unit is what an operator knows, and a + backend's per-name rate and latency metrics then come per unit. The + semantic-convention attributes carry the subject. +- **`code.line.number` is not set.** The AST has no line numbers yet. An + invoke span carries `code.function.name` and `code.file.path`. +- **A success leaves the status unset**, as the semantic conventions ask of + instrumentation; a failure sets it to error with `error.type=_OTHER` and + `error.message`. int64 attributes travel as strings (OTLP JSON mapping). +- **Retries follow the OTLP specification:** connection errors, 429, 502, 503 + and 504, with `Retry-After` honoured up to 30 s. Any other 5xx is a + permanent failure there, so it is not retried. +- **The exporter batches as the OpenTelemetry SDKs do**, with their variables + (`OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BSP_MAX_EXPORT_BATCH_SIZE`, + `OTEL_BSP_MAX_QUEUE_SIZE`; the delay defaults to 1 s rather than 5 s), and + reads its queue on a 25 ms tick while spans are pending instead of waiting + on it. The first measurement showed why: export cost 63 µs of CPU per event. + A request per handful of spans and a JSON tree per span explained about 35 + of it, and waking the export thread for every span about 20. A graceful + stop flushes the queue (3 s at most), and T6 checks that it does. The six + samplers of the specification are read, and a hop that is sampled out + builds no span. +- **The context reaches more places than the text named:** the `http-in` + answer returns the trace id, a dead letter stores its `traceparent` and a + DLQ replay continues it, the `vx.dlq.events` announcement carries the trace + of its last letter, an `exec` sink gets `TRACEPARENT` and `TRACESTATE` in + its environment (the OpenTelemetry carrier for a child process), detect + units (ADR-0031) take part as flows do, and each entry of the event ring + records its trace and span ids. +- **A trace never costs a message.** The headers count toward the server's + `max_payload`, so a message they would push past it is published without + them (its next hop starts a trace), and a death envelope that its + `traceparent` would push past it goes without that field. The + `vx.dlq.events` announcement keeps the trace ids but not the caller's + `tracestate`, which is text from outside. +- **Propagation stays on without an exporter, and is not free.** Point 6 + asked for zero cost with the exporter unset. The context has to travel even + then: a downstream system that traces needs it on the sink's call, another + instance or cell may export, and the event ring shows the trace id. + Measured, it costs about 3 µs of CPU per flow hop (1.5 + to 4.5 over four series, against 72.5 µs for the hop). No switch turns it off; one can be added if a deployment needs it. +- **Not built in lot A:** the Collector configuration and the Grafana + dashboard of point 5 (the guide gives a one-line Jaeger instead, checked + against Jaeger 2.23.0); `traceparent` on the GETs of `http-poll` and + `oauth-poll`; MQTT, which has no headers before version 5; `exec-rpc` + request/reply. Each is an addition, not a change of what is built. +- **Cost (point 6):** `bench/trace-cost.sh` against the runtime from before + tracing (master at `491ba69`), isolated flow hop, 20 000 events, median of + five runs, the runtime's own CPU time per event: 72.5 µs before tracing, + 74.0 with the context and no exporter (about 3 µs more over four series), + 83.0 exporting every span, 76.5 exporting one trace in ten. Throughput stays within 2.5 %, since the four + publishers of the bench bound it. An event that arrives with a + `traceparent` costs about 5 µs more to continue. The hot path never waits + for the collector: the 200 000 spans of the exporting runs all arrived, + none dropped. The numbers are in `bench/README.md` and on the benchmarks + page. + ## Consequences - The guide is honest today. The "future extension" of ADR-0016 has a design diff --git a/docs/adr/README.md b/docs/adr/README.md index 61057ff..267cfc1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -42,7 +42,7 @@ the old one. | [0029](0029-failure-mode-guardrails.md) | The failure-mode guardrails | Accepted | | [0030](0030-enterprise-repo-architecture.md) | How the enterprise tier attaches: seams, not plugins | Proposed | | [0031](0031-pattern-detection-unit-varpulis-engine.md) | Pattern detection as a unit type: the Varpulis engine embedded | Proposed | -| [0034](0034-observability-as-the-trust-surface.md) | Observability as the trust surface: one trace per event, an end-to-end view with provenance | Proposed | +| [0034](0034-observability-as-the-trust-surface.md) | Observability as the trust surface: one trace per event, an end-to-end view with provenance | Accepted (partial): one trace per event built, the panel view not | | [0035](0035-async-nats-bus-island.md) | The NATS client moves to async-nats, behind one synchronous module | Accepted | | [0036](0036-integration-agent-separate-binary.md) | The integration agent is a separate binary, a client of `/mcp` | Accepted, not built | diff --git a/docs/book/src/guides/dlq-replay.md b/docs/book/src/guides/dlq-replay.md index 2803f53..8e5a76a 100644 --- a/docs/book/src/guides/dlq-replay.md +++ b/docs/book/src/guides/dlq-replay.md @@ -10,7 +10,9 @@ A flow error → redelivery (after `VEJAS_ACK_WAIT_SECS`) → up to 5 attempts no pointless retries. The dead letter lands on `vxdlq.` wrapped in a **death envelope**: original payload, error, attempt count, timestamps, and the **flow version** that killed it (ADR-0021) — so a -post-mortem knows *which* logic failed, even after a promote. +post-mortem knows *which* logic failed, even after a promote. The envelope +also keeps the `traceparent` of the event, and a replay continues that +trace (see [observability](observability.md)). ## Seeing and replaying @@ -31,12 +33,13 @@ happens next is a flow or a sink like any other: ```json {"transition": "dead-lettered", "ts": 1793980000, "unit": "flow:orders", "subject": "vx.orders.in", "attempts": 5, "version": "d5768a2de6e8cbb0", - "count": 1} + "count": 1, "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"} ``` - **Metadata only.** The payload and the error text stay in the DLQ: a dead letter is untrusted content, and this event is what wakes a person or an - agent. Read the letter with `vejas_dlq`. + agent. Read the letter with `vejas_dlq`. `trace_id` is the trace of the + last letter the event stands for, and the event travels in that trace. - **One event per unit per window** (`VEJAS_DLQ_EVENT_SECS`, 60 s). The first letter is news at once; `count` says how many letters the next event stands for, so a burst wakes a reader once and loses nothing. Each instance of a diff --git a/docs/book/src/guides/expose-an-api.md b/docs/book/src/guides/expose-an-api.md index 53be701..e49a183 100644 --- a/docs/book/src/guides/expose-an-api.md +++ b/docs/book/src/guides/expose-an-api.md @@ -22,7 +22,9 @@ PORT = 8787 `POST /ingest/shop.orders` publishes the JSON body on `vx.shop.orders` and answers `202` only after JetStream confirmed the write — the caller's success means *persisted*, not *processed*. Flows consume from there with -the full delivery contract (redelivery, DLQ). +the full delivery contract (redelivery, DLQ). The answer carries the event's +`trace_id`; send a `traceparent` header and the event continues your trace, +on this webhook as on an API flow (see [observability](observability.md)). **Lock the port to its subjects.** The `/ingest` port is unauthenticated by design — it only publishes. Without a limit, any caller can publish to any diff --git a/docs/book/src/guides/observability.md b/docs/book/src/guides/observability.md index 4ff18fe..82f2d17 100644 --- a/docs/book/src/guides/observability.md +++ b/docs/book/src/guides/observability.md @@ -22,22 +22,124 @@ health, throughput, and error rate with no configuration. ## Traces — OTLP -Set one variable and the runtime exports spans to any OpenTelemetry -collector: +Every event the runtime lets in gets one trace, and every hop it crosses adds +a span to that trace: the source or webhook that received it, each flow that +processed it, each `invoke` a flow made, and the sink that delivered it. The +context is the W3C `traceparent`. It travels in a NATS header on every +message the runtime publishes, so the payload is untouched and a consumer +outside Vejas can ignore it. The headers count toward the server's +`max_payload`: a message so close to the limit that they would push it over +goes without them, and its next hop starts a new trace. A trace is never the +reason a message fails. + +The context also crosses the edges of the cell: + +- `http-in` and `api` flows honour a `traceparent` sent by the caller, and + the event's trace continues the caller's. `http-in` answers with the trace + id: `{"published":"vx.orders","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}`. +- `http-out` and `slack-out` send `traceparent` with their HTTP calls, and an + `exec` sink hands it to its program as `TRACEPARENT` in the environment. A + downstream system that traces hangs its spans under the sink's. +- A dead letter keeps the trace it died in, and a [DLQ replay](dlq-replay.md) + continues it. The `dead-lettered` event on `vx.dlq.events` carries it too, + so the flow that pages someone appears in the failing event's trace. +- MQTT has no headers before version 5: the trace stops at an `mqtt-out` + sink and starts again at an `mqtt-in` source. + +Each entry of the event ring carries its `trace_id`, so a row of **Recent +events** leads to the trace in your tracing backend. + +### Exporting spans + +Set one variable and spans go to any OpenTelemetry collector or backend that +accepts OTLP over HTTP with JSON: ``` -OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 -OTEL_SERVICE_NAME=vejas # optional label +OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 # spans go to /v1/traces +OTEL_SERVICE_NAME=vejas # optional, the default ``` -Unset, it is a genuine no-op — no exporter thread, no overhead. Each flow -execution becomes one span (subject, ok/error, emit count, timing). +To see a trace within minutes, Jaeger alone is enough: -Today every span is its own trace. The runtime does not yet propagate a -trace context across hops, so a request that crosses three flows shows up in -the collector as three unrelated traces, correlated by time and subject only. -One trace per business event, with parent spans across hops, is decided in -ADR-0034 and will be claimed here once its CI test is green. +``` +docker run --rm -p 127.0.0.1:16686:16686 -p 127.0.0.1:4318:4318 jaegertracing/jaeger:2.23.0 +OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 vejas-runtime +``` + +then open `http://localhost:16686` and pick the service `vejas`. + +The exporter reads the other variables the OpenTelemetry specification +defines for it: + +| Variable | Effect | +|---|---| +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | The full URL for spans, used as given; it wins over the generic endpoint | +| `OTEL_EXPORTER_OTLP_HEADERS` | `key=value,key2=value2` (values percent-encoded), for a backend that wants a token; `OTEL_EXPORTER_OTLP_TRACES_HEADERS` wins over it | +| `OTEL_EXPORTER_OTLP_TIMEOUT` | Milliseconds per export request, 10000 by default; `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` wins over it | +| `OTEL_RESOURCE_ATTRIBUTES` | Extra resource attributes, such as `deployment.environment=prod` | +| `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG` | Sampling, see below | +| `OTEL_BSP_SCHEDULE_DELAY` | Milliseconds a span may wait for its batch, 1000 by default (the specification says 5000; a second shows a test event at once) | +| `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | Spans per export request, 512 by default | +| `OTEL_BSP_MAX_QUEUE_SIZE` | Spans waiting for export, 4096 by default | + +Header values are credentials, and the runtime never writes them to its log; +an entry that HTTP cannot carry is skipped at start, with a warning that gives +its position only. The endpoint is logged without its user info and query. +On a graceful stop the runtime gives the exporter up to 3 seconds to send +what is still queued, so the spans of the last events before a restart reach +the backend. + +**Sampling.** The default sampler is `parentbased_always_on`: every trace is +exported. Under load, `OTEL_TRACES_SAMPLER=parentbased_traceidratio` with +`OTEL_TRACES_SAMPLER_ARG=0.1` keeps one trace in ten. The hop that starts a +trace decides, and the decision travels in the `sampled` flag, so every hop +of a trace agrees with it; a hop that is sampled out builds no span. A failed +hop or a dead letter is exported whatever the sampler says; its ancestors may +then be missing from the backend, which is the known limit of deciding at +the head. With a parent-based sampler, a caller that sends `traceparent` +decides for its own requests. `traceidratio`, `always_on` and `always_off` +ignore the caller's flag, which suits an edge exposed to callers you do not +control. + +**What a span holds.** A hop's span is named after its unit +(`flow:order_sync`, `connector:erp_out`). Its kind says what the hop was: +`SERVER` for `http-in` and an `api` flow, `PRODUCER` for a source, `CONSUMER` +for a flow, `CLIENT` for a sink. It carries the OpenTelemetry messaging +attributes (`messaging.system=nats`, `messaging.destination.name`, +`messaging.message.id`, the JetStream sequence) and the Vejas ones: +`vejas.unit`, `vejas.flow.version` (the content hash of the version that ran, +see [change safely](change-safely.md)), `vejas.flow.baseline` when a +promoted version overrides git, `vejas.delivery.attempt`, `vejas.emits`, and +`vejas.dlq=true` on a dead-lettered run. An `invoke` span is named +`invoke package:service`. A failure sets the span status to error, with +`error.message`. + +**Loss is counted.** The export queue is bounded and the hot path never waits +for the collector. Connection errors and the answers 429, 502, 503 and 504 +are retried with backoff, honouring `Retry-After`. When the queue is full, or +an export still fails after its retries, the spans are dropped and counted +on `/metrics`, and the log says so at most once a minute: + +``` +vejas_spans_exported_total 18342 +vejas_spans_dropped_total{reason="queue_full"} 0 +vejas_spans_dropped_total{reason="export_failed"} 0 +``` + +**Cost.** Without an exporter no span is built; the context still travels, +since it is what puts the trace id in the event ring and in downstream calls. +On the isolated flow hop (`bench/trace-cost.sh`: 20 000 events, median of +five runs, the runtime's own CPU time per event), the hop took 72.5 µs +before tracing. The context alone adds about 3 µs (1.5 to 4.5 over four +series of runs). Exporting every span adds 10.5 µs (+14 %), and exporting one +trace in ten adds 4 µs (+5.5 %). Throughput stays within 2.5 % of the runtime +from before tracing. Resident memory grows by 0.7 MB, +and by 2.6 MB with the exporter and its queue. The details are on the +[benchmarks](../reference/benchmarks.md) page. + +The panel does not draw traces yet. The path of one event hop by hop, with +the flow version and its provenance, is the second lot of ADR-0034; until +then the trace is read in your tracing backend. ## The event ring — what just happened @@ -48,7 +150,7 @@ in-memory ring of recent events: - API: `GET /events`; agent: `vejas_events`. Each entry carries the subject, ok/error, the emitted subjects, a payload -preview, and — for sinks — **what the downstream answered** (a rejected +preview, the `trace_id`, and — for sinks — **what the downstream answered** (a rejected fact, a skip), so you see not just that a message was sent but how it landed. @@ -59,7 +161,6 @@ landed. verdict in the [DLQ](dlq-replay.md), which is its own inspectable surface. Everything here is a read; none of it changes what runs. The -[benchmarks](../reference/benchmarks.md) are taken with metrics on, since the -counters cannot be switched off, so their numbers include that cost. The cost -of the OTLP exporter and of the event ring has not been measured separately -yet; ADR-0034 adds that measurement. +[benchmarks](../reference/benchmarks.md) are taken with metrics and the event +ring on, since neither can be switched off, so their numbers include that +cost. What tracing adds is measured on its own, above. diff --git a/docs/book/src/reference/benchmarks.md b/docs/book/src/reference/benchmarks.md index 1561a22..cc2db6f 100644 --- a/docs/book/src/reference/benchmarks.md +++ b/docs/book/src/reference/benchmarks.md @@ -16,6 +16,7 @@ yours. | e2e paced sustained ~1 900/s | p50 14 ms, p99 36 ms, 20 000/20 000 | `bench/paced.sh 2000 15` | | e2e saturated (32 conns) | ~4 900/s ingest, ~2 650/s delivered (sink-bound) | `bench/run.sh 15 32` | | Isolated flow hop | 13 652/s (13 746/s aggregate over 10 flows) | `bench/flow-only.sh`, `bench/multi-flow.sh` | +| Tracing, runtime CPU per flow hop | 72.5 µs before tracing; +1.5 µs with no exporter (1.5 to 4.5 over four series), +10.5 µs exporting every span, +4 µs one trace in ten | `bench/trace-cost.sh` | | MQTT loopback, QoS 1 both ways, real mosquitto | 2 070 rt/s, 5 000/5 000 | `bench/broker-mqtt.sh 5000` | | Cluster: instance kill -9 under load | 20 000/20 000, zero loss | `bench/cluster.sh` | | Cluster: singleton failover | at most 2 s graceful / 4–5 s crash (TTL-bound) | `bench/cluster-gaps.sh` | diff --git a/docs/book/src/reference/env-vars.md b/docs/book/src/reference/env-vars.md index 84600e7..95abd27 100644 --- a/docs/book/src/reference/env-vars.md +++ b/docs/book/src/reference/env-vars.md @@ -48,8 +48,16 @@ directory is a complete system. | Variable | Purpose | |---|---| -| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP/HTTP-JSON export (hand-rolled, no SDK tree). `/metrics` (Prometheus) is always on. | -| `OTEL_SERVICE_NAME` | Service name for exported spans/metrics. | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP/HTTP-JSON span export to `/v1/traces` (hand-rolled, no SDK tree). `/metrics` (Prometheus) is always on. | +| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | The full URL for spans, used as given; wins over the generic endpoint. | +| `OTEL_EXPORTER_OTLP_HEADERS` / `OTEL_EXPORTER_OTLP_TRACES_HEADERS` | `key=value,…` (percent-encoded) sent with each export, for a backend token. Never logged. | +| `OTEL_EXPORTER_OTLP_TIMEOUT` / `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | Milliseconds per export request (10000). | +| `OTEL_SERVICE_NAME` | Service name for exported spans (`vejas`). | +| `OTEL_RESOURCE_ATTRIBUTES` | Extra resource attributes, `key=value,…`. | +| `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG` | Sampler (`parentbased_always_on`) and its ratio; failures are exported whatever it says. | +| `OTEL_BSP_SCHEDULE_DELAY` / `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` / `OTEL_BSP_MAX_QUEUE_SIZE` | Export batching: 1000 ms, 512 spans per request, 4096 spans queued. | + +See [observability](../guides/observability.md) for what a trace holds. ## API flows diff --git a/docs/book/src/reference/http-api.md b/docs/book/src/reference/http-api.md index dedf479..091cc2f 100644 --- a/docs/book/src/reference/http-api.md +++ b/docs/book/src/reference/http-api.md @@ -76,4 +76,4 @@ answer with a didactic refusal pointing at the proposal queue. | Route | Purpose | |---|---| | `POST /mcp` | JSON-RPC 2.0 — the runtime **is** the MCP server. See [MCP tools](mcp-tools.md). | -| `POST /ingest/` *(http-in connector, own port)* | Webhook ingestion → `vx.` on the bus, 202 after the JetStream pub-ack. At most `MAX_CONNECTIONS` at once (default 512), then 503. | +| `POST /ingest/` *(http-in connector, own port)* | Webhook ingestion → `vx.` on the bus, 202 after the JetStream pub-ack, answering `{"published":"vx.","trace_id":"…"}`; a caller's `traceparent` is continued. At most `MAX_CONNECTIONS` at once (default 512), then 503. | diff --git a/e2e/transport/run.sh b/e2e/transport/run.sh index 6965fbe..1fc7693 100755 --- a/e2e/transport/run.sh +++ b/e2e/transport/run.sh @@ -10,6 +10,13 @@ # after restart (at-least-once, publish-before-ack) # T4 reconnection kill + restart nats; the flow reconnects and resumes # T5 anti-zombie SIGTERM while idle exits promptly (no blocking pull) +# T6 one trace an event is one trace from http-in to the last sink: +# same trace id at every hop, parents chained, the +# caller's traceparent honoured (http-in and an api +# flow), the sink's HTTP call carries it on, a caller's +# unsampled flag is followed, no span dropped, a +# graceful stop flushes the last spans (ADR-0034, +# against a stub collector) # # Redelivery latency is set low (VEJAS_ACK_WAIT_SECS=1) so the whole suite runs # in seconds. No real credentials, no shared state; teardown by captured PID. @@ -31,7 +38,7 @@ NATS_P=4310; HTTP_P=8710 URL="nats://127.0.0.1:$NATS_P" WORK="$(mktemp -d)" ROOT="$WORK/root"; mkdir -p "$ROOT/flows" -NATS_PID=""; RT_PID="" +NATS_PID=""; RT_PID=""; STUB_PID="" fail=0 cat > "$ROOT/flows/echo.vjs" <<'VJS' @@ -64,6 +71,7 @@ wait_health() { # poll /healthz instead of a fixed sleep echo " runtime did not become healthy" >&2; return 1 } teardown() { + [ -n "$STUB_PID" ] && kill "$STUB_PID" 2>/dev/null [ -n "$RT_PID" ] && kill "$RT_PID" 2>/dev/null [ -n "$NATS_PID" ] && kill "$NATS_PID" 2>/dev/null wait 2>/dev/null @@ -178,6 +186,185 @@ else fi RT_PID="" # already down +# ── T6 — one trace per event, end to end (ADR-0034) ────────────────────────── +echo "── T6 one trace per event" +COL_P=8712; IN_P=8713 +T6="$WORK/t6"; mkdir -p "$T6/root/flows" "$T6/root/services" "$T6/root/connectors" +: > "$T6/received" +# The stub collector and HTTP sink target, in one listener: every POST lands +# in $T6/received as {path, traceparent, body}. +cat > "$T6/stub.py" <<'PY' +import http.server, json, sys +port, out = int(sys.argv[1]), sys.argv[2] +class Stub(http.server.BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers.get("content-length") or 0)) + with open(out, "a") as f: + f.write(json.dumps({"path": self.path, "traceparent": self.headers.get("traceparent"), + "body": body.decode("utf-8", "replace")}) + "\n") + self.send_response(200) + self.send_header("content-type", "application/json") + self.end_headers() + self.wfile.write(b"{}") + def log_message(self, *args): + pass +http.server.ThreadingHTTPServer(("127.0.0.1", port), Stub).serve_forever() +PY +python3 "$T6/stub.py" "$COL_P" "$T6/received" & STUB_PID=$! +cat > "$T6/root/connectors/t6_in.vjs" < "$T6/root/connectors/t6_out.vjs" < "$T6/root/services/t6_tag.vjs" <<'VJS' +# service: t6_tag +tag = f"tagged {order}" +VJS +cat > "$T6/root/flows/t6_first.vjs" <<'VJS' +source "vxt.t6.in" +invoke t6_tag(order: event.order) +emit "vxt.t6.mid", { order: event.order, tag: tag } +VJS +cat > "$T6/root/flows/t6_second.vjs" <<'VJS' +source "vxt.t6.mid" +emit "vxt.t6.out", { order: event.order } +VJS +cat > "$T6/root/flows/t6_api.vjs" <<'VJS' +api "POST /t6" +emit "vxt.t6.mid", { order: event.order } +respond 202, { accepted: event.order } +VJS +VEJAS_ROOT="$T6/root" NATS_URL="$URL" VEJAS_STREAM=TTEST VEJAS_SUBJECT_ROOT=vxt \ +VEJAS_HTTP_ADDR="127.0.0.1:$HTTP_P" VEJAS_ACK_WAIT_SECS=1 \ +OTEL_EXPORTER_OTLP_ENDPOINT="http://127.0.0.1:$COL_P" OTEL_SERVICE_NAME=vejas-t6 \ +OTEL_BSP_SCHEDULE_DELAY=3000 \ + "$BIN" >>"$WORK/rt.log" 2>&1 & RT_PID=$! +# The 3 s schedule delay outlasts a graceful stop (about 1 s): case E below +# then proves the stop flushes, since no scheduled export can send its spans. +wait_health || bad "T6 runtime did not start" +for _ in $(seq 1 100); do # t6_first, t6_second, t6_in, t6_out + n=$(curl -s "http://127.0.0.1:$HTTP_P/topology" | grep -o '"status":"running"' | wc -l) + [ "$n" -ge 4 ] && break; sleep 0.1 +done +for _ in $(seq 1 50); do curl -sf "http://127.0.0.1:$IN_P/healthz" >/dev/null && break; sleep 0.1; done + +TA=4bf92f3577b34da6a3ce929d0e0e4736; PA=00f067aa0ba902b7 +TC=0af7651916cd43dd8448eb211c80319c; PC=b7ad6b7169203331 +TD=1bf92f3577b34da6a3ce929d0e0e4737; PD=10f067aa0ba902b8 +RA=$(curl -s -X POST -H "traceparent: 00-$TA-$PA-01" -d '{"order":"A-1"}' "http://127.0.0.1:$IN_P/ingest/t6.in") +RB=$(curl -s -X POST -d '{"order":"B-2"}' "http://127.0.0.1:$IN_P/ingest/t6.in") +# D: the caller sampled its trace out (flag 00); the default sampler follows it. +curl -s -X POST -H "traceparent: 00-$TD-$PD-00" -d '{"order":"D-4"}' "http://127.0.0.1:$IN_P/ingest/t6.in" >/dev/null +curl -s -X POST -H "TraceParent: 00-$TC-$PC-01" -H 'content-type: application/json' \ + -d '{"order":"C-3"}' "http://127.0.0.1:$HTTP_P/api/t6" >/dev/null +TB=$(printf '%s' "$RB" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("trace_id",""))' 2>/dev/null) +case "$RA" in *"\"trace_id\":\"$TA\""*) pass "http-in answers with the trace id it continued";; + *) bad "http-in answer lacks the caller's trace id: $RA";; esac +[ ${#TB} -eq 32 ] && pass "http-in starts a trace when the caller sends none" || bad "no trace id for a fresh request: $RB" + +# Every span the three events produce, checked once the last ones are in. +cat > "$T6/check.py" <<'PY' +import json, sys +received, ta, pa, tb, tc, pc, td = sys.argv[1:8] +spans, sinks = [], [] +for line in open(received): + rec = json.loads(line) + if rec["path"] == "/v1/traces": + for rs in json.loads(rec["body"])["resourceSpans"]: + for ss in rs["scopeSpans"]: + spans += ss["spans"] + elif rec["path"] == "/sink": + sinks.append(rec) +def unit(s): + return next((a["value"]["stringValue"] for a in s["attributes"] if a["key"] == "vejas.unit"), "") +def chain(trace, root_parent, units): + of = [s for s in spans if s["traceId"] == trace] + by = {} + for s in of: + by.setdefault((unit(s), s["name"].startswith("invoke ")), s) + need = [(u, False) for u in units] + [("flow:t6_first", True)] * ("flow:t6_first" in units) + missing = [u for u in need if u not in by] + if missing: + return f"missing {missing} among {sorted(by)}" + hops = [by[(u, False)] for u in units] + if hops[0].get("parentSpanId", "") != root_parent: + return f"{units[0]} hangs under {hops[0].get('parentSpanId')!r}, not {root_parent!r}" + for up, down in zip(hops, hops[1:]): + if down.get("parentSpanId") != up["spanId"]: + return f"{unit(down)} does not hang under {unit(up)}" + if "flow:t6_first" in units and by[("flow:t6_first", True)].get("parentSpanId") != by[("flow:t6_first", False)]["spanId"]: + return "the invoke span does not hang under its flow" + sink = hops[-1] + if not any(r["traceparent"] == f"00-{trace}-{sink['spanId']}-01" for r in sinks): + return "the sink's HTTP call does not carry the sink span as traceparent" + return "" +def sampled_out(trace): + if any(s["traceId"] == trace for s in spans): + return "spans exported for a trace its caller sampled out" + if not any((r["traceparent"] or "").startswith(f"00-{trace}-") and r["traceparent"].endswith("-00") for r in sinks): + return "the sink's HTTP call lost the trace or its unsampled flag" + return "" +done = sys.argv[8] in ("final", "stop") +if sys.argv[8] == "stop": # E only: the spans a graceful stop had to flush + te, pe = sys.argv[9:11] + print("E", chain(te, pe, ["connector:t6_in", "flow:t6_first", "flow:t6_second", "connector:t6_out"]) or "ok") + sys.exit(0) +errors = { + "A": chain(ta, pa, ["connector:t6_in", "flow:t6_first", "flow:t6_second", "connector:t6_out"]), + "B": chain(tb, "", ["connector:t6_in", "flow:t6_first", "flow:t6_second", "connector:t6_out"]), + "C": chain(tc, pc, ["flow:t6_api", "flow:t6_second", "connector:t6_out"]), + "D": sampled_out(td), +} +if any(errors.values()) and not done: + sys.exit(1) +for k, e in errors.items(): + print(f"{k} {e or 'ok'}") +PY +for _ in $(seq 1 150); do + python3 "$T6/check.py" "$T6/received" "$TA" "$PA" "$TB" "$TC" "$PC" "$TD" wait >/dev/null 2>&1 && break + sleep 0.1 +done +VERDICT=$(python3 "$T6/check.py" "$T6/received" "$TA" "$PA" "$TB" "$TC" "$PC" "$TD" final 2>&1) +for case_ in A B C D; do + case "$case_" in + A) what="http-in with a caller's traceparent: one trace, parents chained to the sink's HTTP call";; + B) what="http-in without one: one trace, parents chained to the sink's HTTP call";; + C) what="an api flow with a caller's traceparent: one trace, parents chained to the sink's HTTP call";; + D) what="a trace the caller sampled out: no span exported, the flag carried to the sink's call";; + esac + verdict=$(printf '%s\n' "$VERDICT" | sed -n "s/^$case_ //p") + [ "$verdict" = "ok" ] && pass "$what" || bad "$what: ${verdict:-no verdict: $VERDICT}" +done +M=$(curl -s "http://127.0.0.1:$HTTP_P/metrics") +if printf '%s' "$M" | grep -q 'vejas_spans_dropped_total{reason="queue_full"} 0' \ + && printf '%s' "$M" | grep -q 'vejas_spans_dropped_total{reason="export_failed"} 0'; then + pass "no span dropped" +else + bad "spans dropped: $(printf '%s' "$M" | grep vejas_spans_dropped_total | tr '\n' ' ')" +fi +if curl -s "http://127.0.0.1:$HTTP_P/events?flow=flow:t6_second" | grep -q "\"trace_id\":\"$TA\""; then + pass "the event ring shows the trace id" +else + bad "the event ring has no trace id for event A" +fi +# E: stop the runtime as soon as the sink has delivered an event. Its spans +# are still in the exporter's batch; only the flush on stop can send them. +TE=2cf92f3577b34da6a3ce929d0e0e4739; PE=30f067aa0ba902ba +curl -s -X POST -H "traceparent: 00-$TE-$PE-01" -d '{"order":"E-5"}' "http://127.0.0.1:$IN_P/ingest/t6.in" >/dev/null +for _ in $(seq 1 50); do grep -q "00-$TE-" "$T6/received" && break; sleep 0.1; done +kill -TERM "$RT_PID" 2>/dev/null +for _ in $(seq 1 80); do kill -0 "$RT_PID" 2>/dev/null || break; sleep 0.1; done +verdict=$(python3 "$T6/check.py" "$T6/received" "$TA" "$PA" "$TB" "$TC" "$PC" "$TD" stop "$TE" "$PE" 2>&1 | sed -n 's/^E //p') +[ "$verdict" = "ok" ] && pass "a graceful stop exports the spans of the last event" \ + || bad "a graceful stop lost spans: ${verdict:-no verdict}" +kill "$STUB_PID" 2>/dev/null + echo if [ "$fail" -eq 0 ]; then echo "transport: all invariants hold ✓"; else echo "transport: $fail FAILED"; fi exit $((fail > 0 ? 1 : 0))