Path: redb-route/redb.Route/Telemetry/MetricsSnapshot.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/MetricsSnapshot.cs
----
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using redb.Route.Abstractions;
namespace redb.Route.Telemetry;
///
/// One reading of one instrument: how many measurements, their sum, the extremes, and the last
/// value. For a counter the measurements are deltas, so is the running total;
/// for a histogram they are recorded values, so all five fields are meaningful.
///
public readonly record struct MetricSnapshotPoint(long Count, double Sum, double Min, double Max, double Last);
///
/// Read access to the OpenTelemetry layer from inside the process.
///
///
///
/// The "redb.Route" meter is push-only, as every .NET is: the EIP
/// counters (throttle.delayed, circuitbreaker.tripped, …) and the .Metered()
/// step durations go to a subscriber or nowhere. This service is that subscriber, kept in-process:
/// current values only — no windows, no percentiles, no history. Whoever needs those plugs in an
/// OpenTelemetry backend; a bus should not carry a small Prometheus inside.
///
///
/// Deliberately opt-in (context.UseMetricsSnapshot()): a
/// receives a callback for every measurement of every instrument,
/// which is a tax all routes would pay for a feature few ask for.
///
///
public interface IMetricsSnapshot
{
///
/// The current point of an instrument, keyed exactly by its tags:
/// matches the redb.route.id tag, the redb.route.step
/// tag; null means the measurement carried no such tag. No aggregation across keys —
/// a point either was recorded with these tags or there is nothing to return.
///
/// Instrument name, e.g. redb.route.step.duration.
/// Value of the redb.route.id tag, or null for untagged.
/// Value of the redb.route.step tag, or null for untagged.
/// The point, or null when nothing was recorded under this key.
MetricSnapshotPoint? Point(string instrument, string? routeId = null, string? step = null);
///
/// Convenience reading: the — a counter's running
/// total, a histogram's sum of values.
///
double? Value(string instrument, string? routeId = null, string? step = null);
}
///
/// The in-process subscriber behind : a
/// on the "redb.Route" meter, accumulating per (instrument, route id, step).
///
internal sealed class MetricsSnapshotListener : IMetricsSnapshot, IDisposable
{
private sealed class Accumulator
{
private readonly object _gate = new();
private long _count;
private double _sum;
private double _min = double.PositiveInfinity;
private double _max = double.NegativeInfinity;
private double _last;
public void Add(double value)
{
lock (_gate)
{
_count++;
_sum += value;
if (value < _min) _min = value;
if (value > _max) _max = value;
_last = value;
}
}
public MetricSnapshotPoint Read()
{
lock (_gate)
{
return new MetricSnapshotPoint(_count, _sum, _min, _max, _last);
}
}
}
private readonly ConcurrentDictionary<(string Instrument, string RouteId, string Step), Accumulator> _points = new();
private readonly MeterListener _listener;
private int _disposed;
public MetricsSnapshotListener()
{
_listener = new MeterListener
{
InstrumentPublished = (instrument, listener) =>
{
if (instrument.Meter.Name == RouteMetrics.MeterName)
listener.EnableMeasurementEvents(instrument);
}
};
_listener.SetMeasurementEventCallback((instrument, value, tags, _) => Record(instrument.Name, value, tags));
_listener.SetMeasurementEventCallback((instrument, value, tags, _) => Record(instrument.Name, value, tags));
_listener.Start();
}
private void Record(string instrument, double value, ReadOnlySpan> tags)
{
string routeId = "", step = "";
foreach (var tag in tags)
{
if (tag.Key == "redb.route.id") routeId = tag.Value?.ToString() ?? "";
else if (tag.Key == "redb.route.step") step = tag.Value?.ToString() ?? "";
}
_points.GetOrAdd((instrument, routeId, step), static _ => new Accumulator()).Add(value);
}
///
public MetricSnapshotPoint? Point(string instrument, string? routeId = null, string? step = null)
=> _points.TryGetValue((instrument, routeId ?? "", step ?? ""), out var acc) ? acc.Read() : null;
///
public double? Value(string instrument, string? routeId = null, string? step = null)
=> Point(instrument, routeId, step)?.Sum;
///
/// Stops listening. Collected points stay readable — an operator inspecting a stopped context
/// still sees what it measured.
///
public void Dispose()
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0) return;
_listener.Dispose();
}
}
///
/// Registration for , following the same order as every other
/// pluggable service here: what the context was told, then the DI container — and no default,
/// because the whole point is that nobody pays for the listener without asking for it.
///
public static class MetricsSnapshotRegistration
{
///
/// Starts an in-process subscriber to the "redb.Route" meter on this context. The
/// listener is disposed when the context stops; calling twice keeps the first subscriber.
///
public static IRouteContext UseMetricsSnapshot(this IRouteContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (context.GetService() is not null)
return context;
var listener = new MetricsSnapshotListener();
context.AddService(typeof(IMetricsSnapshot), listener);
context.AddLifecycleListener(new DisposeOnStop(listener));
return context;
}
/// DI registration: services.AddMetricsSnapshot().
public static IServiceCollection AddMetricsSnapshot(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services);
services.TryAddSingleton(_ => new MetricsSnapshotListener());
return services;
}
///
/// Resolves the snapshot, or null when none was registered — there is deliberately no
/// always-on default.
///
public static IMetricsSnapshot? GetMetricsSnapshot(this IRouteContext? context)
=> context?.GetService()
?? context?.GetServiceProvider()?.GetService(typeof(IMetricsSnapshot)) as IMetricsSnapshot;
private sealed class DisposeOnStop(IDisposable listener) : IRouteLifecycleListener
{
public Task OnContextStopped(IRouteContext context, CancellationToken ct)
{
listener.Dispose();
return Task.CompletedTask;
}
}
}