12 private readonly
object _sync =
new();
13 private readonly Func<double> _clock;
14 private readonly Dictionary<long, TelemetrySource> _sources = [];
15 private Queue<TelemetrySnapshot> _history =
new(120);
18 private long _nextId, _generation;
19 private int _requests;
20 private bool _disposed, _truncated;
21 private double _started;
24 public RuntimeProfiler() : this(() => Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency) { }
47 ArgumentNullException.ThrowIfNull(options);
52 ObjectDisposedException.ThrowIf(_disposed,
this);
55 throw new InvalidOperationException(
"Configure telemetry while inactive.");
57 if (_sources.Count > options.SourceCapacity ||
58 _sources.Values.Any(s => s.Metrics.Count > options.MetricCapacity))
59 throw new InvalidOperationException(
"Configured limits are smaller than registered detail.");
62 _history =
new Queue<TelemetrySnapshot>(options.HistoryCapacity);
73 ObjectDisposedException.ThrowIf(_disposed,
this);
81 foreach (var source
in _sources.Values)
82 foreach (var accumulator
in source.Metrics.Values)
87 return new Request(
this);
98 ValidateName(backend);
102 ObjectDisposedException.ThrowIf(_disposed,
this);
104 if (_sources.Count >= _options.SourceCapacity)
116 _sources.Add(source.Id, source);
125 internal TelemetrySource? TryRegisterSource(
string name,
string backend)
138 return _latestSnapshot;
149 return Array.AsReadOnly(_history.ToArray());
158 ObjectDisposedException.ThrowIf(_disposed,
this);
176 _latestSnapshot =
null;
182 internal long Begin() =>
IsCollecting ? Volatile.Read(ref _generation) : 0;
190 internal bool Define(
200 if (!_sources.ContainsKey(source.
Id))
203 if (source.Metrics.TryGetValue(name, out var existing))
207 existing.Availability = availability;
212 if (source.Metrics.Count >= _options.MetricCapacity)
218 source.Metrics.Add(name,
new Accumulator { Availability = availability, Kind = kind });
228 internal void Record(
229 TelemetrySource source,
234 if (generation == 0 || !
IsCollecting || !
double.IsFinite(value))
239 if (_requests == 0 || generation != _generation || !_sources.ContainsKey(source.Id))
244 if (!source.Metrics.TryGetValue(metric, out var accumulator))
250 accumulator.Add(value, _clock());
256 internal void Retire(TelemetrySource source)
259 _sources.Remove(source.Id);
264 internal void MarkTruncated(
long generation)
268 if (generation == _generation && _requests != 0)
273 private static void ValidateName(
string name)
275 if (
string.IsNullOrWhiteSpace(name) || name.Length > 96)
276 throw new ArgumentException(
"Names must contain 1–96 characters.", nameof(name));
279 private void ResetCore()
283 _latestSnapshot =
null;
287 foreach (var source
in _sources.Values)
288 foreach (var accumulator
in source.Metrics.Values)
289 accumulator.Rebase();
292 private void ClearAccumulators()
294 foreach (var source
in _sources.Values)
295 foreach (var accumulator
in source.Metrics.Values)
299 private void Advance()
304 double now = _clock();
306 if (now - _started >= _options.Interval.TotalSeconds)
310 private void Publish(
double now)
316 new ReadOnlyDictionary<string, TelemetrySummary>(
317 source.Metrics.ToDictionary(p => p.Key, p => p.Value.Snapshot())))).ToArray();
319 if (_history.Count == _options.HistoryCapacity)
322 _latestSnapshot =
new(
326 Array.AsReadOnly(sources),
329 _history.Enqueue(_latestSnapshot);
343 double now = _clock();
357 private RuntimeProfiler? _owner = owner;
362 public void Dispose() => Interlocked.Exchange(ref _owner,
null)?.Stop();
366 internal sealed class Accumulator
375 private double _sum, _min, _max, _last, _observed;
376 private double? _baseline;
381 internal void Add(
double value,
double observed)
383 _min = _count == 0 ? value : Math.Min(_min, value);
384 _max = _count == 0 ? value : Math.Max(_max, value);
388 _observed = observed;
392 internal void Clear()
402 internal void Rebase() => _baseline =
null;
410 _count == 0 ? null : _min,
411 _count == 0 ? null : _max,
412 _count == 0 ? null : _last)
415 LastObservedSeconds = _count == 0 ? null : _observed,
416 WindowDelta = Kind == TelemetryMetricKind.LifetimeCounter && _count > 0 && _baseline is { } baseline
record TelemetrySummary(TelemetryAvailability Availability, long Count, double Sum, double? Minimum, double? Maximum, double? Last)
Detached statistics for observations in one window; durations use milliseconds.
record TelemetrySourceSnapshot(long Id, string Name, string Backend, IReadOnlyDictionary< string, TelemetrySummary > Metrics)
Detached source identity, backend label, and measurements. No runtime objects are retained.
record TelemetrySnapshot(long Generation, double StartedSeconds, double EndedSeconds, IReadOnlyList< TelemetrySourceSnapshot > Sources, bool Truncated)
Detached completed window. Sources can be observed asynchronously within its interval.