From ddd5a26b216e88aca2436d0104c8d8d6d043e7b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 May 2026 16:54:46 -0500 Subject: fix DI --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 42f43918..49a1c260 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -777,7 +777,7 @@ namespace slskd services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From f8926332c5ed0ea4153cf2eb79250bdf16cdd52c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Jun 2026 19:05:29 -0500 Subject: wip --- src/slskd/Program.cs | 221 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 217 insertions(+), 4 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b6710fdd..68665c69 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -63,6 +63,8 @@ namespace slskd using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi; + using Prometheus; + using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; using Serilog; @@ -97,6 +99,14 @@ namespace slskd using Utility.EnvironmentVariables; using IOFile = System.IO.File; + using Prometheus; + using Prometheus.DotNetRuntime; + using Prometheus.DotNetRuntime.Metrics.Producers; // ThreadPoolMetricsProducer.Options + using Prometheus.SystemMetrics; + using Prometheus.SystemMetrics.Collectors; // NetworkCollector, DiskCollectorConfig, ... + using System.Diagnostics.Metrics; // Instrument (Meter bridge filter) + using System.Diagnostics.Tracing; // EventLevel, EventKeywords (EventCounter bridge) + /// /// Bootstraps configuration and handles primitive command-line instructions. /// @@ -819,6 +829,187 @@ namespace slskd Log.Debug("SQLite threading mode set to {Mode} ({Number})", "SERIALIZED", SQLitePCL.raw.SQLITE_CONFIG_SERIALIZED); } + private static IServiceCollection ConfigureTelemetry(this IServiceCollection services) + { + // ... your existing CORS / DataProtection / JWT signing key / authentication / + // authorization registrations stay here (Program.cs:824 onward) ... + + // ============================================================================ + // PROMETHEUS-NET + .NET METRICS — MAXIMAL SURFACE (prune to taste) + // ---------------------------------------------------------------------------- + // prometheus-net 8.x auto-bridges BOTH .NET Meters (System.Diagnostics.Metrics) + // and EventCounters into the default registry unless told otherwise. That auto- + // bridge is where the QUIC noise (and kestrel/http/dns/EF/etc.) comes from — the + // .NET runtime owns those meters, we just choose whether to ingest them. + // These adapters start lazily on first scrape, so configuring them here is fine. + // ============================================================================ + + // ---- (A) Registry-wide settings: apply to EVERY exported series ------------ + Prometheus.Metrics.DefaultRegistry.SetStaticLabels(new Dictionary + { + // ["app"] = "slskd", + // ["instance"] = Environment.MachineName, + }); + + // Invoked on every scrape, before collection — refresh pull-style gauges here. + // Prometheus.Metrics.DefaultRegistry.AddBeforeCollectCallback(() => { /* sync */ }); + // Prometheus.Metrics.DefaultRegistry.AddBeforeCollectCallback(async ct => { /* async */ await Task.CompletedTask; }); + + // Exemplars (OpenMetrics trace-id linking). Off, or rate-limited, globally. + // Prometheus.Metrics.DefaultFactory.ExemplarBehavior = ExemplarBehavior.NoExemplars(); + // Prometheus.Metrics.DefaultFactory.ExemplarBehavior = new ExemplarBehavior + // { + // DefaultExemplarProvider = (metric, labels) => null, // ExemplarProvider delegate + // NewExemplarMinInterval = TimeSpan.FromSeconds(5), + // }; + + // ---- (B) NUCLEAR ALTERNATIVE to (C)/(D): kill whole families at the source - + // Each flag, when true, prevents that family from EVER being created/collected. + // Mutually exclusive with ConfigureMeterAdapter / ConfigureEventCounterAdapter + // below: if you SuppressMeters here, the meter adapter never starts and (C) is + // dead code. Pick ONE approach per bridge. + // Prometheus.Metrics.SuppressDefaultMetrics(new SuppressDefaultMetricOptions + // { + // SuppressMeters = true, // System.Diagnostics.Metrics bridge (QUIC, kestrel, http, dns, EF, ...) + // SuppressEventCounters = true, // EventCounters bridge (System.Runtime, sockets, tls, ...) + // SuppressProcessMetrics= false, // process_cpu_seconds_total, process_working_set_bytes, open FDs, ... + // SuppressDebugMetrics = false, // dotnet_collect_* (prometheus-net's own collection timing) + // }); + + // ---- (C) METER BRIDGE (System.Diagnostics.Metrics) — THE QUIC FILTER ------- + // Filter by Meter.Name. Below: drop the noisy framework meters, keep the rest. + // Known built-in .NET meters (names → exported as lower_snake_case): + // System.Net.Quic <-- your QUIC noise (.NET 9+) + // System.Net.Http / System.Net.NameResolution / System.Net.Security + // System.Runtime + // Microsoft.AspNetCore.Hosting + // Microsoft.AspNetCore.Server.Kestrel + // Microsoft.AspNetCore.Routing + // Microsoft.AspNetCore.Diagnostics + // Microsoft.AspNetCore.RateLimiting + // Microsoft.AspNetCore.HeaderParsing + // Microsoft.AspNetCore.Http.Connections (SignalR — you use 4 hubs) + // Microsoft.EntityFrameworkCore / Microsoft.Extensions.Diagnostics.HealthChecks + var suppressedMeterTokens = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "System.Net.Quic", // matches System.Net.Quic AND Private.InternalDiagnostics.System.Net.Quic.MsQuic + "Microsoft.EntityFrameworkCore", + }; + + + Prometheus.Metrics.ConfigureMeterAdapter(options => + { + // Return false to DROP an instrument before it ever becomes a Prometheus series. + options.InstrumentFilterPredicate = instrument => + !suppressedMeterTokens.Any(token => + instrument.Meter.Name.Contains(token, StringComparison.OrdinalIgnoreCase)); + + // Series with no fresh measurements are dropped after this window. + options.MetricsExpireAfter = TimeSpan.FromMinutes(5); + + // Override histogram bucketing per instrument (return null → adapter default). + // options.ResolveHistogramBuckets = instrument => MeterAdapterOptions.DefaultHistogramBuckets; + + // Route bridged meters to a non-default registry / factory if you want them + // isolated from your slskd_* series. + // options.Registry = Prometheus.Metrics.DefaultRegistry; + // options.MetricFactory = Prometheus.Metrics.DefaultFactory; + }); + + // ---- (D) EVENTCOUNTER BRIDGE (legacy EventSource counters) ------------------ + // QUIC also has a System.Net.Quic EventSource on some runtimes; filter by name. + // Compose with the library default so you only ADD exclusions. + Prometheus.Metrics.ConfigureEventCounterAdapter(options => + { + var suppressedEventSources = new[] { "Quic", "EntityFrameworkCore" }; + var allowDefault = EventCounterAdapter.DefaultEventSourceFilterPredicate; + + options.EventSourceFilterPredicate = name => + !suppressedEventSources.Any(s => name.Contains(s, StringComparison.OrdinalIgnoreCase)) + && (allowDefault?.Invoke(name) ?? true); + + // Per-source verbosity/keyword control (drives which counters a source emits). + options.EventSourceSettingsProvider = sourceName => new EventCounterAdapterEventSourceSettings + { + MinimumLevel = EventLevel.Informational, // Critical..Verbose + MatchKeywords = EventKeywords.All, + }; + + // Polling cadence for counters. + options.UpdateInterval = TimeSpan.FromSeconds(10); + + // options.Registry = Prometheus.Metrics.DefaultRegistry; + // options.MetricFactory = Prometheus.Metrics.DefaultFactory; + }); + + // ---- (E) .NET RUNTIME INTERNALS (GC / JIT / threadpool / contention / sockets / exceptions) + // Replaces the existing `DotNetRuntimeStatsBuilder.Default().StartCollecting()`. + // Default() == every collector at default levels. Customize() lets you prune. + // CaptureLevel: Counters < Errors < Informational < Verbose (higher = more detail, more cost). + // SampleEvery: OneEvent | TwoEvents | FiveEvents | TenEvents | TwentyEvents | FiftyEvents | HundredEvents + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Customize() + // .WithGcStats( + // atLevel: CaptureLevel.Verbose, + // histogramBuckets: new[] { 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0 }) // GC pause seconds + .WithGcStats() + .WithThreadPoolStats( + level: CaptureLevel.Informational, + options: new ThreadPoolMetricsProducer.Options + { + QueueLengthHistogramBuckets = new[] { 0.0, 10, 50, 100, 500, 1000 }, + }) + .WithContentionStats(level: CaptureLevel.Informational, sampleRate: SampleEvery.TenEvents) + .WithJitStats(captureLevel: CaptureLevel.Verbose, sampleRate: SampleEvery.TenEvents) + .WithExceptionStats(captureLevel: CaptureLevel.Errors) + .WithSocketStats() // dotnet_sockets_* (no level/sample knob) + // .RecycleCollectorsEvery(TimeSpan.FromMinutes(5)) // periodic listener reset (mem hygiene) + // .WithDebuggingMetrics(generateDebugMetrics: false) // emit prometheus-net's own diagnostics + .WithErrorHandler(ex => Log.Warning(ex, "DotNetRuntime stats collector error")) + .StartCollecting(); // -> assigned to DotNetRuntimeStats (Program.cs:276) + + // ---- (F) HOST / OS METRICS (cpu / memory / disk / network / load average) -- + // registerDefaultCollectors:true == all of the below auto-selected per-OS. + services.AddSystemMetrics(registerDefaultCollectors: true); + + // OR opt in individually (set registerDefaultCollectors:false above), e.g.: + // services.AddSystemMetricCollector(); // resolves Linux/Windows impl + // services.AddSystemMetricCollector(); + // services.AddSystemMetricCollector(); // Linux only + // services.AddSystemMetricCollector(); + // services.AddSystemMetricCollector(); + + // DiskCollector drive-type filter (e.g. exclude tmpfs/overlay noise in containers): + // services.Configure(cfg => + // cfg.DriveTypes = new HashSet { DriveType.Fixed }); + + // ---- (G) .NET-NATIVE control plane (informational) ------------------------- + // .NET's Microsoft.Extensions.Diagnostics.Metrics enable/disable RULES do NOT + // affect prometheus-net — its adapter uses its own MeterListener and ignores + // IMetricsBuilder rules. The effective filter for built-in meters is (C) above. + // services.AddMetrics(); // only needed if you also wire OpenTelemetry/other listeners + + return services; + + // ============================================================================ + // PIPELINE-SIDE OPTIONS (cannot live here — these take IApplicationBuilder / + // IEndpointRouteBuilder; put them in ConfigureWebApplication, NOT this method): + // + // app.UseHttpMetrics(o => // per-request http_request_* labels/cardinality + // { + // o.ReduceStatusCodeCardinality(); + // o.AddRouteParameter(...); o.AddCustomLabel("host", ctx => ctx.Request.Host.Host); + // o.RequestDuration.Histogram = ...; o.InProgress.Enabled = false; o.CaptureMetricsUrl = false; + // }); + // app.UseMetricServer(url: "/metrics"); // built-in middleware exporter + // endpoints.MapMetrics(pattern: "/metrics"); // endpoint-routing exporter + // services.AddMetricServer(o => { o.Port = 9100; o.Url = "/metrics"; o.TlsCertificate = ...; }); + // // standalone Kestrel exporter — + // // you ALREADY serve via the custom + // // MapGet at Program.cs:1133, so this + // // would double-publish. + // ============================================================================ + } + private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder @@ -828,10 +1019,32 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); - // note: don't dispose this (or let it be disposed) or some of the stats, like those related - // to the thread pool won't work - DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); - services.AddSystemMetrics(); + // Prometheus.Metrics.ConfigureMeterAdapter(options => + // { + // options.InstrumentFilterPredicate = instrument => + // { + // var meter = instrument.Meter.Name; + // if (meter.StartsWith("Private.InternalDiagnostics", StringComparison.OrdinalIgnoreCase)) { return false; } + // if (meter.StartsWith("Microsoft.EntityFrameworkCore", StringComparison.OrdinalIgnoreCase)) { return false; } + // if (meter.StartsWith("System.Runtime", StringComparison.OrdinalIgnoreCase)) { return false; } // duplicate of dotnet_* + // return true; + // }; + // }); + + // // note: don't dispose this (or let it be disposed) or some of the stats, like those related + // // to the thread pool won't work + // DotNetRuntimeStats = DotNetRuntimeStatsBuilder + // .Customize() + // .WithGcStats() + // .WithThreadPoolStats() + // .WithJitStats() + // .WithContentionStats() + // .WithExceptionStats() + // .StartCollecting(); + + // services.AddSystemMetrics(); + + services.ConfigureTelemetry(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); -- cgit v1.2.3 From 24f8a59f75fec1fe5a3d6c575eaeffc27d1bbbe0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Jun 2026 22:57:58 -0500 Subject: wip --- src/slskd/Program.cs | 193 +++++++++++++++++++++++++++++---------------------- 1 file changed, 110 insertions(+), 83 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 68665c69..51341d35 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -844,12 +844,12 @@ namespace slskd // These adapters start lazily on first scrape, so configuring them here is fine. // ============================================================================ - // ---- (A) Registry-wide settings: apply to EVERY exported series ------------ - Prometheus.Metrics.DefaultRegistry.SetStaticLabels(new Dictionary - { - // ["app"] = "slskd", - // ["instance"] = Environment.MachineName, - }); + // // ---- (A) Registry-wide settings: apply to EVERY exported series ------------ + // Prometheus.Metrics.DefaultRegistry.SetStaticLabels(new Dictionary + // { + // // ["app"] = "slskd", + // // ["instance"] = Environment.MachineName, + // }); // Invoked on every scrape, before collection — refresh pull-style gauges here. // Prometheus.Metrics.DefaultRegistry.AddBeforeCollectCallback(() => { /* sync */ }); @@ -870,42 +870,47 @@ namespace slskd // dead code. Pick ONE approach per bridge. // Prometheus.Metrics.SuppressDefaultMetrics(new SuppressDefaultMetricOptions // { - // SuppressMeters = true, // System.Diagnostics.Metrics bridge (QUIC, kestrel, http, dns, EF, ...) + // SuppressMeters = true, // System.Diagnostics.Metrics bridge (QUIC, kestrel, http, dns, EF, ...) // SuppressEventCounters = true, // EventCounters bridge (System.Runtime, sockets, tls, ...) - // SuppressProcessMetrics= false, // process_cpu_seconds_total, process_working_set_bytes, open FDs, ... - // SuppressDebugMetrics = false, // dotnet_collect_* (prometheus-net's own collection timing) + // SuppressProcessMetrics = true, // process_cpu_seconds_total, process_working_set_bytes, open FDs, ... + // SuppressDebugMetrics = false, // dotnet_collect_* (prometheus-net's own collection timing) // }); - // ---- (C) METER BRIDGE (System.Diagnostics.Metrics) — THE QUIC FILTER ------- - // Filter by Meter.Name. Below: drop the noisy framework meters, keep the rest. - // Known built-in .NET meters (names → exported as lower_snake_case): - // System.Net.Quic <-- your QUIC noise (.NET 9+) - // System.Net.Http / System.Net.NameResolution / System.Net.Security - // System.Runtime - // Microsoft.AspNetCore.Hosting - // Microsoft.AspNetCore.Server.Kestrel - // Microsoft.AspNetCore.Routing - // Microsoft.AspNetCore.Diagnostics - // Microsoft.AspNetCore.RateLimiting - // Microsoft.AspNetCore.HeaderParsing - // Microsoft.AspNetCore.Http.Connections (SignalR — you use 4 hubs) - // Microsoft.EntityFrameworkCore / Microsoft.Extensions.Diagnostics.HealthChecks - var suppressedMeterTokens = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "System.Net.Quic", // matches System.Net.Quic AND Private.InternalDiagnostics.System.Net.Quic.MsQuic - "Microsoft.EntityFrameworkCore", - }; - + // ---- (C) METER BRIDGE (System.Diagnostics.Metrics) — THE QUIC FILTER ------- Prometheus.Metrics.ConfigureMeterAdapter(options => { + // Filter by Meter.Name. Below: drop the noisy framework meters, keep the rest. + // Known built-in .NET meters (names → exported as lower_snake_case): + // System.Net.Quic <-- your QUIC noise (.NET 9+) + // System.Net.Http / System.Net.NameResolution / System.Net.Security + // System.Runtime + // Microsoft.AspNetCore.Hosting + // Microsoft.AspNetCore.Server.Kestrel + // Microsoft.AspNetCore.Routing + // Microsoft.AspNetCore.Diagnostics + // Microsoft.AspNetCore.RateLimiting + // Microsoft.AspNetCore.HeaderParsing + // Microsoft.AspNetCore.Http.Connections (SignalR — you use 4 hubs) + // Microsoft.EntityFrameworkCore / Microsoft.Extensions.Diagnostics.HealthChecks + var suppressedMeterTokens = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "Private.InternalDiagnostics", // matches System.Net.Quic AND Private.InternalDiagnostics.System.Net.Quic.MsQuic + "Microsoft.EntityFrameworkCore", + "Microsoft.AspNetCore.Authentication", + }; + // Return false to DROP an instrument before it ever becomes a Prometheus series. - options.InstrumentFilterPredicate = instrument => - !suppressedMeterTokens.Any(token => - instrument.Meter.Name.Contains(token, StringComparison.OrdinalIgnoreCase)); + // options.InstrumentFilterPredicate = instrument => + // { + // Log.Warning("{Instrument} {Desc}", instrument.Meter.Name, instrument.Description); + + // return !suppressedMeterTokens.Any(token => + // instrument.Meter.Name.Contains(token, StringComparison.OrdinalIgnoreCase)); + // }; // Series with no fresh measurements are dropped after this window. - options.MetricsExpireAfter = TimeSpan.FromMinutes(5); + options.MetricsExpireAfter = TimeSpan.FromMinutes(5); // <-- the default // Override histogram bucketing per instrument (return null → adapter default). // options.ResolveHistogramBuckets = instrument => MeterAdapterOptions.DefaultHistogramBuckets; @@ -921,19 +926,24 @@ namespace slskd // Compose with the library default so you only ADD exclusions. Prometheus.Metrics.ConfigureEventCounterAdapter(options => { - var suppressedEventSources = new[] { "Quic", "EntityFrameworkCore" }; + // var suppressedEventSources = new[] { "Quic", "EntityFrameworkCore" }; var allowDefault = EventCounterAdapter.DefaultEventSourceFilterPredicate; + string[] suppressedEventSources = []; - options.EventSourceFilterPredicate = name => - !suppressedEventSources.Any(s => name.Contains(s, StringComparison.OrdinalIgnoreCase)) - && (allowDefault?.Invoke(name) ?? true); + // options.EventSourceFilterPredicate = name => + // { + // Log.Warning("{Instrument}", name); - // Per-source verbosity/keyword control (drives which counters a source emits). - options.EventSourceSettingsProvider = sourceName => new EventCounterAdapterEventSourceSettings - { - MinimumLevel = EventLevel.Informational, // Critical..Verbose - MatchKeywords = EventKeywords.All, - }; + // return !suppressedEventSources.Any(s => name.Contains(s, StringComparison.OrdinalIgnoreCase)) + // && (allowDefault?.Invoke(name) ?? true); + // }; + + // // Per-source verbosity/keyword control (drives which counters a source emits). + // options.EventSourceSettingsProvider = sourceName => new EventCounterAdapterEventSourceSettings + // { + // MinimumLevel = EventLevel.Informational, // Critical..Verbose + // MatchKeywords = EventKeywords.All, + // }; // Polling cadence for counters. options.UpdateInterval = TimeSpan.FromSeconds(10); @@ -947,29 +957,58 @@ namespace slskd // Default() == every collector at default levels. Customize() lets you prune. // CaptureLevel: Counters < Errors < Informational < Verbose (higher = more detail, more cost). // SampleEvery: OneEvent | TwoEvents | FiveEvents | TenEvents | TwentyEvents | FiftyEvents | HundredEvents - DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Customize() - // .WithGcStats( - // atLevel: CaptureLevel.Verbose, - // histogramBuckets: new[] { 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0 }) // GC pause seconds - .WithGcStats() - .WithThreadPoolStats( - level: CaptureLevel.Informational, - options: new ThreadPoolMetricsProducer.Options - { - QueueLengthHistogramBuckets = new[] { 0.0, 10, 50, 100, 500, 1000 }, - }) - .WithContentionStats(level: CaptureLevel.Informational, sampleRate: SampleEvery.TenEvents) - .WithJitStats(captureLevel: CaptureLevel.Verbose, sampleRate: SampleEvery.TenEvents) - .WithExceptionStats(captureLevel: CaptureLevel.Errors) - .WithSocketStats() // dotnet_sockets_* (no level/sample knob) - // .RecycleCollectorsEvery(TimeSpan.FromMinutes(5)) // periodic listener reset (mem hygiene) - // .WithDebuggingMetrics(generateDebugMetrics: false) // emit prometheus-net's own diagnostics - .WithErrorHandler(ex => Log.Warning(ex, "DotNetRuntime stats collector error")) - .StartCollecting(); // -> assigned to DotNetRuntimeStats (Program.cs:276) + /* + dotnet_build_info{version="4.4.1.0",target_framework=".NETCoreApp,Version=v10.0",runtime_version=".NET 10.0.8",os_version="Debian GNU/Linux 13 (trixie)",process_architecture="X64",gc_mode="Server"} 1 +dotnet_collection_count_total{generation="0"} 5 +dotnet_collection_count_total{generation="1"} 1 +dotnet_collection_count_total{generation="2"} 0 +dotnet_contention_total 13 +dotnet_gc_allocated_bytes_total 31261944 +dotnet_gc_heap_size_bytes{gc_generation="0"} 0 +dotnet_gc_heap_size_bytes{gc_generation="1"} 6445960 +dotnet_gc_heap_size_bytes{gc_generation="2"} 367280 +dotnet_gc_heap_size_bytes{gc_generation="loh"} 98384 +dotnet_gc_memory_total_available_bytes 33534750720 +dotnet_gc_pause_ratio 0.02 +dotnet_sockets_bytes_received_total 316 +dotnet_sockets_bytes_sent_total 228 +dotnet_sockets_connections_established_incoming_total 0 +dotnet_sockets_connections_established_outgoing_total 2 +dotnet_threadpool_num_threads 9 +dotnet_threadpool_queue_length_bucket{le="+Inf"} 4 +dotnet_threadpool_queue_length_bucket{le="0"} 4 +dotnet_threadpool_queue_length_bucket{le="1"} 4 +dotnet_threadpool_queue_length_bucket{le="10"} 4 +dotnet_threadpool_queue_length_bucket{le="100"} 4 +dotnet_threadpool_queue_length_bucket{le="1000"} 4 +dotnet_threadpool_queue_length_count 4 +dotnet_threadpool_queue_length_sum 0 +dotnet_threadpool_throughput_total 376 +dotnet_threadpool_timer_count 27 + */ + var runtime = false; + + if (runtime) + { + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Customize() // https://github.com/djluck/prometheus-net.DotNetRuntime + // .WithGcStats( + // atLevel: CaptureLevel.Verbose, + // histogramBuckets: new[] { 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0 }) // GC pause seconds + .WithGcStats() + .WithThreadPoolStats() + .WithContentionStats() + // .WithJitStats() + // .WithExceptionStats() + .WithSocketStats() // dotnet_sockets_* (no level/sample knob) + // .RecycleCollectorsEvery(TimeSpan.FromMinutes(5)) // periodic listener reset (mem hygiene) + // .WithDebuggingMetrics(generateDebugMetrics: false) // emit prometheus-net's own diagnostics + .WithErrorHandler(ex => Log.Warning(ex, "DotNetRuntime stats collector error")) + .StartCollecting(); // -> assigned to DotNetRuntimeStats (Program.cs:276) + } // ---- (F) HOST / OS METRICS (cpu / memory / disk / network / load average) -- // registerDefaultCollectors:true == all of the below auto-selected per-OS. - services.AddSystemMetrics(registerDefaultCollectors: true); + // services.AddSystemMetrics(registerDefaultCollectors: true); // OR opt in individually (set registerDefaultCollectors:false above), e.g.: // services.AddSystemMetricCollector(); // resolves Linux/Windows impl @@ -986,28 +1025,16 @@ namespace slskd // .NET's Microsoft.Extensions.Diagnostics.Metrics enable/disable RULES do NOT // affect prometheus-net — its adapter uses its own MeterListener and ignores // IMetricsBuilder rules. The effective filter for built-in meters is (C) above. - // services.AddMetrics(); // only needed if you also wire OpenTelemetry/other listeners + // services.AddMetrics(); // only needed if you also wire OpenTelemetry/other listeners - return services; + var system = true; - // ============================================================================ - // PIPELINE-SIDE OPTIONS (cannot live here — these take IApplicationBuilder / - // IEndpointRouteBuilder; put them in ConfigureWebApplication, NOT this method): - // - // app.UseHttpMetrics(o => // per-request http_request_* labels/cardinality - // { - // o.ReduceStatusCodeCardinality(); - // o.AddRouteParameter(...); o.AddCustomLabel("host", ctx => ctx.Request.Host.Host); - // o.RequestDuration.Histogram = ...; o.InProgress.Enabled = false; o.CaptureMetricsUrl = false; - // }); - // app.UseMetricServer(url: "/metrics"); // built-in middleware exporter - // endpoints.MapMetrics(pattern: "/metrics"); // endpoint-routing exporter - // services.AddMetricServer(o => { o.Port = 9100; o.Url = "/metrics"; o.TlsCertificate = ...; }); - // // standalone Kestrel exporter — - // // you ALREADY serve via the custom - // // MapGet at Program.cs:1133, so this - // // would double-publish. - // ============================================================================ + if (system) + { + services.AddSystemMetrics(); // https://github.com/Daniel15/prometheus-net.SystemMetrics + } + + return services; } private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) -- cgit v1.2.3 From 2112c69139df93bea9b005196627be0125bb737b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Jun 2026 14:25:39 -0500 Subject: document telemetry configuration --- src/slskd/Program.cs | 400 ++++++++++++++++++++------------------------------- 1 file changed, 157 insertions(+), 243 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 51341d35..14050674 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -46,6 +46,7 @@ namespace slskd using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json.Serialization; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning.ApiExplorer; @@ -64,12 +65,11 @@ namespace slskd using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi; using Prometheus; - using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; + using Prometheus.SystemMetrics.Collectors; using Serilog; using Serilog.Events; - using Serilog.Formatting.Display; using Serilog.Sinks.Grafana.Loki; using Serilog.Sinks.SystemConsole.Themes; using slskd.Authentication; @@ -99,14 +99,6 @@ namespace slskd using Utility.EnvironmentVariables; using IOFile = System.IO.File; - using Prometheus; - using Prometheus.DotNetRuntime; - using Prometheus.DotNetRuntime.Metrics.Producers; // ThreadPoolMetricsProducer.Options - using Prometheus.SystemMetrics; - using Prometheus.SystemMetrics.Collectors; // NetworkCollector, DiskCollectorConfig, ... - using System.Diagnostics.Metrics; // Instrument (Meter bridge filter) - using System.Diagnostics.Tracing; // EventLevel, EventKeywords (EventCounter bridge) - /// /// Bootstraps configuration and handles primitive command-line instructions. /// @@ -829,214 +821,6 @@ namespace slskd Log.Debug("SQLite threading mode set to {Mode} ({Number})", "SERIALIZED", SQLitePCL.raw.SQLITE_CONFIG_SERIALIZED); } - private static IServiceCollection ConfigureTelemetry(this IServiceCollection services) - { - // ... your existing CORS / DataProtection / JWT signing key / authentication / - // authorization registrations stay here (Program.cs:824 onward) ... - - // ============================================================================ - // PROMETHEUS-NET + .NET METRICS — MAXIMAL SURFACE (prune to taste) - // ---------------------------------------------------------------------------- - // prometheus-net 8.x auto-bridges BOTH .NET Meters (System.Diagnostics.Metrics) - // and EventCounters into the default registry unless told otherwise. That auto- - // bridge is where the QUIC noise (and kestrel/http/dns/EF/etc.) comes from — the - // .NET runtime owns those meters, we just choose whether to ingest them. - // These adapters start lazily on first scrape, so configuring them here is fine. - // ============================================================================ - - // // ---- (A) Registry-wide settings: apply to EVERY exported series ------------ - // Prometheus.Metrics.DefaultRegistry.SetStaticLabels(new Dictionary - // { - // // ["app"] = "slskd", - // // ["instance"] = Environment.MachineName, - // }); - - // Invoked on every scrape, before collection — refresh pull-style gauges here. - // Prometheus.Metrics.DefaultRegistry.AddBeforeCollectCallback(() => { /* sync */ }); - // Prometheus.Metrics.DefaultRegistry.AddBeforeCollectCallback(async ct => { /* async */ await Task.CompletedTask; }); - - // Exemplars (OpenMetrics trace-id linking). Off, or rate-limited, globally. - // Prometheus.Metrics.DefaultFactory.ExemplarBehavior = ExemplarBehavior.NoExemplars(); - // Prometheus.Metrics.DefaultFactory.ExemplarBehavior = new ExemplarBehavior - // { - // DefaultExemplarProvider = (metric, labels) => null, // ExemplarProvider delegate - // NewExemplarMinInterval = TimeSpan.FromSeconds(5), - // }; - - // ---- (B) NUCLEAR ALTERNATIVE to (C)/(D): kill whole families at the source - - // Each flag, when true, prevents that family from EVER being created/collected. - // Mutually exclusive with ConfigureMeterAdapter / ConfigureEventCounterAdapter - // below: if you SuppressMeters here, the meter adapter never starts and (C) is - // dead code. Pick ONE approach per bridge. - // Prometheus.Metrics.SuppressDefaultMetrics(new SuppressDefaultMetricOptions - // { - // SuppressMeters = true, // System.Diagnostics.Metrics bridge (QUIC, kestrel, http, dns, EF, ...) - // SuppressEventCounters = true, // EventCounters bridge (System.Runtime, sockets, tls, ...) - // SuppressProcessMetrics = true, // process_cpu_seconds_total, process_working_set_bytes, open FDs, ... - // SuppressDebugMetrics = false, // dotnet_collect_* (prometheus-net's own collection timing) - // }); - - - // ---- (C) METER BRIDGE (System.Diagnostics.Metrics) — THE QUIC FILTER ------- - Prometheus.Metrics.ConfigureMeterAdapter(options => - { - // Filter by Meter.Name. Below: drop the noisy framework meters, keep the rest. - // Known built-in .NET meters (names → exported as lower_snake_case): - // System.Net.Quic <-- your QUIC noise (.NET 9+) - // System.Net.Http / System.Net.NameResolution / System.Net.Security - // System.Runtime - // Microsoft.AspNetCore.Hosting - // Microsoft.AspNetCore.Server.Kestrel - // Microsoft.AspNetCore.Routing - // Microsoft.AspNetCore.Diagnostics - // Microsoft.AspNetCore.RateLimiting - // Microsoft.AspNetCore.HeaderParsing - // Microsoft.AspNetCore.Http.Connections (SignalR — you use 4 hubs) - // Microsoft.EntityFrameworkCore / Microsoft.Extensions.Diagnostics.HealthChecks - var suppressedMeterTokens = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "Private.InternalDiagnostics", // matches System.Net.Quic AND Private.InternalDiagnostics.System.Net.Quic.MsQuic - "Microsoft.EntityFrameworkCore", - "Microsoft.AspNetCore.Authentication", - }; - - // Return false to DROP an instrument before it ever becomes a Prometheus series. - // options.InstrumentFilterPredicate = instrument => - // { - // Log.Warning("{Instrument} {Desc}", instrument.Meter.Name, instrument.Description); - - // return !suppressedMeterTokens.Any(token => - // instrument.Meter.Name.Contains(token, StringComparison.OrdinalIgnoreCase)); - // }; - - // Series with no fresh measurements are dropped after this window. - options.MetricsExpireAfter = TimeSpan.FromMinutes(5); // <-- the default - - // Override histogram bucketing per instrument (return null → adapter default). - // options.ResolveHistogramBuckets = instrument => MeterAdapterOptions.DefaultHistogramBuckets; - - // Route bridged meters to a non-default registry / factory if you want them - // isolated from your slskd_* series. - // options.Registry = Prometheus.Metrics.DefaultRegistry; - // options.MetricFactory = Prometheus.Metrics.DefaultFactory; - }); - - // ---- (D) EVENTCOUNTER BRIDGE (legacy EventSource counters) ------------------ - // QUIC also has a System.Net.Quic EventSource on some runtimes; filter by name. - // Compose with the library default so you only ADD exclusions. - Prometheus.Metrics.ConfigureEventCounterAdapter(options => - { - // var suppressedEventSources = new[] { "Quic", "EntityFrameworkCore" }; - var allowDefault = EventCounterAdapter.DefaultEventSourceFilterPredicate; - string[] suppressedEventSources = []; - - // options.EventSourceFilterPredicate = name => - // { - // Log.Warning("{Instrument}", name); - - // return !suppressedEventSources.Any(s => name.Contains(s, StringComparison.OrdinalIgnoreCase)) - // && (allowDefault?.Invoke(name) ?? true); - // }; - - // // Per-source verbosity/keyword control (drives which counters a source emits). - // options.EventSourceSettingsProvider = sourceName => new EventCounterAdapterEventSourceSettings - // { - // MinimumLevel = EventLevel.Informational, // Critical..Verbose - // MatchKeywords = EventKeywords.All, - // }; - - // Polling cadence for counters. - options.UpdateInterval = TimeSpan.FromSeconds(10); - - // options.Registry = Prometheus.Metrics.DefaultRegistry; - // options.MetricFactory = Prometheus.Metrics.DefaultFactory; - }); - - // ---- (E) .NET RUNTIME INTERNALS (GC / JIT / threadpool / contention / sockets / exceptions) - // Replaces the existing `DotNetRuntimeStatsBuilder.Default().StartCollecting()`. - // Default() == every collector at default levels. Customize() lets you prune. - // CaptureLevel: Counters < Errors < Informational < Verbose (higher = more detail, more cost). - // SampleEvery: OneEvent | TwoEvents | FiveEvents | TenEvents | TwentyEvents | FiftyEvents | HundredEvents - /* - dotnet_build_info{version="4.4.1.0",target_framework=".NETCoreApp,Version=v10.0",runtime_version=".NET 10.0.8",os_version="Debian GNU/Linux 13 (trixie)",process_architecture="X64",gc_mode="Server"} 1 -dotnet_collection_count_total{generation="0"} 5 -dotnet_collection_count_total{generation="1"} 1 -dotnet_collection_count_total{generation="2"} 0 -dotnet_contention_total 13 -dotnet_gc_allocated_bytes_total 31261944 -dotnet_gc_heap_size_bytes{gc_generation="0"} 0 -dotnet_gc_heap_size_bytes{gc_generation="1"} 6445960 -dotnet_gc_heap_size_bytes{gc_generation="2"} 367280 -dotnet_gc_heap_size_bytes{gc_generation="loh"} 98384 -dotnet_gc_memory_total_available_bytes 33534750720 -dotnet_gc_pause_ratio 0.02 -dotnet_sockets_bytes_received_total 316 -dotnet_sockets_bytes_sent_total 228 -dotnet_sockets_connections_established_incoming_total 0 -dotnet_sockets_connections_established_outgoing_total 2 -dotnet_threadpool_num_threads 9 -dotnet_threadpool_queue_length_bucket{le="+Inf"} 4 -dotnet_threadpool_queue_length_bucket{le="0"} 4 -dotnet_threadpool_queue_length_bucket{le="1"} 4 -dotnet_threadpool_queue_length_bucket{le="10"} 4 -dotnet_threadpool_queue_length_bucket{le="100"} 4 -dotnet_threadpool_queue_length_bucket{le="1000"} 4 -dotnet_threadpool_queue_length_count 4 -dotnet_threadpool_queue_length_sum 0 -dotnet_threadpool_throughput_total 376 -dotnet_threadpool_timer_count 27 - */ - var runtime = false; - - if (runtime) - { - DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Customize() // https://github.com/djluck/prometheus-net.DotNetRuntime - // .WithGcStats( - // atLevel: CaptureLevel.Verbose, - // histogramBuckets: new[] { 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0 }) // GC pause seconds - .WithGcStats() - .WithThreadPoolStats() - .WithContentionStats() - // .WithJitStats() - // .WithExceptionStats() - .WithSocketStats() // dotnet_sockets_* (no level/sample knob) - // .RecycleCollectorsEvery(TimeSpan.FromMinutes(5)) // periodic listener reset (mem hygiene) - // .WithDebuggingMetrics(generateDebugMetrics: false) // emit prometheus-net's own diagnostics - .WithErrorHandler(ex => Log.Warning(ex, "DotNetRuntime stats collector error")) - .StartCollecting(); // -> assigned to DotNetRuntimeStats (Program.cs:276) - } - - // ---- (F) HOST / OS METRICS (cpu / memory / disk / network / load average) -- - // registerDefaultCollectors:true == all of the below auto-selected per-OS. - // services.AddSystemMetrics(registerDefaultCollectors: true); - - // OR opt in individually (set registerDefaultCollectors:false above), e.g.: - // services.AddSystemMetricCollector(); // resolves Linux/Windows impl - // services.AddSystemMetricCollector(); - // services.AddSystemMetricCollector(); // Linux only - // services.AddSystemMetricCollector(); - // services.AddSystemMetricCollector(); - - // DiskCollector drive-type filter (e.g. exclude tmpfs/overlay noise in containers): - // services.Configure(cfg => - // cfg.DriveTypes = new HashSet { DriveType.Fixed }); - - // ---- (G) .NET-NATIVE control plane (informational) ------------------------- - // .NET's Microsoft.Extensions.Diagnostics.Metrics enable/disable RULES do NOT - // affect prometheus-net — its adapter uses its own MeterListener and ignores - // IMetricsBuilder rules. The effective filter for built-in meters is (C) above. - // services.AddMetrics(); // only needed if you also wire OpenTelemetry/other listeners - - var system = true; - - if (system) - { - services.AddSystemMetrics(); // https://github.com/Daniel15/prometheus-net.SystemMetrics - } - - return services; - } - private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder @@ -1046,31 +830,6 @@ dotnet_threadpool_timer_count 27 .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); - // Prometheus.Metrics.ConfigureMeterAdapter(options => - // { - // options.InstrumentFilterPredicate = instrument => - // { - // var meter = instrument.Meter.Name; - // if (meter.StartsWith("Private.InternalDiagnostics", StringComparison.OrdinalIgnoreCase)) { return false; } - // if (meter.StartsWith("Microsoft.EntityFrameworkCore", StringComparison.OrdinalIgnoreCase)) { return false; } - // if (meter.StartsWith("System.Runtime", StringComparison.OrdinalIgnoreCase)) { return false; } // duplicate of dotnet_* - // return true; - // }; - // }); - - // // note: don't dispose this (or let it be disposed) or some of the stats, like those related - // // to the thread pool won't work - // DotNetRuntimeStats = DotNetRuntimeStatsBuilder - // .Customize() - // .WithGcStats() - // .WithThreadPoolStats() - // .WithJitStats() - // .WithContentionStats() - // .WithExceptionStats() - // .StartCollecting(); - - // services.AddSystemMetrics(); - services.ConfigureTelemetry(); services.AddDataProtection() @@ -1541,6 +1300,161 @@ dotnet_threadpool_timer_count 27 }; } + private static IServiceCollection ConfigureTelemetry(this IServiceCollection services) + { + Prometheus.Metrics.SuppressDefaultMetrics(new SuppressDefaultMetricOptions + { + SuppressDebugMetrics = true, // prometheus_net_metric_families/instances/timeseries + SuppressProcessMetrics = false, // dotnet_collection_count_total, dotnet_total_memory_bytes, process_* + SuppressMeters = true, // system_ + SuppressEventCounters = true, // more system_ + }); + + Regex[] sources = + [ + new Regex("^System.*", RegexOptions.Compiled), + new Regex("^Microsoft-Windows-DotNETRuntime", RegexOptions.Compiled), + new Regex("^Microsoft-Diagnostics-DiagnosticSource", RegexOptions.Compiled), + new Regex("^Private.InternalDiagnostics.System.Net.Sockets$", RegexOptions.Compiled), + ]; + + /* + Meter bridge - uses new .NET Meters + + included: + + System.Runtime + + excluded: + + Microsoft.AspNetCore.MemoryPool + Microsoft.AspNetCore.Server.Kestrel + Microsoft.AspNetCore.Http.Connections + Microsoft.AspNetCore.Hosting + Microsoft.AspNetCore.Routing + Microsoft.AspNetCore.Diagnostics + Microsoft.AspNetCore.Authentication + Microsoft.EntityFrameworkCore + Private.InternalDiagnostics.System.Net.Quic.MsQuic + */ + Prometheus.Metrics.ConfigureMeterAdapter(options => + { + options.InstrumentFilterPredicate = instrument => + { + return sources.Any(s => + { + Log.Warning("Testing: {Thing}", instrument.Meter.Name); + + if (s.IsMatch(instrument?.Meter?.Name)) + { + Log.Warning("Allowed {Thing}", instrument.Meter.Name); + return true; + } + + return false; + }); + }; + }); + + /* + EventCounter bridge - uses 'legacy' EventSource counters + + included: + + System.Runtime + System.Data.DataCommonEventSource + System.Transactions.TransactionsEventSource + System.Diagnostics.Metrics + System.Buffers.ArrayPoolEventSource + System.Diagnostics.Eventing.FrameworkEventSource + System.Threading.Tasks.TplEventSource + System.Collections.Concurrent.ConcurrentCollectionsEventSource + System.Net.Sockets + Private.InternalDiagnostics.System.Net.Sockets + + excluded: + + Microsoft.AspNetCore.Hosting + Microsoft-AspNetCore-Server-Kestrel + Microsoft-Windows-DotNETRuntime + Microsoft-Diagnostics-DiagnosticSource + Microsoft-Extensions-Logging + Microsoft-Extensions-DependencyInjection + Microsoft.EntityFrameworkCore + Private.InternalDiagnostics.System.Net.Quic + */ + Prometheus.Metrics.ConfigureEventCounterAdapter(options => + { + options.EventSourceFilterPredicate = name => + { + return sources.Any(s => + { + Log.Warning("Testing: {Thing}", name); + if (s.IsMatch(name)) + { + Log.Warning("Allowed {Thing}", name); + return true; + } + + return false; + }); + }; + }); + + /* + https://github.com/djluck/prometheus-net.DotNetRuntime + + this package overlaps nearly completely with the built in stats, but it offers a slightly different + calculation for memory, and a thread pool throughput stat that's fairly important to me. + + this has been enabled for many years and it should be included because it may break people's stuff. + i may make it optional in the future. it honestly might make more sense to disable the meters above + and keep this. + + included: + + dotnet_build_info + dotnet_collection + dotnet_contention + dotnet_exceptions + dotnet_jit + dotnet_gc + dotnet_sockets + dotnet_threadpool + */ + DotNetRuntimeStats = DotNetRuntimeStatsBuilder + .Customize() + .WithGcStats() + .WithThreadPoolStats() + .WithContentionStats() + .WithJitStats() + .WithExceptionStats() + .WithSocketStats() + .StartCollecting(); + + /* + https://github.com/Daniel15/prometheus-net.SystemMetrics + + this package adds information about the host machine slskd is running on, including CPU, RAM, disks, + and network interfaces. + + included: + + node_filesystem_avail/size + node_network_receive_ + node_network_transmit_ + node_cpu_seconds_total (detailed user/syste/irq/idle for ALL cores) + node_memory_ + */ + services.AddSystemMetrics(registerDefaultCollectors: true); + + // exclude tmpfs/overlay noise in containers + services.Configure(cfg => + cfg.DriveTypes = new HashSet { DriveType.Fixed }); + + return services; + } + private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) { configurationFile = Path.GetFullPath(configurationFile); -- cgit v1.2.3 From 433541879e45d2978904c924af132b169336b179 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Jun 2026 19:23:47 -0500 Subject: plumb metrics hub --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 14050674..23351c75 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1113,6 +1113,7 @@ namespace slskd endpoints.MapHub("/hub/logs"); endpoints.MapHub("/hub/search"); endpoints.MapHub("/hub/relay"); + endpoints.MapHub("/hub/metrics"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); -- cgit v1.2.3 From ee1fac35e7c5679e2a389ff524fdddf38bb6f795 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jun 2026 22:02:23 -0500 Subject: force telemetryservice instantiation --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 23351c75..0d94d4ce 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -629,6 +629,7 @@ namespace slskd _ = app.Services.GetService(); _ = app.Services.GetService(); _ = app.Services.GetService(); + _ = app.Services.GetService(); app.ConfigureAspDotNetPipeline(); -- cgit v1.2.3 From 0d86190f79f8f087abdbd923c552104b2a939c7d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 18 Jun 2026 21:29:45 -0500 Subject: add metrics service, refactor MetricsHub --- src/slskd/Program.cs | 1 + src/slskd/Telemetry/API/MetricsHub.cs | 68 +++++-------------------- src/slskd/Telemetry/MetricsService.cs | 89 +++++++++++++++++++++++++++++++++ src/slskd/Telemetry/TelemetryService.cs | 12 +++-- 4 files changed, 111 insertions(+), 59 deletions(-) create mode 100644 src/slskd/Telemetry/MetricsService.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0d94d4ce..f7434fb1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -760,6 +760,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index d8692755..9161de85 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -30,75 +30,31 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // +namespace slskd.Telemetry; + using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using Serilog; -namespace slskd.Telemetry; - -public static class MetricsHubMethods +public interface IMetricsHub { - public static readonly string Transfers = nameof(Transfers); + Task Update(object metrics); } -public static class MetricsHubExtensions +[Authorize] +public class MetricsHub : Hub { - public static Task BroadcastTransferMetrics(this IHubContext hub) + public MetricsHub(MetricsService metricsService) { - return hub.Clients.All.SendAsync(MetricsHubMethods.Transfers, MetricsHub.GetMetrics()); - } -} - -public class MetricsHub : Hub -{ - public MetricsHub() - { - } - - public override async Task OnConnectedAsync() - { - await Clients.Caller.SendAsync(MetricsHubMethods.Transfers, GetMetrics()); + Metrics = metricsService; } + private MetricsService Metrics { get; } private static ILogger Log { get; } = Serilog.Log.ForContext(); - public static object GetMetrics() + public override async Task OnConnectedAsync() { - var metrics = new - { - Downloads = new - { - InProgress = new - { - Files = Metrics.Transfers.Downloads.InProgress.Files.Value, - AverageSpeed = Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Value, - TotalSpeed = Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Value, - }, - Queued = new - { - Files = Metrics.Transfers.Downloads.Queued.Files.Value, - Users = Metrics.Transfers.Downloads.Queued.Users.Value, - Bytes = Metrics.Transfers.Downloads.Queued.Bytes.Value, - }, - }, - Uploads = new - { - InProgress = new - { - Files = Metrics.Transfers.Uploads.InProgress.Files.Value, - AverageSpeed = Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Value, - TotalSpeed = Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Value, - }, - Queued = new - { - Files = Metrics.Transfers.Uploads.Queued.Files.Value, - Users = Metrics.Transfers.Uploads.Queued.Users.Value, - Bytes = Metrics.Transfers.Uploads.Queued.Bytes.Value, - }, - }, - }; - - Log.Warning("{Metrics}", metrics); - return metrics; + await Clients.Caller.Update(Metrics.Current()); } } \ No newline at end of file diff --git a/src/slskd/Telemetry/MetricsService.cs b/src/slskd/Telemetry/MetricsService.cs new file mode 100644 index 00000000..64610fa5 --- /dev/null +++ b/src/slskd/Telemetry/MetricsService.cs @@ -0,0 +1,89 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Telemetry; + +public class MetricsService +{ + public object Current() + { + var metrics = new + { + Downloads = new + { + InProgress = new + { + Files = Metrics.Transfers.Downloads.InProgress.Files.Value, + Users = Metrics.Transfers.Downloads.InProgress.Users.Value, + AverageSpeed = Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Value, + TotalSpeed = Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Value, + }, + Queued = new + { + Files = Metrics.Transfers.Downloads.Queued.Files.Value, + Users = Metrics.Transfers.Downloads.Queued.Users.Value, + Bytes = Metrics.Transfers.Downloads.Queued.Bytes.Value, + }, + Completed = new + { + Succeeded = Metrics.Transfers.Downloads.Completed.Succeeded.Value, + Failed = Metrics.Transfers.Downloads.Completed.Failed.Value, + Bytes = Metrics.Transfers.Downloads.Completed.Bytes.Value, + }, + }, + Uploads = new + { + InProgress = new + { + Files = Metrics.Transfers.Uploads.InProgress.Files.Value, + Users = Metrics.Transfers.Uploads.InProgress.Users.Value, + AverageSpeed = Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Value, + TotalSpeed = Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Value, + }, + Queued = new + { + Files = Metrics.Transfers.Uploads.Queued.Files.Value, + Users = Metrics.Transfers.Uploads.Queued.Users.Value, + Bytes = Metrics.Transfers.Uploads.Queued.Bytes.Value, + }, + Completed = new + { + Succeeded = Metrics.Transfers.Uploads.Completed.Succeeded.Value, + Failed = Metrics.Transfers.Uploads.Completed.Failed.Value, + Bytes = Metrics.Transfers.Uploads.Completed.Bytes.Value, + }, + }, + }; + + return metrics; + } +} \ No newline at end of file diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs index 81ee6380..5085d6ed 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -36,20 +36,26 @@ namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, ReportsService reportsService, IHubContext metricsHub) + public TelemetryService( + PrometheusService prometheusService, + ReportsService reportsService, + MetricsService metricsService, + IHubContext metricsHub) { Prometheus = prometheusService; Reports = reportsService; + Metrics = metricsService; MetricsHub = metricsHub; Clock.EverySecond += (_, _) => { - MetricsHub.BroadcastTransferMetrics(); + MetricsHub.Clients.All.Update(Metrics.Current()); }; } public PrometheusService Prometheus { get; } public ReportsService Reports { get; } - private IHubContext MetricsHub { get; } + public MetricsService Metrics { get; } + private IHubContext MetricsHub { get; } } \ No newline at end of file -- cgit v1.2.3 From 198be40b601e3eab548134884391859ece62be0c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 19 Jun 2026 12:46:46 -0500 Subject: fix namespace issue in test --- src/slskd/Program.cs | 31 ++------------------ src/slskd/Transfers/Downloads/DownloadService.cs | 6 +--- src/slskd/Transfers/Uploads/UploadService.cs | 4 +-- src/web/src/components/App.css | 2 +- src/web/src/components/App.jsx | 5 ++++ src/web/src/components/AppFooter.jsx | 2 +- .../Transfers/Uploads/UploadQueueTests.cs | 33 +++++++++++----------- 7 files changed, 28 insertions(+), 55 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f7434fb1..2ee57738 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1342,21 +1342,7 @@ namespace slskd */ Prometheus.Metrics.ConfigureMeterAdapter(options => { - options.InstrumentFilterPredicate = instrument => - { - return sources.Any(s => - { - Log.Warning("Testing: {Thing}", instrument.Meter.Name); - - if (s.IsMatch(instrument?.Meter?.Name)) - { - Log.Warning("Allowed {Thing}", instrument.Meter.Name); - return true; - } - - return false; - }); - }; + options.InstrumentFilterPredicate = instrument => sources.Any(s => s.IsMatch(instrument?.Meter?.Name)); }); /* @@ -1388,20 +1374,7 @@ namespace slskd */ Prometheus.Metrics.ConfigureEventCounterAdapter(options => { - options.EventSourceFilterPredicate = name => - { - return sources.Any(s => - { - Log.Warning("Testing: {Thing}", name); - if (s.IsMatch(name)) - { - Log.Warning("Allowed {Thing}", name); - return true; - } - - return false; - }); - }; + options.EventSourceFilterPredicate = name => sources.Any(s => s.IsMatch(name)); }); /* diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 1c0f443e..bfb9a97c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1227,14 +1227,12 @@ namespace slskd.Transfers.Downloads if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) { - Log.Warning("[{File}] Increment queued {Size}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Size); Telemetry.Metrics.Transfers.Downloads.Queued.Files.Inc(1); Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Inc(transfer.Size); } if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) { - Log.Warning("[{File}] Decrement queued {Size}, Increment in progress {Size}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Size, transfer.Size); Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Inc(1); @@ -1387,13 +1385,11 @@ namespace slskd.Transfers.Downloads if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) { - Log.Warning("[{File}] Decrement in progress {Size}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Size); Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); } else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) { - Log.Warning("[{File}] Decrement queued {Size}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Size); Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); } @@ -1547,7 +1543,7 @@ namespace slskd.Transfers.Downloads } finally { - Log.Debug("Download of {Filename} from user {Username} completed with states: {@States}", stateHistory); + Log.Debug("Download of {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); // figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes // for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 988a9cd9..46a468b4 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -518,10 +518,10 @@ namespace slskd.Transfers.Uploads } finally { - Log.Debug("Upload of {Filename} to user {Username} completed with states: {@States}", stateHistory); + Log.Debug("Upload of {Filename} to user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); // figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes - // for transfers that succeed this will be InProgress, for transfers that never started this will be Quued (cancelled or something) + // for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something) // state will almost certainly transition to errored or completed before we get here, so we can't just take the last state var mostRecentQueuedOrInProgressState = stateHistory .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 45e0e64d..1e2000f9 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -129,7 +129,7 @@ body { .app-content-body { flex: 1; - padding-bottom: 45px; /* footer */ + padding-bottom: 40px; /* footer */ } .navigation { diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index e412186b..0c0ca5a5 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -156,6 +156,7 @@ class App extends Component { super(props); this.state = initialState; + this.hubConnections = {}; } componentDidMount() { @@ -208,6 +209,8 @@ class App extends Component { this.setState({ error: false, retriesExhausted: false }), ); + await this.hubConnections.appHub?.stop(); + this.hubConnections.appHub = appHub; await appHub.start(); const metricsHub = createMetricsHubConnection(); @@ -216,6 +219,8 @@ class App extends Component { this.setState({ transferMetrics: metrics }); }); + await this.hubConnections.metricsHub?.stop(); + this.hubConnections.metricsHub = metricsHub; await metricsHub.start(); } diff --git a/src/web/src/components/AppFooter.jsx b/src/web/src/components/AppFooter.jsx index 35cfcd71..c7265e8a 100644 --- a/src/web/src/components/AppFooter.jsx +++ b/src/web/src/components/AppFooter.jsx @@ -3,7 +3,7 @@ import React from 'react'; import { Icon, Menu } from 'semantic-ui-react'; const formatSpeed = (bytesPerSecond) => { - if (!bytesPerSecond) { + if (!bytesPerSecond || bytesPerSecond < 1) { return ' 0 B/s'; } diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 6f21f9ba..b1da3a77 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -8,10 +8,9 @@ namespace slskd.Tests.Unit.Transfers.Uploads using Moq; using slskd.Transfers; using slskd.Users; - using Soulseek; using System; using Xunit; - using static slskd.Transfers.UploadQueue; + using slskd.Transfers.Uploads; public class UploadQueueTests { @@ -376,11 +375,11 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - Assert.Empty(queue.GetProperty>>("Uploads")); + Assert.Empty(queue.GetProperty>>("UploadDictionary")); queue.Enqueue(username, filename); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); Assert.Single(uploads); Assert.True(uploads.ContainsKey(username)); @@ -396,7 +395,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.Enqueue(username, filename); queue.Enqueue(username, filename2); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); Assert.Single(uploads); Assert.True(uploads.ContainsKey(username)); @@ -410,12 +409,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - Assert.Empty(queue.GetProperty>>("Uploads")); + Assert.Empty(queue.GetProperty>>("UploadDictionary")); queue.Enqueue(username, filename); queue.Enqueue(username2, filename2); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); Assert.Equal(2, uploads.Count); Assert.True(uploads.ContainsKey(username)); @@ -471,7 +470,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.Complete(username, filename); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); Assert.Single(uploads); Assert.True(uploads.ContainsKey(username)); @@ -509,14 +508,14 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.Enqueue(username, filename); queue.Enqueue(username, filename2); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); Assert.Single(uploads); queue.Complete(username, filename); queue.Complete(username, filename2); - uploads = queue.GetProperty>>("Uploads"); + uploads = queue.GetProperty>>("UploadDictionary"); Assert.Empty(uploads); } @@ -557,7 +556,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.Enqueue(username, filename); - var uploads = queue.GetProperty>>("Uploads"); + var uploads = queue.GetProperty>>("UploadDictionary"); var task = queue.AwaitStartAsync(username, filename); @@ -605,7 +604,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); var result = queue.InvokeMethod("Process"); @@ -629,7 +628,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); _ = queue.InvokeMethod("Process"); @@ -658,7 +657,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); var result = queue.InvokeMethod("Process"); @@ -687,7 +686,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); // all default group slots consumed var groups = queue.GetProperty>("Groups"); @@ -722,7 +721,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user2, Filename = file2, Enqueued = enqueued.AddHours(-2), Ready = ready } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); var groups = queue.GetProperty>("Groups"); groups[Application.DefaultGroup].Strategy = QueueStrategy.FirstInFirstOut; @@ -754,7 +753,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads new Upload() { Username = user2, Filename = file2, Enqueued = enqueued, Ready = ready.AddMinutes(-1) } }); - queue.SetProperty("Uploads", uploads); + queue.SetProperty("UploadDictionary", uploads); var groups = queue.GetProperty>("Groups"); groups[Application.DefaultGroup].Strategy = QueueStrategy.RoundRobin; -- cgit v1.2.3 From 28fa7202724da10075dbddc3244d5d5528b4bdad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Jun 2026 10:13:59 -0500 Subject: stop signalr hubs when logging out --- src/slskd/Program.cs | 4 ++-- src/slskd/Telemetry/API/MetricsHub.cs | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 4 ++-- src/web/src/components/App.jsx | 4 ++++ 5 files changed, 10 insertions(+), 6 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2ee57738..0fc6b294 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1342,7 +1342,7 @@ namespace slskd */ Prometheus.Metrics.ConfigureMeterAdapter(options => { - options.InstrumentFilterPredicate = instrument => sources.Any(s => s.IsMatch(instrument?.Meter?.Name)); + options.InstrumentFilterPredicate = instrument => sources.Any(s => instrument?.Meter?.Name is string name && s.IsMatch(name)); }); /* @@ -1374,7 +1374,7 @@ namespace slskd */ Prometheus.Metrics.ConfigureEventCounterAdapter(options => { - options.EventSourceFilterPredicate = name => sources.Any(s => s.IsMatch(name)); + options.EventSourceFilterPredicate = name => sources.Any(s => name is string n && s.IsMatch(n)); }); /* diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index 9161de85..5dcd4ecc 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -50,8 +50,8 @@ public class MetricsHub : Hub Metrics = metricsService; } - private MetricsService Metrics { get; } private static ILogger Log { get; } = Serilog.Log.ForContext(); + private MetricsService Metrics { get; } public override async Task OnConnectedAsync() { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 1dd81d37..a4d48279 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -208,7 +208,7 @@ namespace slskd.Transfers.Downloads EventBus = eventBus; Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); - Clock.EveryFiveSeconds += (_, _) => EmitMetrics(); + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 35abe881..5f98afac 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -197,7 +197,7 @@ namespace slskd.Transfers.Uploads Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); - Clock.EveryFiveSeconds += (_, _) => EmitMetrics(); + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// @@ -253,7 +253,7 @@ namespace slskd.Transfers.Uploads /// /// The Transfer to upload. /// The token to monitor for cancellation. - /// /// The operation context. + /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. /// Thrown if the specified Transfer is not in the Queued | Locally state. diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 0c0ca5a5..9839bf35 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -278,6 +278,10 @@ class App extends Component { logout = () => { session.logout(); + + this.hubConnections?.appHub?.stop(); + this.hubConnections?.metricsHub?.stop(); + this.setState({ login: { ...initialState.login } }); }; -- cgit v1.2.3