Skip to content

Commit 697f5df

Browse files
authored
Merge pull request #33 from Accenture/feat/otel-forwarder
OpenTelemetry trace forwarder - the engines' opentelemetry-forwarder twin, opt-in and dependency-free
2 parents 8857d74 + 876d438 commit 697f5df

16 files changed

Lines changed: 1711 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,27 @@
11
# Changelog
22

3+
## Unreleased (4.12.15 in preparation)
4+
5+
### Added
6+
7+
- The **OpenTelemetry trace forwarder** (`mercury_composable.otel`), the lock-step twin of the
8+
engines' `opentelemetry-forwarder` extension: with `otel.forwarding=true` the host hands
9+
every distributed-trace dataset it emits to the engines' extension route
10+
`distributed.trace.forwarder`, where the built-in forwarder maps it to one OpenTelemetry
11+
span carrying the host's exact W3C ids and exports it over OTLP/HTTP (protobuf) - the same
12+
`otel.*` keys, span mapping, per-export credential headers, retry policy and failure
13+
diagnostics as the Java and Rust forwarders. No OpenTelemetry SDK and no new dependency:
14+
the encoder is the Rust port's hand-written OTLP writer, ported. Off by default.
15+
- The `distributed.trace.forwarder` extension route itself: a function an application
16+
registers under that name receives every emitted dataset (delivered without a trace, so
17+
the forwarder's own execution emits none) - the engines' zero-tracing forwarder contract.
18+
19+
### Changed
20+
21+
- The demo `application.yml` carries the `otel.*` keys switched off, wired to the
22+
`OTLP_API_ENDPOINT`, `OTLP_AUTH_HEADER` and `OTLP_TOKEN` environment variables, so
23+
`-Dotel.forwarding=true` at run time is enough to export to a backend.
24+
325
## Version 4.12.1, 9/1/2026
426

527
The first PyPI release: `pip install mercury-composable`. The v4.12.0 lock-step line

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ This package is a deliberately **lightweight wrapper of the Event-over-HTTP prot
1414
- a **primitive in-process event bus** — the single dispatch pipeline: one FIFO mailbox
1515
per route consumed by `instances` worker tasks, and
1616
- the **minimalist utilities** shared with the engines for consistency: configuration
17-
management, logging in the engines' presentation format, and distributed-trace context.
17+
management, logging in the engines' presentation format, and distributed-trace context, and
18+
- the **OpenTelemetry forwarder** (opt-in, `otel.forwarding=true`): the host's trace spans
19+
exported over OTLP/HTTP to Dynatrace, Splunk or a collector — no SDK, no new dependency.
1820

1921
Orchestration deliberately stays in the engines. Functions written here are addressed by
2022
route name through the engines' declarative `yaml.event.over.http` map, so a flow or a

‎docs/guides/config-logging-actuators.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,45 @@ one way in the aggregator:
4545
(pretty-printed) and `compact` (single-line JSONL for log aggregators). The level
4646
comes from the `LOG_LEVEL` environment variable when set, else `log.level`.
4747

48+
## Distributed tracing — the OpenTelemetry forwarder (opt-in)
49+
50+
Every traced, non-RPC execution emits the engines' distributed-trace dataset on the
51+
`distributed.tracing` log stream — `{"trace": {...}, "annotations": {...}}`, the record the
52+
Java engine logs — so a log aggregation already stitches the span tree across all four
53+
runtimes. The forwarder is the second sink, for backends that take spans directly:
54+
Dynatrace, Splunk, an OpenTelemetry Collector.
55+
56+
```yaml
57+
otel.forwarding: true
58+
otel.exporter.otlp.endpoint: 'https://<tenant>.live.dynatrace.com/api/v2/otlp/v1/traces'
59+
otel.exporter.otlp.headers: 'Authorization=Api-Token ${DT_TOKEN}'
60+
otel.service.name: 'my-python-functions'
61+
```
62+
63+
With `otel.forwarding=true` (the switch is the only thing that turns it on — `false` by
64+
default, and `-Dotel.forwarding=true` at run time is enough), the host also hands each
65+
dataset to the engines' extension route `distributed.trace.forwarder`, where the built-in
66+
forwarder registers itself at start-up (private, two workers; an application that registers
67+
its own function on that route wins). Each dataset becomes **one OpenTelemetry span carrying
68+
the host's exact W3C trace, span and parent-span ids** — the same mapping as the engines'
69+
forwarders, so one trace spans the engine that called and the function here — and is
70+
exported over OTLP/HTTP as protobuf, one span per request. There is no OpenTelemetry SDK
71+
and no new dependency: the encoder is the engines' own hand-written OTLP writer, ported.
72+
73+
Request headers are re-read on every export, so a credential a start-up bootstrap publishes
74+
with `config.set(...)` after the forwarder started takes effect without a restart; header
75+
**names** appear in the log, never values. A transport failure or a 408/429/502/503/504
76+
answer is retried five times on the OpenTelemetry SDK's backoff (1 s growing by 1.5×);
77+
any other rejection is logged once with the status, the backend's message and a hint
78+
(`HTTP 401 ... | the backend rejected the credential itself - check otel.exporter.otlp.headers`).
79+
The start-up line confirms the configuration:
80+
`OpenTelemetry trace forwarder ready - service=..., OTLP endpoint=..., compression=none, credential headers=[...]`.
81+
82+
Differences from the engines: only `none` compression is honoured (a warning otherwise);
83+
`otel.exporter.otlp.connect.timeout` **is** honoured here (aiohttp's connect timeout); the
84+
instrumentation scope is `mercury-composable-python`, so a backend shows which runtime
85+
produced a span. The keys are listed in the [configuration reference](configuration-reference.md).
86+
4887
## Actuators — the engines' operational surface
4988

5089
The host serves the engines' endpoints on the same port as `/api/event`:

‎docs/guides/configuration-reference.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@ keywords: [configuration, reference, keys, substitution, overrides]
3232
| `show.application.properties` | opt-in list of configuration keys shown by `/env` | (empty) |
3333
| `mandatory.health.dependencies` | routes of health check functions that decide `/health` | (empty) |
3434
| `optional.health.dependencies` | health check routes reported but never affecting status | (empty) |
35+
| `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)) | `false` |
36+
| `otel.exporter.otlp.endpoint` | the OTLP/HTTP traces URL including the signal path | `http://localhost:4318/v1/traces` |
37+
| `otel.exporter.otlp.headers` | request headers, `k=v` or `k: v`, comma-separated (re-read per export) | (none) |
38+
| `otel.exporter.otlp.timeout` | per-export timeout in milliseconds | `10000` |
39+
| `otel.exporter.otlp.connect.timeout` | connect timeout in milliseconds | the client default |
40+
| `otel.exporter.otlp.compression` | only `none` is honoured (a warning otherwise) | `none` |
41+
| `otel.service.name` | the `service.name` resource attribute of exported spans | `application.name` |
3542

3643
List-valued keys accept a comma/space-separated string (engine syntax) or a YAML list.
3744

‎docs/guides/function-patterns.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,9 @@ on the `distributed.tracing` log stream - the same
117117
`{"trace": {...}, "annotations": {...}}` record the Java engine logs - so a
118118
stdout log-ingest agent (Dynatrace-style) or any log aggregation stitches the
119119
span tree across all four runtimes. RPC round-trips fold into the caller's
120-
view, exactly like the engines.
120+
view, exactly like the engines. With `otel.forwarding=true` the same datasets are also
121+
exported as OpenTelemetry spans — see the
122+
[forwarder](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in).
121123

122124
**Application log context**: with `log.format` json/compact, every log line a
123125
function writes inside a traced request carries a `context` block (the

‎docs/llms.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
## Write functions
2222
- [Function Writing Patterns](https://accenture.github.io/mercury-python/guides/function-patterns/): the (headers, body) contract, plain-def vs async-def, AppException, trace context, private functions, composition incl. the sync bridge.
23-
- [Configuration, Logging & Actuators](https://accenture.github.io/mercury-python/guides/config-logging-actuators/): resources convention, -D overrides, three log formats, actuator endpoints, health-function contract, Kubernetes probes.
23+
- [Configuration, Logging & Actuators](https://accenture.github.io/mercury-python/guides/config-logging-actuators/): resources convention, -D overrides, three log formats, actuator endpoints, health-function contract, Kubernetes probes, and the opt-in OpenTelemetry forwarder (`otel.forwarding=true`).
2424
- [Testing Your Functions](https://accenture.github.io/mercury-python/guides/testing/): handler tests, fresh-registry bus tests, real-HTTP host tests, golden wire vectors.
2525

2626
## Join the engines

‎examples/resources/application.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,12 @@ mandatory.health.dependencies: 'demo.health'
2020
# Opt-in lists for the /env endpoint - nothing is ever dumped wholesale.
2121
show.env.variables: 'LOG_LEVEL'
2222
show.application.properties: 'application.name, rest.server.port'
23+
24+
# OpenTelemetry forwarder (opt-in) - the engines' opentelemetry-forwarder twin. Switch it on
25+
# at run time with -Dotel.forwarding=true; the endpoint and credential come from the
26+
# environment (a Dynatrace endpoint ends in /api/v2/otlp/v1/traces; the header is the whole
27+
# 'Authorization=Api-Token' prefix, the token its value). Header names are logged, never values.
28+
otel.forwarding: false
29+
otel.exporter.otlp.endpoint: '${OTLP_API_ENDPOINT:http://localhost:4318/v1/traces}'
30+
otel.exporter.otlp.headers: '${OTLP_AUTH_HEADER} ${OTLP_TOKEN}'
31+
otel.service.name: '${OTLP_SERVICE_NAME:demo-app}'

‎src/mercury_composable/bus.py‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
from .exceptions import AppException
3939
from .log import get_logger
4040
from .trace import (
41+
DISTRIBUTED_TRACE_FORWARDER,
4142
MY_CID_TAG,
4243
MY_CORRELATION_ID,
4344
RPC_TAG,
@@ -132,13 +133,14 @@ def _is_rpc(delivery: _Delivery) -> bool:
132133

133134
def _emit_trace(delivery: _Delivery, info: TraceInfo, start: str,
134135
exec_time: float, status: int, success: bool,
135-
exception: str | None) -> None:
136+
exception: str | None) -> dict[str, Any] | None:
136137
"""Emit the engines' distributed-trace dataset for a traced, non-RPC
137138
execution - the same record shape the Java reference engine logs
138139
(message = {"trace": {...}, "annotations": {...}}), so polyglot log
139-
aggregation stitches spans across all runtimes."""
140+
aggregation stitches spans across all runtimes. Returns the dataset (for
141+
the extension route), or None when the execution emits none."""
140142
if not info.trace_id or _is_rpc(delivery):
141-
return
143+
return None
142144
from .actuator import app_origin # late: actuator imports the registry chain
143145
trace: dict[str, Any] = {
144146
"origin": app_origin(), "id": info.trace_id, "path": info.trace_path,
@@ -156,6 +158,7 @@ def _emit_trace(delivery: _Delivery, info: TraceInfo, start: str,
156158
if info.annotations:
157159
dataset["annotations"] = dict(info.annotations)
158160
telemetry_log.info(dataset)
161+
return dataset
159162

160163

161164
class EventBus:
@@ -319,9 +322,9 @@ async def _execute(self, delivery: _Delivery) -> EventEnvelope:
319322
reply.exec_time = round((time.perf_counter() - start) * 1000, 3)
320323
if info.annotations:
321324
reply.annotations.update(info.annotations)
322-
_emit_trace(delivery, info, start_iso, reply.exec_time,
323-
reply.get_status(), not reply.has_error(),
324-
str(reply.body) if reply.has_error() else None)
325+
self._forward(_emit_trace(delivery, info, start_iso, reply.exec_time,
326+
reply.get_status(), not reply.has_error(),
327+
str(reply.body) if reply.has_error() else None))
325328
return reply
326329

327330
async def _execute_interceptor(self, delivery: _Delivery) -> EventEnvelope:
@@ -362,12 +365,24 @@ async def _execute_interceptor(self, delivery: _Delivery) -> EventEnvelope:
362365
_reset_trace(token)
363366
status = error.status if isinstance(error, AppException) \
364367
else (500 if error else 200)
365-
_emit_trace(delivery, info, start_iso,
366-
round((time.perf_counter() - start) * 1000, 3),
367-
status, error is None, str(error) if error else None)
368+
self._forward(_emit_trace(delivery, info, start_iso,
369+
round((time.perf_counter() - start) * 1000, 3),
370+
status, error is None, str(error) if error else None))
368371
# an interceptor's own outcome is never auto-replied
369372
return EventEnvelope()
370373

374+
def _forward(self, dataset: dict[str, Any] | None) -> None:
375+
"""Hand an emitted dataset to the engines' extension route when a
376+
function is registered there (the OpenTelemetry forwarder, or an
377+
application's own). Delivered without a trace, so the forwarder's own
378+
execution emits no dataset - the engines' zero-tracing forwarder."""
379+
if dataset is None or self._registry is None:
380+
return
381+
service = self._registry.get(DISTRIBUTED_TRACE_FORWARDER)
382+
if service is None or service.interceptor:
383+
return
384+
self.publish(service, {}, dataset)
385+
371386
def _reply_interceptor_error(self, route: str, event: EventEnvelope,
372387
e: Exception) -> None:
373388
if isinstance(e, AppException):
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"""
2+
The OpenTelemetry trace forwarder - the engines' ``opentelemetry-forwarder``
3+
extension for this host, opt-in and dependency-free.
4+
5+
Every traced, non-RPC execution already emits the engines' distributed-trace
6+
dataset on the ``distributed.tracing`` log stream. With ``otel.forwarding=true``
7+
the host ALSO hands each dataset to a function on the engines' extension route
8+
``distributed.trace.forwarder``; the built-in forwarder registered there maps
9+
the dataset to one OpenTelemetry span carrying the host's exact W3C ids and
10+
exports it over OTLP/HTTP (protobuf) to the configured endpoint - Dynatrace,
11+
Splunk, an OpenTelemetry Collector - so one trace spans the engines and the
12+
polyglot functions they call. Off by default: the switch is the only thing
13+
that turns it on.
14+
"""
15+
from __future__ import annotations
16+
17+
from collections.abc import Awaitable, Callable
18+
from typing import Any
19+
20+
from ..log import get_logger
21+
from ..trace import DISTRIBUTED_TRACE_FORWARDER
22+
from .config import FORWARDING_SWITCH, HEADERS, ForwarderSettings, parse_headers
23+
from .export import INSTRUMENTATION_SCOPE, Exporter, ExportFailure, describe_http_failure
24+
from .span import Span, span_from_dataset
25+
26+
__all__ = [
27+
"DISTRIBUTED_TRACE_FORWARDER",
28+
"FORWARDING_SWITCH",
29+
"INSTRUMENTATION_SCOPE",
30+
"ExportFailure",
31+
"Exporter",
32+
"ForwarderSettings",
33+
"Span",
34+
"activate",
35+
"describe_http_failure",
36+
"forwarder",
37+
"parse_headers",
38+
"span_from_dataset",
39+
]
40+
41+
log = get_logger("mercury.otel")
42+
43+
# the engines run the forwarder with two workers
44+
FORWARDER_INSTANCES = 2
45+
46+
47+
def forwarder(exporter: Exporter) -> Callable[[dict[str, str], Any], Awaitable[None]]:
48+
"""The ``distributed.trace.forwarder`` function bound to one exporter: map
49+
the dataset to a span and export it, logging - never raising - a failure."""
50+
51+
async def forward(_headers: dict[str, str], body: Any) -> None:
52+
# a dataset without W3C-valid ids cannot become a span without forging ids - skipped
53+
span = span_from_dataset(body)
54+
if span is None:
55+
return
56+
try:
57+
await exporter.export(span)
58+
except ExportFailure as failure:
59+
log.warning("OTLP export failed for span %s of trace %s - %s",
60+
span.span_id_hex, span.trace_id_hex, failure)
61+
62+
return forward
63+
64+
65+
def enabled(config: Any) -> bool:
66+
"""Whether ``otel.forwarding`` is switched on (the text ``true``, case-insensitive)."""
67+
value = config.get_property(FORWARDING_SWITCH)
68+
return value is not None and value.strip().lower() == "true"
69+
70+
71+
def activate(config: Any, registry: Any) -> Exporter | None:
72+
"""Register the built-in forwarder on ``distributed.trace.forwarder`` when
73+
``otel.forwarding=true`` - the host's start-up hook. Returns the exporter
74+
(so the host can close it at shutdown), or ``None`` when forwarding is off
75+
or a function already occupies the route (an application's own forwarder
76+
wins, as in the engines). A misconfigured endpoint fails the start."""
77+
if not enabled(config):
78+
return None
79+
if registry.exists(DISTRIBUTED_TRACE_FORWARDER):
80+
log.info("%s is provided by the application - the built-in OpenTelemetry forwarder "
81+
"stands down", DISTRIBUTED_TRACE_FORWARDER)
82+
return None
83+
exporter = Exporter(ForwarderSettings.from_config(config))
84+
names = exporter.header_names()
85+
log.info("OpenTelemetry trace forwarder ready - service=%s, OTLP endpoint=%s, "
86+
"compression=%s, credential headers=%s", exporter.service_name, exporter.endpoint,
87+
exporter.compression, names)
88+
if not names:
89+
log.info("No OTLP credential header yet (%s unset) - it is re-read on every export, so "
90+
"a credential published later takes effect without a restart", HEADERS)
91+
registry.register(DISTRIBUTED_TRACE_FORWARDER, forwarder(exporter),
92+
instances=FORWARDER_INSTANCES, private=True)
93+
return exporter

0 commit comments

Comments
 (0)