Skip to content

Commit 0db1121

Browse files
fix(diagnostics-otel): route OTLP endpoints by signal
Keep shared endpoint routing signal-aware while preserving explicit signal-specific URLs exactly. Cover the resolver through mocked constructors and real OTLP/HTTP trace, metric, and log exporters. Co-authored-by: Darren2030 <[email protected]>
1 parent 9ef94e4 commit 0db1121

4 files changed

Lines changed: 227 additions & 23 deletions

File tree

‎docs/gateway/opentelemetry.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,19 @@ and export only when `diagnostics.otel.logs` is explicitly `true`. Log export
8989
defaults to OTLP; set `diagnostics.otel.logsExporter` to `stdout` for JSONL on
9090
stdout, or `both` for both.
9191

92+
<Note>
93+
The shared `endpoint` and `OTEL_EXPORTER_OTLP_ENDPOINT` are bases for all
94+
enabled signals. OpenClaw appends `/v1/traces`, `/v1/metrics`, or `/v1/logs`
95+
to root and custom collector paths. For compatibility with hosted frontends,
96+
a shared endpoint already ending in one of those signal paths keeps that path
97+
for its matching signal and replaces the terminal segment for the others.
98+
99+
Signal-specific `tracesEndpoint`, `metricsEndpoint`, and `logsEndpoint`
100+
settings, plus their matching `OTEL_EXPORTER_OTLP_*_ENDPOINT` fallbacks, are
101+
passed to the exporter as exact URLs. OpenClaw does not append or rewrite their
102+
paths.
103+
</Note>
104+
92105
## Which processes export
93106

94107
- **Gateway** starts the exporter at startup and exports from the Gateway

‎extensions/diagnostics-otel/src/service-exporter.ts‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,35 @@ export function normalizeEndpoint(endpoint?: string): string | undefined {
1818
return trimmed ? trimmed.replace(/\/+$/, "") : undefined;
1919
}
2020

