| | | 1 | | using Elsa.Diagnostics.OpenTelemetry.Contracts; |
| | | 2 | | using Elsa.Diagnostics.OpenTelemetry.Models; |
| | | 3 | | using Elsa.Diagnostics.OpenTelemetry.Options; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Diagnostics.OpenTelemetry.Services; |
| | | 7 | | |
| | | 8 | | public class OpenTelemetrySourceRegistry : IOpenTelemetrySourceRegistry |
| | | 9 | | { |
| | 16 | 10 | | private readonly object _lock = new(); |
| | 16 | 11 | | private readonly Dictionary<string, TelemetryResource> _resources = new(StringComparer.OrdinalIgnoreCase); |
| | | 12 | | private readonly int _capacity; |
| | | 13 | | private long _droppedCount; |
| | | 14 | | |
| | 16 | 15 | | public OpenTelemetrySourceRegistry(IOptions<OpenTelemetryDiagnosticsOptions> options) |
| | | 16 | | { |
| | 16 | 17 | | _capacity = Math.Max(1, options.Value.ResourceCapacity); |
| | 16 | 18 | | } |
| | | 19 | | |
| | 0 | 20 | | public OpenTelemetrySourceRegistry() : this(Microsoft.Extensions.Options.Options.Create(new OpenTelemetryDiagnostics |
| | | 21 | | { |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | public long DroppedCount |
| | | 25 | | { |
| | | 26 | | get |
| | | 27 | | { |
| | 2 | 28 | | lock (_lock) |
| | 2 | 29 | | return _droppedCount; |
| | 2 | 30 | | } |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | public void MarkSeen(TelemetryResource resource) |
| | | 34 | | { |
| | 15 | 35 | | lock (_lock) |
| | | 36 | | { |
| | 15 | 37 | | if (!_resources.ContainsKey(resource.Id) && _resources.Count >= _capacity) |
| | 1 | 38 | | RemoveOldestResource(); |
| | | 39 | | |
| | 15 | 40 | | _resources[resource.Id] = resource; |
| | 15 | 41 | | } |
| | 15 | 42 | | } |
| | | 43 | | |
| | | 44 | | public IReadOnlyCollection<TelemetryResource> List() |
| | | 45 | | { |
| | 7 | 46 | | lock (_lock) |
| | 19 | 47 | | return _resources.Values.OrderBy(x => x.ServiceName, StringComparer.OrdinalIgnoreCase).ThenBy(x => x.Id, Str |
| | 7 | 48 | | } |
| | | 49 | | |
| | | 50 | | private void RemoveOldestResource() |
| | | 51 | | { |
| | 4 | 52 | | var oldest = _resources.Values.OrderBy(x => x.LastSeen).ThenBy(x => x.Id, StringComparer.OrdinalIgnoreCase).Firs |
| | 1 | 53 | | if (oldest == null) |
| | 0 | 54 | | return; |
| | | 55 | | |
| | 1 | 56 | | _resources.Remove(oldest.Id); |
| | 1 | 57 | | _droppedCount++; |
| | 1 | 58 | | } |
| | | 59 | | } |