fix(otel): don't throw when calling setActiveSpan at root (#28323)

When calling `setActiveSpan` at the module root, or with `options.root =
true`, the function would internally throw.
This commit is contained in:
Luca Casonato 2025-02-27 18:47:09 +01:00 committed by GitHub
parent 1fe721f1f8
commit aa55efaa13
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 67 additions and 3 deletions

View file

@ -145,7 +145,7 @@ function hrToMs(hr: [number, number]): number {
export function enterSpan(span: Span): Context | undefined {
if (!span.isRecording()) return undefined;
const context = (CURRENT.get() || ROOT_CONTEXT).setValue(SPAN_KEY, span);
const context = (CURRENT.get() ?? ROOT_CONTEXT).setValue(SPAN_KEY, span);
return CURRENT.enter(context);
}
@ -254,9 +254,9 @@ class Tracer {
throw new Error("startActiveSpan requires a function argument");
}
if (options?.root) {
context = undefined;
context = ROOT_CONTEXT;
} else {
context = context ?? CURRENT.get();
context = context ?? CURRENT.get() ?? ROOT_CONTEXT;
}
const span = this.startSpan(name, options, context);
const ctx = CURRENT.enter(context.setValue(SPAN_KEY, span));

View file

@ -33,6 +33,10 @@
"links": {
"args": "run -A main.ts links.ts",
"output": "links.out"
},
"start_active_span": {
"args": "run -A main.ts start_active_span.ts",
"output": "start_active_span.out"
}
}
}

View file

@ -0,0 +1,48 @@
{
"spans": [
{
"traceId": "00000000000000000000000000000001",
"spanId": "0000000000000001",
"traceState": "",
"parentSpanId": "",
"flags": 1,
"name": "top level span",
"kind": 1,
"startTimeUnixNano": "[WILDCARD]",
"endTimeUnixNano": "[WILDCARD]",
"attributes": [],
"droppedAttributesCount": 0,
"events": [],
"droppedEventsCount": 0,
"links": [],
"droppedLinksCount": 0,
"status": {
"message": "",
"code": 0
}
},
{
"traceId": "00000000000000000000000000000002",
"spanId": "0000000000000002",
"traceState": "",
"parentSpanId": "",
"flags": 1,
"name": "root span",
"kind": 1,
"startTimeUnixNano": "[WILDCARD]",
"endTimeUnixNano": "[WILDCARD]",
"attributes": [],
"droppedAttributesCount": 0,
"events": [],
"droppedEventsCount": 0,
"links": [],
"droppedLinksCount": 0,
"status": {
"message": "",
"code": 0
}
}
],
"logs": [],
"metrics": []
}

View file

@ -0,0 +1,12 @@
// Copyright 2018-2025 the Deno authors. MIT license.
import { trace } from "npm:@opentelemetry/api@1.9.0";
const tracer = trace.getTracer("example-tracer");
tracer.startActiveSpan("top level span", (span) => {
span.end();
});
tracer.startActiveSpan("root span", { root: true }, (span) => {
span.end();
});