generateTracingContext function

TracingContext generateTracingContext(
  1. AtatusSdk sdk,
  2. AtatusRum rum, {
  3. TracingId? parentSpanId,
})

Generate a tracing context.

Pass parentSpanId when the request is a child of a span created elsewhere (e.g. a manually started Flutter span). 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();

  TracingId? effectiveParentSpanId = parentSpanId;

  if (activeTrace != null) {
    if (rum.isTraceRoot) {
      // First request after startTrace(). This becomes the true root span of the trace.
      // We don't inherit the activeTrace's spanId as a parent because it was never reported.
      effectiveParentSpanId = null;
      rum.isTraceRoot = false;
    } else {
      // Subsequent requests inherit the previous span's ID as their parent.
      effectiveParentSpanId = parentSpanId ?? activeTrace.spanId;
    }
  }

  final context = sdk.platform.getContext();
  bool sampled = activeTrace != null
      ? activeTrace.sampled
      : rum.shouldSampleTrace(context?.sessionId, traceId);

  final newContext = TracingContext(
    traceId,
    spanId,
    effectiveParentSpanId,
    context?.sessionId,
    context?.userId,
    context?.accountId,
    sampled,
  );

  // If a manual trace is active, update it with this new context so the NEXT
  // request will become a child of THIS request. This forms a chain.
  if (activeTrace != null) {
    rum.activeTraceContext = newContext;
  }

  return newContext;
}