From 005a8310ad5729275a50903162eba0abf450f8b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 18:53:41 -0500 Subject: rough in transfer metrics --- src/slskd/Telemetry/Metrics.cs | 78 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33e16873..88d2706a 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -264,6 +264,84 @@ public static class Metrics private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds"); } + /// + /// Metrics related to transfers. + /// + public static class Transfers + { + /// + /// Metrics related to uploads. + /// + public static class Uploads + { + /// + /// Gets a counter representing the total number of uploads completed successfully. + /// + public static Counter Completed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_completed", "Total number of uploads completed successfully"); + + /// + /// Gets a counter representing the total number of uploads that failed. + /// + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_failed", "Total number of uploads that failed"); + + /// + /// Gets a counter representing the total number of bytes uploaded. + /// + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_bytes", "Total number of bytes uploaded"); + + /// + /// Gets a gauge representing the current number of active uploads. + /// + public static Gauge Active { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_active", "Current number of active uploads"); + + /// + /// Gets a gauge representing the current aggregate upload speed, in bytes per second. + /// + public static Gauge CurrentSpeed { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_speed_current", "Current aggregate upload speed, in bytes per second"); + + /// + /// Gets a gauge representing the current number of uploads waiting to be started. + /// + public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_queue_depth_current", "Current number of uploads waiting to be started"); + } + + /// + /// Metrics related to downloads. + /// + public static class Downloads + { + /// + /// Gets a counter representing the total number of downloads completed successfully. + /// + public static Counter Completed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_completed", "Total number of downloads completed successfully"); + + /// + /// Gets a counter representing the total number of downloads that failed. + /// + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_failed", "Total number of downloads that failed"); + + /// + /// Gets a counter representing the total number of bytes downloaded. + /// + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_bytes", "Total number of bytes downloaded"); + + /// + /// Gets a gauge representing the current number of active downloads. + /// + public static Gauge Active { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_active", "Current number of active downloads"); + + /// + /// Gets a gauge representing the current aggregate download speed, in bytes per second. + /// + public static Gauge CurrentSpeed { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_speed_current", "Current aggregate download speed, in bytes per second"); + + /// + /// Gets a gauge representing the current number of downloads queued locally, waiting to be started. + /// + public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_queue_depth_current", "Current number of downloads queued locally, waiting to be started"); + } + } + /// /// Metrics related to the distributed network. /// -- cgit v1.2.3 From 1b1ffdd6d7b1db0558dfb33c74e005d4ad8df2c1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 18:55:56 -0500 Subject: add notes --- src/slskd/Telemetry/Metrics.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 88d2706a..0cbd99cc 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -279,6 +279,8 @@ public static class Metrics /// public static Counter Completed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_completed", "Total number of uploads completed successfully"); + // todo: should this be succeeded? should we totalize? probably not + /// /// Gets a counter representing the total number of uploads that failed. /// @@ -299,10 +301,14 @@ public static class Metrics /// public static Gauge CurrentSpeed { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_speed_current", "Current aggregate upload speed, in bytes per second"); + // todo: this ^ is probably not sufficient for an aggregated field + /// /// Gets a gauge representing the current number of uploads waiting to be started. /// public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_queue_depth_current", "Current number of uploads waiting to be started"); + + // todo: should we have a gauge for queued bytes, too? } /// -- cgit v1.2.3 From 244256980318eae6fd5648277f7ac2229be4f267 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 1 May 2026 18:42:31 -0500 Subject: pin down upload metrics --- src/slskd/Telemetry/Metrics.cs | 77 ++++++++++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 17 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 0cbd99cc..ec8681ce 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -275,31 +275,74 @@ public static class Metrics public static class Uploads { /// - /// Gets a counter representing the total number of uploads completed successfully. + /// Metrics related to in-progress uploads. /// - public static Counter Completed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_completed", "Total number of uploads completed successfully"); + public static class InProgress + { + /// + /// Gets a counter representing the current number of unique users with in-progress uploads. + /// + public static Counter Users { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_in-progress_users_current", + help: "Current number of unique users with in-progress uploads"); - // todo: should this be succeeded? should we totalize? probably not + /// + /// Gets a gauge representing the current number of in-progress uploads. + /// + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in-progress_files_current", + help: "Current total number of in-progress uploads"); - /// - /// Gets a counter representing the total number of uploads that failed. - /// - public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_failed", "Total number of uploads that failed"); + /// + /// Gets a gauge representing the current total size, in bytes, of in-progress uploads. + /// + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in-progress_bytes_current", + help: "Current total size, in bytes, of in-progress uploads"); - /// - /// Gets a counter representing the total number of bytes uploaded. - /// - public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_uploads_bytes", "Total number of bytes uploaded"); + /// + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress uploads. + /// + public static TimedCounter TotalSpeed { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentTotalSpeedGauge.Set(count)); + public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in-progress_total_speed_bytes_current", + help: "Current total speed, in bytes per second, of in-progress uploads"); - /// - /// Gets a gauge representing the current number of active uploads. - /// - public static Gauge Active { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_active", "Current number of active uploads"); + /// + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress uploads. + /// + public static ExponentialMovingAverage AverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in-progress_average_speed_bytes_current", + help: "Current average speed, in bytes per second, of in-progress uploads"); + } /// - /// Gets a gauge representing the current aggregate upload speed, in bytes per second. + /// Metrics related to queued uploads. /// - public static Gauge CurrentSpeed { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_speed_current", "Current aggregate upload speed, in bytes per second"); + public static class Queued + { + /// + /// Gets a counter representing the total number of unique users with queued uploads. + /// + public static Counter Users { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_in-progress_users", + help: "Current number of unique users with queued uploads"); + + /// + /// Gets a gauge representing the current number of queued uploads. + /// + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_files_current", + help: "Current total number of in-progress uploads"); + + /// + /// Gets a gauge representing the current number of queued uploads. + /// + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_bytes_current", + help: "Current total size, in bytes, of in-progress uploads"); + } // todo: this ^ is probably not sufficient for an aggregated field -- cgit v1.2.3 From 5895c77c09efd92499ffb0ff9d492f46c4e05c16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 1 May 2026 18:50:45 -0500 Subject: names and things --- src/slskd/Telemetry/Metrics.cs | 73 ++++++++---------------------------------- 1 file changed, 14 insertions(+), 59 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index ec8681ce..0ec86a94 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -280,24 +280,24 @@ public static class Metrics public static class InProgress { /// - /// Gets a counter representing the current number of unique users with in-progress uploads. + /// Gets a gauge representing the current number of unique users with in-progress uploads. /// - public static Counter Users { get; } = Prometheus.Metrics.CreateCounter( - name: "slskd_transfers_uploads_in-progress_users_current", + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_users_current", help: "Current number of unique users with in-progress uploads"); /// /// Gets a gauge representing the current number of in-progress uploads. /// public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( - name: "slskd_transfers_uploads_in-progress_files_current", - help: "Current total number of in-progress uploads"); + name: "slskd_transfers_uploads_in_progress_files_current", + help: "Current number of in-progress uploads"); /// /// Gets a gauge representing the current total size, in bytes, of in-progress uploads. /// public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( - name: "slskd_transfers_uploads_in-progress_bytes_current", + name: "slskd_transfers_uploads_in_progress_bytes_current", help: "Current total size, in bytes, of in-progress uploads"); /// @@ -305,7 +305,7 @@ public static class Metrics /// public static TimedCounter TotalSpeed { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentTotalSpeedGauge.Set(count)); public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( - name: "slskd_transfers_uploads_in-progress_total_speed_bytes_current", + name: "slskd_transfers_uploads_in_progress_speed_total_current", help: "Current total speed, in bytes per second, of in-progress uploads"); /// @@ -313,7 +313,7 @@ public static class Metrics /// public static ExponentialMovingAverage AverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( - name: "slskd_transfers_uploads_in-progress_average_speed_bytes_current", + name: "slskd_transfers_uploads_in_progress_speed_average_current", help: "Current average speed, in bytes per second, of in-progress uploads"); } @@ -323,10 +323,10 @@ public static class Metrics public static class Queued { /// - /// Gets a counter representing the total number of unique users with queued uploads. + /// Gets a gauge representing the current number of unique users with queued uploads. /// - public static Counter Users { get; } = Prometheus.Metrics.CreateCounter( - name: "slskd_transfers_uploads_in-progress_users", + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_users_current", help: "Current number of unique users with queued uploads"); /// @@ -334,60 +334,15 @@ public static class Metrics /// public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_uploads_queued_files_current", - help: "Current total number of in-progress uploads"); + help: "Current number of queued uploads"); /// - /// Gets a gauge representing the current number of queued uploads. + /// Gets a gauge representing the current total size, in bytes, of queued uploads. /// public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_uploads_queued_bytes_current", - help: "Current total size, in bytes, of in-progress uploads"); + help: "Current total size, in bytes, of queued uploads"); } - - // todo: this ^ is probably not sufficient for an aggregated field - - /// - /// Gets a gauge representing the current number of uploads waiting to be started. - /// - public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_uploads_queue_depth_current", "Current number of uploads waiting to be started"); - - // todo: should we have a gauge for queued bytes, too? - } - - /// - /// Metrics related to downloads. - /// - public static class Downloads - { - /// - /// Gets a counter representing the total number of downloads completed successfully. - /// - public static Counter Completed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_completed", "Total number of downloads completed successfully"); - - /// - /// Gets a counter representing the total number of downloads that failed. - /// - public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_failed", "Total number of downloads that failed"); - - /// - /// Gets a counter representing the total number of bytes downloaded. - /// - public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter("slskd_transfers_downloads_bytes", "Total number of bytes downloaded"); - - /// - /// Gets a gauge representing the current number of active downloads. - /// - public static Gauge Active { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_active", "Current number of active downloads"); - - /// - /// Gets a gauge representing the current aggregate download speed, in bytes per second. - /// - public static Gauge CurrentSpeed { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_speed_current", "Current aggregate download speed, in bytes per second"); - - /// - /// Gets a gauge representing the current number of downloads queued locally, waiting to be started. - /// - public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_transfers_downloads_queue_depth_current", "Current number of downloads queued locally, waiting to be started"); } } -- cgit v1.2.3 From 477eaa97466cd36280639b1a43fa95938d4e99a2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 1 May 2026 18:54:48 -0500 Subject: add downloads --- src/slskd/Telemetry/Metrics.cs | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 0ec86a94..0f998428 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -344,6 +344,82 @@ public static class Metrics help: "Current total size, in bytes, of queued uploads"); } } + + /// + /// Metrics related to downloads. + /// + public static class Downloads + { + /// + /// Metrics related to in-progress downloads. + /// + public static class InProgress + { + /// + /// Gets a gauge representing the current number of unique users with in-progress downloads. + /// + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_users_current", + help: "Current number of unique users with in-progress downloads"); + + /// + /// Gets a gauge representing the current number of in-progress downloads. + /// + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_files_current", + help: "Current number of in-progress downloads"); + + /// + /// Gets a gauge representing the current total size, in bytes, of in-progress downloads. + /// + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_bytes_current", + help: "Current total size, in bytes, of in-progress downloads"); + + /// + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress downloads. + /// + public static TimedCounter TotalSpeed { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentTotalSpeedGauge.Set(count)); + public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_speed_total_current", + help: "Current total speed, in bytes per second, of in-progress downloads"); + + /// + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress downloads. + /// + public static ExponentialMovingAverage AverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_speed_average_current", + help: "Current average speed, in bytes per second, of in-progress downloads"); + } + + /// + /// Metrics related to queued downloads. + /// + public static class Queued + { + /// + /// Gets a gauge representing the current number of unique users with queued downloads. + /// + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_users_current", + help: "Current number of unique users with queued downloads"); + + /// + /// Gets a gauge representing the current number of queued downloads. + /// + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_files_current", + help: "Current number of queued downloads"); + + /// + /// Gets a gauge representing the current total size, in bytes, of queued downloads. + /// + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_bytes_current", + help: "Current total size, in bytes, of queued downloads"); + } + } } /// -- cgit v1.2.3 From 97a1b160903e9719ab7ef00d23ac3e31dcbfcff5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 May 2026 16:55:35 -0500 Subject: add completed metrics and a histogram for average speed --- src/slskd/Telemetry/Metrics.cs | 62 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 0f998428..dae87699 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -303,7 +303,7 @@ public static class Metrics /// /// Gets a gauge representing the current total speed, in bytes per second, of in-progress uploads. /// - public static TimedCounter TotalSpeed { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentTotalSpeedGauge.Set(count)); + public static ExponentialMovingAverage CurrentTotalSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentTotalSpeedGauge.Set(value)); public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_uploads_in_progress_speed_total_current", help: "Current total speed, in bytes per second, of in-progress uploads"); @@ -311,7 +311,7 @@ public static class Metrics /// /// Gets a gauge representing the current average speed, in bytes per second, of in-progress uploads. /// - public static ExponentialMovingAverage AverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_uploads_in_progress_speed_average_current", help: "Current average speed, in bytes per second, of in-progress uploads"); @@ -343,6 +343,64 @@ public static class Metrics name: "slskd_transfers_uploads_queued_bytes_current", help: "Current total size, in bytes, of queued uploads"); } + + /// + /// Metrics related to completed uploads. + /// + public static class Completed + { + /// + /// Gets a counter representing the total number of uploads that completed successfully. + /// + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_succeeded", + help: "Total number of uploads that completed successfully"); + + /// + /// Gets a counter representing the total number of uploads that failed. + /// + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_failed", + help: "Total number of uploads that failed"); + + /// + /// Gets a counter representing the total number of bytes transferred by successfully completed uploads. + /// + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_bytes", + help: "Total number of bytes transferred by successfully completed uploads"); + + /// + /// Gets a histogram representing the the average speed of completed uploads, in bytes per second. + /// + public static Histogram AverageSpeed { get; } = Prometheus.Metrics.CreateHistogram( + name: "slskd_transfers_uploads_completed_speed_average", + help: "The average speed of completed uploads, in bytes per second", + new HistogramConfiguration + { + Buckets = [ + 1_024, // 1 KB/s + 10_240, // 10 KB/s + 51_200, // 50 KB/s + 102_400, // 100 KB/s + 204_800, // 200 KB/s + 307_200, // 300 KB/s + 409_600, // 400 KB/s + 512_000, // 500 KB/s + 1_048_576, // 1 MB/s + 2_097_152, // 2 MB/s + 4_194_304, // 4 MB/s + 6_291_456, // 6 MB/s + 10_485_760, // 10 MB/s + 26_214_400, // 25 MB/s + 52_428_800, // 50 MB/s + 104_857_600, // 100 MB/s + 262_144_000, // 250 MB/s + 524_288_000, // 500 MB/s + 1_073_741_824, // 1 GB/s + ], + }); + } } /// -- cgit v1.2.3 From 4d2089daa0b410120541c0927a69447206466e29 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 2 May 2026 16:58:37 -0500 Subject: fix up download metrics too --- src/slskd/Telemetry/Metrics.cs | 76 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 67 insertions(+), 9 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index dae87699..b7ee0092 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -356,13 +356,6 @@ public static class Metrics name: "slskd_transfers_uploads_completed_succeeded", help: "Total number of uploads that completed successfully"); - /// - /// Gets a counter representing the total number of uploads that failed. - /// - public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( - name: "slskd_transfers_uploads_completed_failed", - help: "Total number of uploads that failed"); - /// /// Gets a counter representing the total number of bytes transferred by successfully completed uploads. /// @@ -370,6 +363,13 @@ public static class Metrics name: "slskd_transfers_uploads_completed_bytes", help: "Total number of bytes transferred by successfully completed uploads"); + /// + /// Gets a counter representing the total number of uploads that failed. + /// + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_failed", + help: "Total number of uploads that failed"); + /// /// Gets a histogram representing the the average speed of completed uploads, in bytes per second. /// @@ -437,7 +437,7 @@ public static class Metrics /// /// Gets a gauge representing the current total speed, in bytes per second, of in-progress downloads. /// - public static TimedCounter TotalSpeed { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentTotalSpeedGauge.Set(count)); + public static ExponentialMovingAverage CurrentTotalSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentTotalSpeedGauge.Set(value)); public static Gauge CurrentTotalSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_downloads_in_progress_speed_total_current", help: "Current total speed, in bytes per second, of in-progress downloads"); @@ -445,7 +445,7 @@ public static class Metrics /// /// Gets a gauge representing the current average speed, in bytes per second, of in-progress downloads. /// - public static ExponentialMovingAverage AverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( name: "slskd_transfers_downloads_in_progress_speed_average_current", help: "Current average speed, in bytes per second, of in-progress downloads"); @@ -477,6 +477,64 @@ public static class Metrics name: "slskd_transfers_downloads_queued_bytes_current", help: "Current total size, in bytes, of queued downloads"); } + + /// + /// Metrics related to completed downloads. + /// + public static class Completed + { + /// + /// Gets a counter representing the total number of downloads that completed successfully. + /// + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_succeeded", + help: "Total number of downloads that completed successfully"); + + /// + /// Gets a counter representing the total number of bytes transferred by successfully completed downloads. + /// + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_bytes", + help: "Total number of bytes transferred by successfully completed downloads"); + + /// + /// Gets a counter representing the total number of downloads that failed. + /// + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_failed", + help: "Total number of downloads that failed"); + + /// + /// Gets a histogram representing the the average speed of completed downloads, in bytes per second. + /// + public static Histogram AverageSpeed { get; } = Prometheus.Metrics.CreateHistogram( + name: "slskd_transfers_downloads_completed_speed_average", + help: "The average speed of completed downloads, in bytes per second", + new HistogramConfiguration + { + Buckets = [ + 1_024, // 1 KB/s + 10_240, // 10 KB/s + 51_200, // 50 KB/s + 102_400, // 100 KB/s + 204_800, // 200 KB/s + 307_200, // 300 KB/s + 409_600, // 400 KB/s + 512_000, // 500 KB/s + 1_048_576, // 1 MB/s + 2_097_152, // 2 MB/s + 4_194_304, // 4 MB/s + 6_291_456, // 6 MB/s + 10_485_760, // 10 MB/s + 26_214_400, // 25 MB/s + 52_428_800, // 50 MB/s + 104_857_600, // 100 MB/s + 262_144_000, // 250 MB/s + 524_288_000, // 500 MB/s + 1_073_741_824, // 1 GB/s + ], + }); + } } } -- cgit v1.2.3 From 86bab11ddbd008f236006ee49bde7de40106675c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Jun 2026 14:33:24 -0500 Subject: stub the MetricsHub --- src/slskd/Telemetry/API/MetricsHub.cs | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/slskd/Telemetry/API/MetricsHub.cs (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs new file mode 100644 index 00000000..ff4a6eeb --- /dev/null +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -0,0 +1,61 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System.Threading.Tasks; +using Microsoft.AspNetCore.SignalR; + +namespace slskd.Telemetry; + +public static class MetricsHubMethods +{ + public static readonly string TRANSFERS = nameof(TRANSFERS); +} + +public static class ApplicationHubExtensions +{ + public static Task BroadcastTransferMetrics(this IHubContext hub) + { + return hub.Clients.All.SendAsync(MetricsHubMethods.TRANSFERS, new { }); + } +} + +public class MetricsHub : Hub +{ + public MetricsHub() + { + } + + public override async Task OnConnectedAsync() + { + await Clients.Caller.SendAsync(MetricsHubMethods.TRANSFERS, new { }); + } +} \ No newline at end of file -- cgit v1.2.3 From 5079a12e2aa540fe756285297f1cfbaaf30fc176 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Jun 2026 14:48:11 -0500 Subject: add CurrentAverageSpeed --- src/slskd/Telemetry/Metrics.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index b7ee0092..fa15ed6d 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -370,6 +370,14 @@ public static class Metrics name: "slskd_transfers_uploads_completed_failed", help: "Total number of uploads that failed"); + /// + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_completed_speed_average_current", + help: "Current average speed, in bytes per second, of completed uploads"); + /// /// Gets a histogram representing the the average speed of completed uploads, in bytes per second. /// @@ -504,6 +512,14 @@ public static class Metrics name: "slskd_transfers_downloads_completed_failed", help: "Total number of downloads that failed"); + /// + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// + public static ExponentialMovingAverage CurrentAverageSpeed { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentAverageSpeedGauge.Set(value)); + public static Gauge CurrentAverageSpeedGauge { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_completed_speed_average_current", + help: "Current average speed, in bytes per second, of completed downloads"); + /// /// Gets a histogram representing the the average speed of completed downloads, in bytes per second. /// -- cgit v1.2.3 From cfa299fc873f619730d867db8b73ebc5cf40cd26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Jun 2026 19:23:39 -0500 Subject: send transfer metrics every second --- src/slskd/Telemetry/API/MetricsHub.cs | 46 ++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index ff4a6eeb..889636cc 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -37,14 +37,14 @@ namespace slskd.Telemetry; public static class MetricsHubMethods { - public static readonly string TRANSFERS = nameof(TRANSFERS); + public static readonly string Transfers = nameof(Transfers); } -public static class ApplicationHubExtensions +public static class MetricsHubExtensions { public static Task BroadcastTransferMetrics(this IHubContext hub) { - return hub.Clients.All.SendAsync(MetricsHubMethods.TRANSFERS, new { }); + return hub.Clients.All.SendAsync(MetricsHubMethods.Transfers, new { }); } } @@ -52,10 +52,48 @@ public class MetricsHub : Hub { public MetricsHub() { + Clock.EverySecond += (_, _) => Clients.All.SendAsync(MetricsHubMethods.Transfers, GetMetrics()); } public override async Task OnConnectedAsync() { - await Clients.Caller.SendAsync(MetricsHubMethods.TRANSFERS, new { }); + await Clients.Caller.SendAsync(MetricsHubMethods.Transfers, GetMetrics()); + } + + private object GetMetrics() + { + return 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, + }, + }, + }; } } \ No newline at end of file -- cgit v1.2.3 From 9f02e15709c2168bf029822c930b8a69f27cd3fc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jun 2026 22:02:44 -0500 Subject: add metrics hub --- src/slskd/Telemetry/TelemetryService.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs index 74800126..81ee6380 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -30,16 +30,26 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // +using Microsoft.AspNetCore.SignalR; + namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, ReportsService reportsService) + public TelemetryService(PrometheusService prometheusService, ReportsService reportsService, IHubContext metricsHub) { Prometheus = prometheusService; Reports = reportsService; + + MetricsHub = metricsHub; + + Clock.EverySecond += (_, _) => + { + MetricsHub.BroadcastTransferMetrics(); + }; } public PrometheusService Prometheus { get; } public ReportsService Reports { get; } + private IHubContext MetricsHub { get; } } \ No newline at end of file -- cgit v1.2.3 From c292d3db3fd96a72b1be8041d4233ea6e70b1f00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jun 2026 22:04:32 -0500 Subject: wip --- src/slskd/Telemetry/API/MetricsHub.cs | 13 +++++++++---- src/slskd/Transfers/Downloads/DownloadService.cs | 5 ++++- src/slskd/Transfers/Uploads/UploadService.cs | 3 +++ src/web/src/components/App.css | 14 ++++++++++---- 4 files changed, 26 insertions(+), 9 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index 889636cc..d8692755 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -32,6 +32,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; +using Serilog; namespace slskd.Telemetry; @@ -44,7 +45,7 @@ public static class MetricsHubExtensions { public static Task BroadcastTransferMetrics(this IHubContext hub) { - return hub.Clients.All.SendAsync(MetricsHubMethods.Transfers, new { }); + return hub.Clients.All.SendAsync(MetricsHubMethods.Transfers, MetricsHub.GetMetrics()); } } @@ -52,7 +53,6 @@ public class MetricsHub : Hub { public MetricsHub() { - Clock.EverySecond += (_, _) => Clients.All.SendAsync(MetricsHubMethods.Transfers, GetMetrics()); } public override async Task OnConnectedAsync() @@ -60,9 +60,11 @@ public class MetricsHub : Hub await Clients.Caller.SendAsync(MetricsHubMethods.Transfers, GetMetrics()); } - private object GetMetrics() + private static ILogger Log { get; } = Serilog.Log.ForContext(); + + public static object GetMetrics() { - return new + var metrics = new { Downloads = new { @@ -95,5 +97,8 @@ public class MetricsHub : Hub }, }, }; + + Log.Warning("{Metrics}", metrics); + return metrics; } } \ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 117502bf..55b05b95 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1126,6 +1126,9 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed .Update(inProgress.Sum(u => u.AverageSpeed)); + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed + .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0); + Log.Warning("Metrics: Set Downloads InProgress Users, Files, and Bytes to {Users}, {Files} and {Bytes}, respectively", Telemetry.Metrics.Transfers.Downloads.InProgress.Users.Value, Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Value, Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Value); } @@ -1392,7 +1395,7 @@ namespace slskd.Transfers.Downloads } // reset the history to make detection logic above easier and more accurate - Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", stateHistory); + Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); stateHistory = []; Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 60804ebe..cf7e8753 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -1022,6 +1022,9 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed .Update(inProgress.Sum(u => u.AverageSpeed)); + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed + .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0); + Log.Warning("Metrics: Set Upload InProgress Users, Files, and Bytes to {Users}, {Files} and {Bytes}, respectively", Telemetry.Metrics.Transfers.Uploads.InProgress.Users.Value, Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Value, Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Value); } diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index ecadc1d5..0ecf500c 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -289,12 +289,18 @@ body { .footer-version { margin-left: 6px; font-family: monospace; - font-size: 11px; - opacity: 0.6; + font-size: 13px; + opacity: 0.7; } .footer-license { margin-left: 6px; - font-size: 11px; - opacity: 0.4; + font-size: 13px; + opacity: 0.5; +} + +.footer-stat-detail { + margin-left: 6px; + font-size: 13px; + opacity: 0.7; } \ No newline at end of file -- 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/Telemetry') 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 9272fe6932a33ae681216a02dbaabf58d1351185 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 19 Jun 2026 18:19:13 -0500 Subject: update metrics every 5 seconds, synchronize updates to prevent desync --- src/slskd/Core/Clock.cs | 10 ++ src/slskd/Telemetry/Metrics.cs | 21 +++++ src/slskd/Transfers/Downloads/DownloadService.cs | 115 ++++++++++++++--------- src/slskd/Transfers/Uploads/UploadQueue.cs | 7 +- src/slskd/Transfers/Uploads/UploadService.cs | 86 +++++++++++------ 5 files changed, 164 insertions(+), 75 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs index ceb26b91..6dabb7ac 100644 --- a/src/slskd/Core/Clock.cs +++ b/src/slskd/Core/Clock.cs @@ -49,6 +49,7 @@ namespace slskd EveryFiveMinutesTimer.Elapsed += (_, _) => Fire(EveryFiveMinutes); EveryThirtyMinutesTimer.Elapsed += (_, _) => Fire(EveryThirtyMinutes); EveryHourTimer.Elapsed += (_, _) => Fire(EveryHour); + EveryFiveSecondsTimer.Elapsed += (_, _) => Fire(EveryFiveSeconds); EverySecondTimer.Elapsed += (_, _) => Fire(EverySecond); EveryFiveHundredMillisecondsTimer.Elapsed += (_, _) => Fire(EveryFiveHundredMilliseconds); } @@ -78,6 +79,11 @@ namespace slskd /// public static event EventHandler EveryFifteenSeconds; + /// + /// Fires every 5 seconds. + /// + public static event EventHandler EveryFiveSeconds; + /// /// Fires every second. /// @@ -99,6 +105,7 @@ namespace slskd private static Timer EveryThirtySecondsTimer { get; } = CreateTimer(interval: 1000 * 30); private static Timer EveryFifteenSecondsTimer { get; } = CreateTimer(interval: 1000 * 15); private static Timer EveryThirtyMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 30); + private static Timer EveryFiveSecondsTimer { get; } = CreateTimer(interval: 1000 * 5); private static Timer EverySecondTimer { get; } = CreateTimer(interval: 1000); private static Timer EveryFiveHundredMillisecondsTimer { get; } = CreateTimer(interval: 500); @@ -114,6 +121,7 @@ namespace slskd EveryFiveMinutesTimer.Enabled = true; EveryThirtyMinutesTimer.Enabled = true; EveryHourTimer.Enabled = true; + EveryFiveSecondsTimer.Enabled = true; EverySecondTimer.Enabled = true; EveryFiveHundredMillisecondsTimer.Enabled = true; @@ -126,6 +134,7 @@ namespace slskd Task.Run(() => Fire(EveryFiveMinutes, firstRunArgs)), Task.Run(() => Fire(EveryThirtyMinutes, firstRunArgs)), Task.Run(() => Fire(EveryHour, firstRunArgs)), + Task.Run(() => Fire(EveryFiveSeconds, firstRunArgs)), Task.Run(() => Fire(EverySecond, firstRunArgs)), Task.Run(() => Fire(EveryFiveHundredMilliseconds, firstRunArgs))); } @@ -140,6 +149,7 @@ namespace slskd EveryFifteenSecondsTimer.Stop(); EveryFiveMinutesTimer.Stop(); EveryThirtyMinutesTimer.Stop(); + EveryFiveSecondsTimer.Stop(); EveryHourTimer.Stop(); EverySecondTimer.Stop(); EveryFiveHundredMillisecondsTimer.Stop(); diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index fa15ed6d..921941a9 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -33,6 +33,7 @@ namespace slskd.Telemetry; using System; +using System.Threading; using Prometheus; /// @@ -45,6 +46,26 @@ using Prometheus; /// public static class Metrics { + private static SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// + /// Updates metrics under a mutex to prevent mismatches and under/overruns. + /// + /// Updates to execute. + public static void Update(Action work) + { + SyncRoot.Wait(); + + try + { + work.Invoke(); + } + finally + { + SyncRoot.Release(); + } + } + /// /// Metrics related to search requests and responses. /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bfb9a97c..e8e1f39b 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.EveryFifteenSeconds += (_, _) => EmitMetrics(); + Clock.EveryFiveSeconds += (_, _) => EmitMetrics(); } /// @@ -1136,8 +1136,11 @@ namespace slskd.Transfers.Downloads } } - EmitQueuedMetrics(); - EmitInProgressMetrics(); + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); } /// @@ -1225,24 +1228,27 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(args.Transfer); - if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + Telemetry.Metrics.Update(() => { - Telemetry.Metrics.Transfers.Downloads.Queued.Files.Inc(1); - Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Inc(transfer.Size); - } + if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + { + 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)) - { - 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); - Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Inc(transfer.Size); - } + if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) + { + 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); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Inc(transfer.Size); + } - stateHistory.Add(transfer.State); + stateHistory.Add(transfer.State); - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); + }); } finally { @@ -1274,7 +1280,10 @@ namespace slskd.Transfers.Downloads .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }); } finally { @@ -1383,16 +1392,19 @@ namespace slskd.Transfers.Downloads var mostRecentQueuedOrInProgressState = stateHistory .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); - if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + Telemetry.Metrics.Update(() => { - Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); - Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); - } - else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) - { - Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); - Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); - } + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + } + }); // reset the history to make detection logic above easier and more accurate Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory); @@ -1426,9 +1438,12 @@ namespace slskd.Transfers.Downloads // todo: broadcast to signalr hub SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Downloads.Completed.Succeeded.Inc(1); - Telemetry.Metrics.Transfers.Downloads.Completed.Bytes.Inc(transfer.BytesTransferred); - Telemetry.Metrics.Transfers.Downloads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Succeeded.Inc(1); + Telemetry.Metrics.Transfers.Downloads.Completed.Bytes.Inc(transfer.BytesTransferred); + Telemetry.Metrics.Transfers.Downloads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + }); Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); @@ -1525,7 +1540,11 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }); throw; } @@ -1537,7 +1556,11 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }); throw; } @@ -1551,18 +1574,24 @@ namespace slskd.Transfers.Downloads var mostRecentQueuedOrInProgressState = stateHistory .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); - if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) - { - // if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition - Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); - Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); - } - else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + Telemetry.Metrics.Update(() => { - // if the transfer never transitioned to in progress but it was queued at any point, decrement queued - Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); - Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); - } + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + { + // if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition + Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + { + // if the transfer never transitioned to in progress but it was queued at any point, decrement queued + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + }); + } + }); if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) { diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index b20dba7c..2dca0d9e 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -572,8 +572,11 @@ namespace slskd.Transfers.Uploads private void EmitMetrics() { - Telemetry.Metrics.Transfers.Uploads.Queued.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is null))); - Telemetry.Metrics.Transfers.Uploads.InProgress.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is not null))); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Queued.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is null))); + Telemetry.Metrics.Transfers.Uploads.InProgress.Users.Set(UploadDictionary.Values.Count(u => u.Any(t => t.Started is not null))); + }); } } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 46a468b4..881e1e26 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -195,7 +195,7 @@ namespace slskd.Transfers.Uploads Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); - Clock.EveryFifteenSeconds += (_, _) => EmitMetrics(); + Clock.EveryFiveSeconds += (_, _) => EmitMetrics(); } /// @@ -348,19 +348,22 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(args.Transfer); - if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + Telemetry.Metrics.Update(() => { - Telemetry.Metrics.Transfers.Uploads.Queued.Files.Inc(1); - Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Inc(transfer.Size); - } + if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Inc(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Inc(transfer.Size); + } - if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) - { - Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); - Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); - Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1); - Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size); - } + if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); + Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1); + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size); + } + }); stateHistory.Add(transfer.State); @@ -392,7 +395,10 @@ namespace slskd.Transfers.Uploads .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }); } finally { @@ -465,9 +471,12 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1); - Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred); - Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1); + Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred); + Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); + }); EventBus.Raise(new UploadFileCompleteEvent { @@ -488,7 +497,10 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }); throw; } @@ -500,7 +512,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }); throw; } @@ -512,7 +528,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }); throw; } @@ -526,16 +546,19 @@ namespace slskd.Transfers.Uploads var mostRecentQueuedOrInProgressState = stateHistory .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); - if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + Telemetry.Metrics.Update(() => { - Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1); - Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size); - } - else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) - { - Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); - Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); - } + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size); + } + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + { + Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); + } + }); if (host != Program.LocalHostName) { @@ -1032,8 +1055,11 @@ namespace slskd.Transfers.Uploads } } - EmitQueuedMetrics(); - EmitInProgressMetrics(); + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); } private bool TryFail(Guid id, string exception, TransferStates state) -- cgit v1.2.3 From 4ce36c42ab8d78ae5b9412e260d25736dbfa0f25 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 20 Jun 2026 17:21:06 -0500 Subject: fix deadlock on re-entrant update semaphore, tweak speed metric collection --- src/slskd/Telemetry/Metrics.cs | 9 +++- src/slskd/Telemetry/MetricsService.cs | 7 +++ src/slskd/Transfers/Downloads/DownloadService.cs | 44 +++++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 56 +++++++++++++++--------- src/web/src/components/AppFooter.jsx | 2 +- 5 files changed, 77 insertions(+), 41 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 921941a9..822f6aeb 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -51,10 +51,15 @@ public static class Metrics /// /// Updates metrics under a mutex to prevent mismatches and under/overruns. /// + /// + /// This method uses a for synchronization and it is therefore safe to do async work + /// inside of , though it is discouraged for causing un-needed contention. + /// /// Updates to execute. - public static void Update(Action work) + /// The token to monitor for cancellation requests. + public static void Update(Action work, CancellationToken cancellationToken = default) { - SyncRoot.Wait(); + SyncRoot.Wait(cancellationToken); try { diff --git a/src/slskd/Telemetry/MetricsService.cs b/src/slskd/Telemetry/MetricsService.cs index 64610fa5..1c69ef85 100644 --- a/src/slskd/Telemetry/MetricsService.cs +++ b/src/slskd/Telemetry/MetricsService.cs @@ -32,8 +32,15 @@ namespace slskd.Telemetry; +using Serilog; + +/// +/// Metrics. +/// public class MetricsService { + private ILogger Log { get; } = Serilog.Log.ForContext(); + public object Current() { var metrics = new diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e8e1f39b..1dd81d37 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1185,6 +1185,7 @@ namespace slskd.Transfers.Downloads var updateSyncRoot = new SemaphoreSlim(1, 1); var stateHistory = new List(); + DateTime lastReportedAverageSpeed = default; try { @@ -1243,12 +1244,12 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Inc(1); Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Inc(transfer.Size); } + }); - stateHistory.Add(transfer.State); + stateHistory.Add(transfer.State); - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); - }); + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } finally { @@ -1280,10 +1281,20 @@ namespace slskd.Transfers.Downloads .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - Telemetry.Metrics.Update(() => + // progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms) + // the transfer's speed is also zero until it has enough data to compute the EMA, so throw both + // repeated and zero values out + var now = DateTime.UtcNow; + + if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000)) { - Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); - }); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } } finally { @@ -1443,7 +1454,7 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Transfers.Downloads.Completed.Succeeded.Inc(1); Telemetry.Metrics.Transfers.Downloads.Completed.Bytes.Inc(transfer.BytesTransferred); Telemetry.Metrics.Transfers.Downloads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); - }); + }, cancellationToken); Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); @@ -1544,7 +1555,7 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); - }); + }, cancellationToken); throw; } @@ -1560,7 +1571,7 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); - }); + }, cancellationToken); throw; } @@ -1576,22 +1587,19 @@ namespace slskd.Transfers.Downloads Telemetry.Metrics.Update(() => { - if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Value > 0) { // if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1); Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size); } - else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.Queued.Files.Value > 0) { // if the transfer never transitioned to in progress but it was queued at any point, decrement queued - Telemetry.Metrics.Update(() => - { - Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); - Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); - }); + Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); } - }); + }, cancellationToken); if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 881e1e26..55e525f3 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// /// Adds the specified . Supersedes any existing record for the same file and username. /// - /// This should generally not be called; use instead. + /// This should generally not be called; use instead. /// void AddOrSupersede(Transfer transfer); @@ -78,20 +78,22 @@ namespace slskd.Transfers.Uploads /// /// The username of the requesting user. /// The local filename of the requested file. + /// The token to monitor for cancellation. /// The operation context. - Task EnqueueAsync(string username, string filename); + Task EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default); /// /// Uploads the specified enqueued to the requesting user. /// /// The Transfer to upload. + /// The token to monitor for cancellation. /// 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. /// Thrown if an upload matching the username and filename is already tracked by Soulseek.NET. /// Thrown if the specified file can't be found on disk. - Task UploadAsync(Transfer transfer); + Task UploadAsync(Transfer transfer, CancellationToken cancellationToken = default); /// /// Finds a single upload matching the specified . @@ -223,7 +225,7 @@ namespace slskd.Transfers.Uploads /// /// Adds the specified . Supersedes any existing record for the same file and username. /// - /// This should generally not be called; use instead. + /// This should generally not be called; use instead. /// public void AddOrSupersede(Transfer transfer) { @@ -250,21 +252,23 @@ namespace slskd.Transfers.Uploads /// Uploads the specified enqueued to the requesting user. /// /// The Transfer to upload. - /// The operation context. + /// The token to monitor for cancellation. + /// /// 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. /// Thrown if an upload matching the username and filename is already tracked by Soulseek.NET. /// Thrown if the specified file can't be found on disk. - public async Task UploadAsync(Transfer transfer) + public async Task UploadAsync(Transfer transfer, CancellationToken cancellationToken = default) { - var cts = new CancellationTokenSource(); + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); string host = default; string localFilename = default; long localFileLength = default; var stateHistory = new List(); + DateTime lastReportedAverageSpeed = default; var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; @@ -363,7 +367,7 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1); Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size); } - }); + }, cancellationToken); stateHistory.Add(transfer.State); @@ -395,10 +399,21 @@ namespace slskd.Transfers.Uploads .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - Telemetry.Metrics.Update(() => + // progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms) + // the transfer's speed is also zero until it has enough data to compute the EMA, so throw both + // repeated and zero values out + var now = DateTime.UtcNow; + + if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000)) { - Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); - }); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } + } finally { @@ -476,7 +491,7 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1); Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred); Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); - }); + }, cancellationToken); EventBus.Raise(new UploadFileCompleteEvent { @@ -500,7 +515,7 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); - }); + }, cancellationToken); throw; } @@ -516,7 +531,7 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); - }); + }, cancellationToken); throw; } @@ -532,7 +547,7 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); - }); + }, cancellationToken); throw; } @@ -548,17 +563,17 @@ namespace slskd.Transfers.Uploads Telemetry.Metrics.Update(() => { - if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState)) + if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Value > 0) { Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1); Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size); } - else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState)) + else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.Queued.Files.Value > 0) { Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); } - }); + }, cancellationToken); if (host != Program.LocalHostName) { @@ -596,8 +611,9 @@ namespace slskd.Transfers.Uploads /// /// The username of the requesting user. /// The local filename of the requested file. + /// The token to monitor for cancellation. /// The operation context. - public async Task EnqueueAsync(string username, string filename) + public async Task EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -752,7 +768,7 @@ namespace slskd.Transfers.Uploads { Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", id, task.Exception.Message); } - }); + }, cancellationToken); return transfer; } diff --git a/src/web/src/components/AppFooter.jsx b/src/web/src/components/AppFooter.jsx index 80c6de7d..261b5c11 100644 --- a/src/web/src/components/AppFooter.jsx +++ b/src/web/src/components/AppFooter.jsx @@ -7,7 +7,7 @@ const formatSpeed = (bytesPerSecond) => { return ' 0 B/s'; } - return `${formatBytes(bytesPerSecond, 1, 5, ' ')}/s`; + return `${formatBytes(bytesPerSecond, 1, 4, ' ')}/s`; }; const AppFooter = ({ -- 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/Telemetry') 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