21-
function resolveOtelUrl(endpoint: string | undefined, path: string): string | undefined {
22-
if (!endpoint) {
23-
return undefined;
24-
}
21+
const SIGNAL_QUALIFIED_OTLP_PATH_PATTERN = /\/v1\/(traces|metrics|logs)$/iu;
22+
23+
function appendOrReplaceSignalPath(value: string, path: string): string {
24+
const base = value.replace(/\/+$/u, "");
25+
return SIGNAL_QUALIFIED_OTLP_PATH_PATTERN.test(base)
26+
? base.replace(SIGNAL_QUALIFIED_OTLP_PATH_PATTERN, `/${path}`)
27+
: `${base}/${path}`;
28+
}
29+
30+
function resolveSharedOtelUrl(endpoint: string, path: string): string {
2531
const endpointWithoutQueryOrFragment = endpoint.split(/[?#]/, 1)[0] ?? endpoint;
26-
if (/\/v1\/(?:traces|metrics|logs)$/i.test(endpointWithoutQueryOrFragment)) {
32+
const matchedSignal = endpointWithoutQueryOrFragment
33+
.replace(/\/+$/u, "")
34+
.match(SIGNAL_QUALIFIED_OTLP_PATH_PATTERN)?.[1];
35+
const requestedSignal = path.slice(path.lastIndexOf("/") + 1);
36+
if (matchedSignal?.toLowerCase() === requestedSignal.toLowerCase()) {
2737
return endpoint;
2838
}
2939
if (/[?#]/u.test(endpoint)) {
3040
const url = new URL(endpoint);
31-
const basePath = url.pathname.replace(/\/+$/u, "");
32-
url.pathname = `${basePath}/${path}`;
41+
url.pathname = appendOrReplaceSignalPath(url.pathname, path);
3342
return url.toString();
3443
}
35-
return `${endpoint}/${path}`;
44+
return appendOrReplaceSignalPath(endpoint, path);
45+
}
46+
47+
function normalizeSignalEndpoint(endpoint?: string): string | undefined {
48+
const trimmed = endpoint?.trim();
49+
return trimmed || undefined;
3650
}
3751

3852
export function resolveSignalOtelUrl(params: {
@@ -42,8 +56,8 @@ export function resolveSignalOtelUrl(params: {
4256
endpoint?: string;
4357
path: string;
4458
}): string | undefined {
45-
const endpoint =
46-
normalizeEndpoint(params.signalEndpoint ?? params.signalEnvEndpoint) ?? params.endpoint;
59+
const signalEndpoint = normalizeSignalEndpoint(params.signalEndpoint ?? params.signalEnvEndpoint);
60+
const endpoint = signalEndpoint ?? params.endpoint;
4761
// OTLP parses nonblank env values verbatim even when explicit config takes precedence.
4862
const signalEnvEndpoint = params.signalEnvEndpoint?.trim() ? params.signalEnvEndpoint : undefined;
4963
const sharedEnvEndpoint = params.sharedEnvEndpoint?.trim() ? params.sharedEnvEndpoint : undefined;
@@ -52,7 +66,9 @@ export function resolveSignalOtelUrl(params: {
5266
? `${consumedSharedEnvEndpoint}${consumedSharedEnvEndpoint.endsWith("/") ? "" : "/"}${params.path}`
5367
: undefined;
5468
const resolvedEndpoint =
55-
endpoint && URL.canParse(endpoint) ? resolveOtelUrl(endpoint, params.path) : endpoint;
69+
endpoint && URL.canParse(endpoint) && !signalEndpoint
70+
? resolveSharedOtelUrl(endpoint, params.path)
71+
: endpoint;
5672

5773
for (const candidate of [
5874
endpoint,

‎extensions/diagnostics-otel/src/service.otlp-export.test.ts‎

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
// Collector-boundary cases start the real NodeSDK, so teardown restores every global SDK
1010
// registration; otherwise a shutdown provider would poison later real-SDK cases.
1111
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
12+
import { createServer } from "node:http";
13+
import type { AddressInfo } from "node:net";
1214
import { tmpdir } from "node:os";
1315
import path from "node:path";
1416
import { context, diag, DiagLogLevel, metrics, propagation, trace } from "@opentelemetry/api";
@@ -36,6 +38,10 @@ import {
3638

3739
const PRELOAD_ENV = "OPENCLAW_OTEL_PRELOADED";
3840
const ENDPOINT_ENV_KEYS = [
41+
"OTEL_SDK_DISABLED",
42+
"OTEL_TRACES_EXPORTER",
43+
"OTEL_METRICS_EXPORTER",
44+
"OTEL_LOGS_EXPORTER",
3945
"OTEL_EXPORTER_OTLP_ENDPOINT",
4046
"OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
4147
"OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
@@ -179,6 +185,154 @@ function captureOtelDiagnostics(): string[] {
179185
return messages;
180186
}
181187

188+
async function startOtlpReceiver() {
189+
const requests: Array<{
190+
contentType: string | undefined;
191+
method: string | undefined;
192+
url: string;
193+
}> = [];
194+
const server = createServer((request, response) => {
195+
request.resume();
196+
request.on("end", () => {
197+
requests.push({
198+
contentType: request.headers["content-type"],
199+
method: request.method,
200+
url: request.url ?? "",
201+
});
202+
response.writeHead(200, { "content-type": "application/x-protobuf" });
203+
response.end();
204+
});
205+
});
206+
await new Promise<void>((resolve, reject) => {
207+
server.once("error", reject);
208+
server.listen(0, "127.0.0.1", resolve);
209+
});
210+
const { port } = server.address() as AddressInfo;
211+
return {
212+
endpoint: `http://127.0.0.1:${port}`,
213+
requests,
214+
async close() {
215+
await new Promise<void>((resolve, reject) => {
216+
server.close((error) => (error ? reject(error) : resolve()));
217+
server.closeIdleConnections();
218+
});
219+
},
220+
};
221+
}
222+
223+
function releasePreloadedOtelGlobals() {
224+
context.disable();
225+
logs.disable();
226+
metrics.disable();
227+
propagation.disable();
228+
trace.disable();
229+
process.env[PRELOAD_ENV] = "0";
230+
}
231+
232+
async function emitRealSdkSignals() {
233+
trace.getTracer("openclaw-otel-routing-test").startSpan("routing-test").end();
234+
metrics.getMeter("openclaw-otel-routing-test").createCounter("openclaw.routing.test").add(1);
235+
emit({
236+
type: "log.record",
237+
level: "INFO",
238+
message: "OTLP routing test",
239+
});
240+
await waitForDiagnosticEventsDrained();
241+
}
242+
243+
const SHARED_ENDPOINT_ROUTING_CASES = [
244+
{
245+
label: "root",
246+
suffix: "",
247+
expected: ["/v1/traces", "/v1/metrics", "/v1/logs"],
248+
},
249+
{
250+
label: "trailing-slash root",
251+
suffix: "/",
252+
expected: ["/v1/traces", "/v1/metrics", "/v1/logs"],
253+
},
254+
{
255+
label: "custom collector path",
256+
suffix: "/api/public/otel",
257+
expected: [
258+
"/api/public/otel/v1/traces",
259+
"/api/public/otel/v1/metrics",
260+
"/api/public/otel/v1/logs",
261+
],
262+
},
263+
{
264+
label: "signal-qualified collector path",
265+
suffix: "/api/public/otel/v1/traces",
266+
expected: [
267+
"/api/public/otel/v1/traces",
268+
"/api/public/otel/v1/metrics",
269+
"/api/public/otel/v1/logs",
270+
],
271+
},
272+
] as const;
273+
274+
test.each(SHARED_ENDPOINT_ROUTING_CASES)(
275+
"routes real exporters from a shared $label endpoint",
276+
async ({ suffix, expected }) => {
277+
const receiver = await startOtlpReceiver();
278+
releasePreloadedOtelGlobals();
279+
const { service, ctx } = await startOtelService({
280+
endpoint: `${receiver.endpoint}${suffix}`,
281+
traces: true,
282+
metrics: true,
283+
logs: true,
284+
});
285+
286+
try {
287+
await emitRealSdkSignals();
288+
await service.stop?.(ctx);
289+
290+
expect(new Set(receiver.requests.map((request) => request.url))).toEqual(new Set(expected));
291+
expect(
292+
receiver.requests.every(
293+
(request) =>
294+
request.method === "POST" && request.contentType === "application/x-protobuf",
295+
),
296+
).toBe(true);
297+
} finally {
298+
await service.stop?.(ctx);
299+
await receiver.close();
300+
}
301+
},
302+
30_000,
303+
);
304+
305+
test("uses real signal-specific exporter endpoints verbatim", async () => {
306+
const receiver = await startOtlpReceiver();
307+
releasePreloadedOtelGlobals();
308+
const traceEndpoint = `${receiver.endpoint}/custom-traces?tenant=red`;
309+
const metricEndpoint = `${receiver.endpoint}/custom-metrics/`;
310+
const logEndpoint = `${receiver.endpoint}/v1/traces`;
311+
const { service, ctx } = await startOtelService({
312+
endpoint: `${receiver.endpoint}/shared-unused`,
313+
traces: true,
314+
metrics: true,
315+
logs: true,
316+
configure: (serviceContext) => {
317+
serviceContext.config.diagnostics!.otel!.tracesEndpoint = traceEndpoint;
318+
serviceContext.config.diagnostics!.otel!.metricsEndpoint = metricEndpoint;
319+
serviceContext.config.diagnostics!.otel!.logsEndpoint = logEndpoint;
320+
},
321+
});
322+
323+
try {
324+
await emitRealSdkSignals();
325+
await service.stop?.(ctx);
326+
327+
expect(new Set(receiver.requests.map((request) => request.url))).toEqual(
328+
new Set(["/custom-traces?tenant=red", "/custom-metrics/", "/v1/traces"]),
329+
);
330+
} finally {
331+
await service.stop?.(ctx);
332+
await receiver.close();
333+
}
334+
}, 30_000);
335+
182336
// Covers all three completeTrackedLifecycleSpan owners: run.completed,
183337
// harness.run.completed, and message.processed. The mocked suite cannot tell the two id
184338
// spaces apart, so a regression at any one of them is only visible here.

‎extensions/diagnostics-otel/src/service.test.ts‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1797,6 +1797,25 @@ describe("diagnostics-otel service", () => {
17971797
expect(firstExporterOptions(traceExporterCtor).url).toBe(expected);
17981798
});
17991799

1800+
test("routes every signal from a shared signal-qualified endpoint", async () => {
1801+
await startOtelService({
1802+
endpoint: "https://collector.example.com/api/public/otel/v1/traces?tenant=red",
1803+
traces: true,
1804+
metrics: true,
1805+
logs: true,
1806+
});
1807+
1808+
expect(firstExporterOptions(traceExporterCtor).url).toBe(
1809+
"https://collector.example.com/api/public/otel/v1/traces?tenant=red",
1810+
);
1811+
expect(firstExporterOptions(metricExporterCtor).url).toBe(
1812+
"https://collector.example.com/api/public/otel/v1/metrics?tenant=red",
1813+
);
1814+
expect(firstExporterOptions(logExporterCtor).url).toBe(
1815+
"https://collector.example.com/api/public/otel/v1/logs?tenant=red",
1816+
);
1817+
});
1818+
18001819
test("applies flush interval to trace batching", async () => {
18011820
await startOtelService({
18021821
traces: true,
@@ -1829,24 +1848,26 @@ describe("diagnostics-otel service", () => {
18291848
metrics: true,
18301849
logs: true,
18311850
configure: (ctx) => {
1832-
ctx.config.diagnostics!.otel!.tracesEndpoint = "https://trace.example.com/otlp";
1833-
ctx.config.diagnostics!.otel!.metricsEndpoint = "https://metric.example.com/v1/metrics";
1834-
ctx.config.diagnostics!.otel!.logsEndpoint = "https://log.example.com/otlp";
1851+
ctx.config.diagnostics!.otel!.tracesEndpoint = "https://trace.example.com/custom";
1852+
ctx.config.diagnostics!.otel!.metricsEndpoint =
1853+
"https://metric.example.com/v1/traces?tenant=red";
1854+
ctx.config.diagnostics!.otel!.logsEndpoint = "https://log.example.com/otlp/";
18351855
},
18361856
});
18371857

18381858
const traceOptions = firstExporterOptions(traceExporterCtor);
18391859
const metricOptions = firstExporterOptions(metricExporterCtor);
18401860
const logOptions = firstExporterOptions(logExporterCtor);
1841-
expect(traceOptions.url).toBe("https://trace.example.com/otlp/v1/traces");
1842-
expect(metricOptions.url).toBe("https://metric.example.com/v1/metrics");
1843-
expect(logOptions.url).toBe("https://log.example.com/otlp/v1/logs");
1861+
expect(traceOptions.url).toBe("https://trace.example.com/custom");
1862+
expect(metricOptions.url).toBe("https://metric.example.com/v1/traces?tenant=red");
1863+
expect(logOptions.url).toBe("https://log.example.com/otlp/");
18441864
});
18451865

18461866
test("uses signal-specific OTLP env endpoints when config is unset", async () => {
1847-
process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = "https://trace-env.example.com/v1/traces";
1848-
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT = "https://metric-env.example.com/otlp";
1849-
process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT = "https://log-env.example.com/otlp";
1867+
process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT = "https://trace-env.example.com/custom";
1868+
process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT =
1869+
"https://metric-env.example.com/v1/traces?tenant=red";
1870+
process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT = "https://log-env.example.com/otlp/";
18501871

18511872
await startOtelService({
18521873
traces: true,
@@ -1857,9 +1878,9 @@ describe("diagnostics-otel service", () => {
18571878
const traceOptions = firstExporterOptions(traceExporterCtor);
18581879
const metricOptions = firstExporterOptions(metricExporterCtor);
18591880
const logOptions = firstExporterOptions(logExporterCtor);
1860-
expect(traceOptions.url).toBe("https://trace-env.example.com/v1/traces");
1861-
expect(metricOptions.url).toBe("https://metric-env.example.com/otlp/v1/metrics");
1862-
expect(logOptions.url).toBe("https://log-env.example.com/otlp/v1/logs");
1881+
expect(traceOptions.url).toBe("https://trace-env.example.com/custom");
1882+
expect(metricOptions.url).toBe("https://metric-env.example.com/v1/traces?tenant=red");
1883+
expect(logOptions.url).toBe("https://log-env.example.com/otlp/");
18631884
});
18641885

18651886
test("ignores malformed shared OTLP env when valid signal endpoints shadow it", async () => {

0 commit comments

Comments
 (0)