Path: redb-route/redb.Route/Telemetry/RouteTelemetryExtensions.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/redb.Route/Telemetry/RouteTelemetryExtensions.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Telemetry; /// Reads one trace field (traceparent, tracestate, baggage) from a transport carrier; /// null when the carrier does not hold it. Header names are compared the way the transport compares them. /// Headers, message properties, attributes — whatever the transport carries. public delegate string? TraceHeaderReader(TCarrier carrier, string name); /// Writes one trace field to a transport carrier, replacing a value already there: a header copied /// from the incoming message names the previous hop, not this one. /// Headers, message properties, attributes — whatever the transport carries. public delegate void TraceHeaderWriter(TCarrier carrier, string name, string value); /// Where an inbound span takes its parent from. public enum InboundParent { /// /// From the trace fields of the message itself. Without them the span is a root: the thread's ambient activity /// (a poll loop, a host span of some other work) is never the parent of a message it did not send. /// Carrier, /// /// The host's span for this same request, when there is one — an ASP.NET Core server span has already taken the /// caller's context from the request headers. Without one the carrier is read, as with . /// HostRequest, } /// /// An inbound transport span opened by . Disposing /// it ends the span and gives the thread back the ambient activity it had before. /// public readonly struct TransportSpan : IDisposable { private readonly Activity? _ambient; internal TransportSpan(Activity? activity, Activity? ambient) { Activity = activity; _ambient = ambient; } /// The span; null when nobody listens or tracing is off for the context. public Activity? Activity { get; } /// public void Dispose() { if (Activity is null) return; Activity.Dispose(); // A span with a remote parent or none stops into a null current; the thread had its own before. System.Diagnostics.Activity.Current = _ambient; } } /// /// The tracing contract of a transport, on the shared : open the span /// ( /// outbound, inbound), carry the context to the next hop /// () and mark a failed call (). Every span /// carries redb.route.endpoint, sanitized, and honours RouteEngineOptions.EnableTelemetry of the context. /// A connector supplies only the carrier and its names; the W3C and baggage handling lives here once. /// public static class RouteTelemetryExtensions { /// /// Whether spans are opened for : its RouteEngineOptions.EnableTelemetry. /// true without a context — a component used on its own traces as before. /// public static bool IsTracingEnabled(this IRouteContext? context) => (context as RouteContext)?.TelemetryEnabled ?? true; /// /// Starts a messaging / RPC / I/O span for a transport operation. /// Tags are emitted following the OpenTelemetry semantic conventions for the /// supplied namespace. Does not read EnableTelemetry; a connector passes its /// context to the overload that does. /// /// Span name, e.g. "queue.name publish" or "GET /users/{id}". /// Activity kind (Producer / Consumer / Client / Server). /// /// Semantic-convention attribute name. Use "messaging.system" for brokers, /// "db.system" for databases, "rpc.system" for gRPC, /// "http.method" for plain HTTP or "file.system" for file transports. /// /// Value of the (e.g. "rabbitmq"). /// The full redb.route endpoint URI; always emitted as redb.route.endpoint. /// Optional destination (queue/topic/path) emitted as messaging.destination.name. /// Optional verb emitted as messaging.operation when relevant. /// The opened activity, or null when no listener is active. public static Activity? StartTransportSpan( string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, string? destination = null, string? operation = null) { var activity = RouteActivitySource.Source.StartActivity(name, kind); Tag(activity, systemAttribute, systemValue, endpointUri, destination, operation); return activity; } /// /// for an /// endpoint of : null when the context has tracing off. /// /// The route context of the endpoint (ComponentBase.Context). /// Span name. /// Activity kind (Producer / Client). /// Semantic-convention attribute name. /// Value of the . /// The endpoint URI, emitted sanitized as redb.route.endpoint. /// Optional destination, emitted sanitized as messaging.destination.name. /// Optional verb emitted as messaging.operation. public static Activity? StartTransportSpan( IRouteContext? context, string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, string? destination = null, string? operation = null) => context.IsTracingEnabled() ? StartTransportSpan(name, kind, systemAttribute, systemValue, endpointUri, destination, operation) : null; /// /// Opens the span of an inbound message or request. Its parent is chosen by ; with /// the W3C fields are read from and, when absent, /// the span is a root — never a child of whatever activity the receiving thread happens to hold. The baggage /// the sender put on its activity is put back on this one, so the route's own spans and sends carry it on. /// /// The route context of the endpoint; tracing off opens nothing. /// Span name, e.g. "orders receive". /// for a message, for a request. /// Semantic-convention attribute name. /// Value of the . /// The endpoint URI, emitted sanitized as redb.route.endpoint. /// The incoming message's headers or properties. /// Reads one field from . /// Where the parent comes from. /// Optional destination, emitted sanitized as messaging.destination.name. /// Optional verb emitted as messaging.operation. /// Links to other contexts, e.g. every message of a batch (). public static TransportSpan StartConsumerSpan( IRouteContext? context, string name, ActivityKind kind, string systemAttribute, string systemValue, string endpointUri, TCarrier carrier, TraceHeaderReader readHeader, InboundParent parent = InboundParent.Carrier, string? destination = null, string? operation = null, IEnumerable? links = null) { ArgumentNullException.ThrowIfNull(readHeader); if (!context.IsTracingEnabled()) return default; var ambient = Activity.Current; Activity? activity; if (parent == InboundParent.HostRequest && ambient is not null) { activity = RouteActivitySource.Source.StartActivity(name, kind, parentContext: default, tags: null, links); } else { var fields = new CarrierReader(carrier, readHeader); var remote = Extract(fields); // StartActivity with a default parent context falls back to Activity.Current rather than starting a root // (the house pattern, see DetachedDispatch.Enter): clear it for the start, give it back on dispose. Activity.Current = null; activity = RouteActivitySource.Source.StartActivity(name, kind, remote, tags: null, links); if (activity is null) { Activity.Current = ambient; } else if (DistributedContextPropagator.Current.ExtractBaggage(fields, Getter) is { } baggage) { // AddBaggage puts an item first; adding in reverse keeps the sender's order. foreach (var (key, value) in baggage.Reverse()) activity.AddBaggage(key, value); } } Tag(activity, systemAttribute, systemValue, endpointUri, destination, operation); return new TransportSpan(activity, ambient); } /// /// The W3C context holds, or default when it holds none or an invalid one. For /// links: a batch span links the context of every message it carries. /// /// The message's headers or properties. /// Reads one field from . public static ActivityContext ExtractTraceContext(TCarrier carrier, TraceHeaderReader readHeader) { ArgumentNullException.ThrowIfNull(readHeader); return Extract(new CarrierReader(carrier, readHeader)); } /// /// Writes the trace context of — or, without one, of the ambient activity — to an /// outgoing message: traceparent, tracestate and the baggage, through the process's /// . A context the route received is passed on even with tracing off, /// so a redb hop does not cut the trace of the systems around it. Writes nothing when there is no context. /// /// The send span; null falls back to . /// The outgoing message's headers or properties. /// Writes one field, replacing a value already there. public static void InjectTraceContext(Activity? activity, TCarrier carrier, TraceHeaderWriter writeHeader) { ArgumentNullException.ThrowIfNull(writeHeader); activity ??= Activity.Current; if (activity is null) return; DistributedContextPropagator.Current.Inject(activity, new CarrierWriter(carrier, writeHeader), Setter); } /// /// Marks the span failed by : status and an /// OpenTelemetry exception event — the shape the route spans use, so a failed call shows red on the /// transport span, not only on the route above it. /// /// The span; null does nothing. /// What failed. public static void RecordFailure(this Activity? activity, Exception exception) { ArgumentNullException.ThrowIfNull(exception); if (activity is null) return; activity.SetStatus(ActivityStatusCode.Error, exception.Message); if (activity.IsAllDataRequested) activity.RecordException(exception); } private static void Tag(Activity? activity, string systemAttribute, string systemValue, string endpointUri, string? destination, string? operation) { if (activity is not { IsAllDataRequested: true }) return; activity.SetTag(systemAttribute, systemValue); activity.SetTag("redb.route.endpoint", EndpointUri.Sanitize(endpointUri)); // The destination is often a full URL and may carry a userinfo password or a // sensitive query value; Sanitize is format-preserving and leaves plain names // (queues, topics) byte-for-byte. if (!string.IsNullOrEmpty(destination)) activity.SetTag("messaging.destination.name", EndpointUri.Sanitize(destination)); if (!string.IsNullOrEmpty(operation)) activity.SetTag("messaging.operation", operation); } private static ActivityContext Extract(ICarrierReader fields) { DistributedContextPropagator.Current.ExtractTraceIdAndState(fields, Getter, out var traceParent, out var traceState); return !string.IsNullOrEmpty(traceParent) && ActivityContext.TryParse(traceParent, traceState, out var parsed) ? parsed : default; } private interface ICarrierReader { string? Read(string name); } private sealed class CarrierReader(TCarrier carrier, TraceHeaderReader read) : ICarrierReader { public string? Read(string name) => read(carrier, name); } private interface ICarrierWriter { void Write(string name, string value); } private sealed class CarrierWriter(TCarrier carrier, TraceHeaderWriter write) : ICarrierWriter { public void Write(string name, string value) => write(carrier, name, value); } private static readonly DistributedContextPropagator.PropagatorGetterCallback Getter = static (object? carrier, string name, out string? value, out IEnumerable? values) => { values = null; value = (carrier as ICarrierReader)?.Read(name); }; private static readonly DistributedContextPropagator.PropagatorSetterCallback Setter = static (carrier, name, value) => (carrier as ICarrierWriter)?.Write(name, value); }