Path: redb-route/tests/Shared/SpanCapture.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/Shared/SpanCapture.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Trace; using redb.Route.Telemetry; namespace redb.Route.Tests.Shared; /// /// Collects the route spans of one test through the OpenTelemetry SDK. A tracer provider sees every span the route /// source emits in the process, those of test classes running in parallel included, and it records them from their /// threads. The capture therefore opens a root span for the test, keeps only the route spans of that trace (what the /// test itself caused), and keeps them in a thread-safe queue. /// /// /// Create it before the step that emits the span, in the test's own flow: the root becomes /// for the rest of the test, so the spans the step opens are its children. /// internal sealed class SpanCapture : IDisposable { private static readonly ActivitySource TestSource = new("redb.Route.Tests.SpanCapture"); private readonly ConcurrentQueue _spans = new(); private readonly TracerProvider _provider; // Set right after the provider is built. Between the two, a span of a test running in parallel can end and reach // the collector: it must find no root and keep nothing, never throw into that test's thread (findings register // row 45: a NullReferenceException here failed FileProducer tests that use no capture at all). private volatile Activity? _root; public SpanCapture() { _provider = Sdk.CreateTracerProviderBuilder() .AddSource(RouteActivitySource.SourceName, TestSource.Name) .AddProcessor(new Collector(this)) .Build()!; _root = TestSource.StartActivity("test") ?? throw new InvalidOperationException("The capture's own tracer provider must sample the test root span."); } /// The route spans of this test, after the provider has been flushed. public IReadOnlyList Spans { get { _provider.ForceFlush(1000); return _spans.ToArray(); } } public void Dispose() { _root?.Dispose(); _provider.Dispose(); } private sealed class Collector(SpanCapture owner) : BaseProcessor { public override void OnEnd(Activity data) { if (owner._root is { } root && data.Source.Name == RouteActivitySource.SourceName && data.TraceId == root.TraceId) owner._spans.Enqueue(data); } } }