generateTracingContext function
Generate a tracing context.
While a manual trace is active (AtatusRum.startTrace) the context joins that trace. The first request made in the trace becomes its root span, and every later request is a direct child of that first request, so they are siblings rather than each nesting inside the request before it. Outside a manual trace each call starts its own trace.
Pass parentSpanId when the request is a child of a span created
elsewhere (e.g. a manually started Flutter span); it takes precedence over
the active trace's root. The parent span id is surfaced both in
distributed-tracing headers (B3 multi X-B3-ParentSpanId, W3C
tracestate) and as the _atatus.parent_span_id resource attribute.
Implementation
// ATCHG - Change class name from DDSdk to AtatusSdk
TracingContext generateTracingContext(
AtatusSdk sdk,
AtatusRum rum, {
TracingId? parentSpanId,
}) {
final activeTrace = rum.activeTraceContext;
final traceId =
activeTrace != null ? activeTrace.traceId : TracingId.traceId();
final spanId = TracingId.spanId();
// Inside a manual trace (`startTrace`) the first request is the root span
// and every later one is its child. Both are reported RUM resources, so no
// request points at a parent that never arrives (a "missing span"). The
// trace's own context is only a carrier for the trace id and sampling
// decision - its span id is never reported, so it is never a parent. The
// active context is deliberately left untouched here: replacing it with
// each request's context is what used to nest requests one inside the next.
var effectiveParentSpanId = parentSpanId;
if (activeTrace != null) {
final rootSpanId = rum.traceRootSpanId;
if (rootSpanId == null) {
rum.traceRootSpanId = spanId;
} else {
effectiveParentSpanId ??= rootSpanId;
}
}
final context = sdk.platform.getContext();
bool sampled = activeTrace != null
? activeTrace.sampled
: rum.shouldSampleTrace(context?.sessionId, traceId);
return TracingContext(
traceId,
spanId,
effectiveParentSpanId,
context?.sessionId,
context?.userId,
context?.accountId,
sampled,
);
}