diff options
Diffstat (limited to 'src')
23 files changed, 1358 insertions, 196 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2b9a1f93..475e4288 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -112,7 +112,7 @@ namespace slskd ISoulseekClient soulseekClient, FileService fileService, ConnectionWatchdog connectionWatchdog, - ITransferService transferService, + TransferService transferService, IBrowseTracker browseTracker, IRoomService roomService, IUserService userService, @@ -257,7 +257,7 @@ namespace slskd private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } private IManagedState<State> State { get; } - private ITransferService Transfers { get; init; } + private TransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } private EventBus EventBus { get; } diff --git a/src/slskd/Common/ExponentialMovingAverage.cs b/src/slskd/Common/ExponentialMovingAverage.cs index aaa6e5ea..6bc773cb 100644 --- a/src/slskd/Common/ExponentialMovingAverage.cs +++ b/src/slskd/Common/ExponentialMovingAverage.cs @@ -73,6 +73,16 @@ namespace slskd private Action<double> OnUpdate { get; } /// <summary> + /// Resets the value. + /// </summary> + public void Reset() + { + Value = 0; + Initialized = false; + OnUpdate?.Invoke(Value); + } + + /// <summary> /// Updates the average with a new value. /// </summary> /// <param name="value"></param> diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs index 9d1e8c75..6dabb7ac 100644 --- a/src/slskd/Core/Clock.cs +++ b/src/slskd/Core/Clock.cs @@ -45,9 +45,13 @@ namespace slskd { EveryMinuteTimer.Elapsed += (_, _) => Fire(EveryMinute); EveryThirtySecondsTimer.Elapsed += (_, _) => Fire(EveryThirtySeconds); + EveryFifteenSecondsTimer.Elapsed += (_, _) => Fire(EveryFifteenSeconds); EveryFiveMinutesTimer.Elapsed += (_, _) => Fire(EveryFiveMinutes); EveryThirtyMinutesTimer.Elapsed += (_, _) => Fire(EveryThirtyMinutes); EveryHourTimer.Elapsed += (_, _) => Fire(EveryHour); + EveryFiveSecondsTimer.Elapsed += (_, _) => Fire(EveryFiveSeconds); + EverySecondTimer.Elapsed += (_, _) => Fire(EverySecond); + EveryFiveHundredMillisecondsTimer.Elapsed += (_, _) => Fire(EveryFiveHundredMilliseconds); } /// <summary> @@ -71,6 +75,26 @@ namespace slskd public static event EventHandler<ClockEventArgs> EveryThirtySeconds; /// <summary> + /// Fires every 15 seconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFifteenSeconds; + + /// <summary> + /// Fires every 5 seconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFiveSeconds; + + /// <summary> + /// Fires every second. + /// </summary> + public static event EventHandler<ClockEventArgs> EverySecond; + + /// <summary> + /// Fires every 500 milliseconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryFiveHundredMilliseconds; + + /// <summary> /// Fires every 30 minutes. /// </summary> public static event EventHandler<ClockEventArgs> EveryThirtyMinutes; @@ -79,7 +103,11 @@ namespace slskd private static Timer EveryHourTimer { get; } = CreateTimer(interval: 1000 * 60 * 60); private static Timer EveryMinuteTimer { get; } = CreateTimer(interval: 1000 * 60); 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); /// <summary> /// Starts the clock. @@ -89,18 +117,26 @@ namespace slskd { EveryMinuteTimer.Enabled = true; EveryThirtySecondsTimer.Enabled = true; + EveryFifteenSecondsTimer.Enabled = true; EveryFiveMinutesTimer.Enabled = true; EveryThirtyMinutesTimer.Enabled = true; EveryHourTimer.Enabled = true; + EveryFiveSecondsTimer.Enabled = true; + EverySecondTimer.Enabled = true; + EveryFiveHundredMillisecondsTimer.Enabled = true; var firstRunArgs = new ClockEventArgs(firstRun: true); return Task.WhenAll( Task.Run(() => Fire(EveryMinute, firstRunArgs)), Task.Run(() => Fire(EveryThirtySeconds, firstRunArgs)), + Task.Run(() => Fire(EveryFifteenSeconds, firstRunArgs)), Task.Run(() => Fire(EveryFiveMinutes, firstRunArgs)), Task.Run(() => Fire(EveryThirtyMinutes, firstRunArgs)), - Task.Run(() => Fire(EveryHour, firstRunArgs))); + Task.Run(() => Fire(EveryHour, firstRunArgs)), + Task.Run(() => Fire(EveryFiveSeconds, firstRunArgs)), + Task.Run(() => Fire(EverySecond, firstRunArgs)), + Task.Run(() => Fire(EveryFiveHundredMilliseconds, firstRunArgs))); } /// <summary> @@ -110,9 +146,13 @@ namespace slskd { EveryMinuteTimer.Stop(); EveryThirtySecondsTimer.Stop(); + EveryFifteenSecondsTimer.Stop(); EveryFiveMinutesTimer.Stop(); EveryThirtyMinutesTimer.Stop(); + EveryFiveSecondsTimer.Stop(); EveryHourTimer.Stop(); + EverySecondTimer.Stop(); + EveryFiveHundredMillisecondsTimer.Stop(); } private static Timer CreateTimer(double interval) => new() { AutoReset = true, Interval = interval, Enabled = false }; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9a2914ea..0fc6b294 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; @@ -63,11 +64,12 @@ namespace slskd using Microsoft.Extensions.FileProviders.Physical; 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; @@ -627,6 +629,7 @@ namespace slskd _ = app.Services.GetService<ScriptService>(); _ = app.Services.GetService<WebhookService>(); _ = app.Services.GetService<VPNService>(); + _ = app.Services.GetService<TelemetryService>(); app.ConfigureAspDotNetPipeline(); @@ -757,6 +760,7 @@ namespace slskd services.AddSingleton<PrometheusService>(); services.AddSingleton<ReportsService>(); + services.AddSingleton<MetricsService>(); services.AddSingleton<TelemetryService>(); services.AddSingleton<VPNService>(); @@ -778,7 +782,7 @@ namespace slskd services.AddSingleton<IRoomService, RoomService>(); - services.AddSingleton<ITransferService, TransferService>(); + services.AddSingleton<TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); services.AddSingleton<IBatchService, BatchService>(); @@ -828,10 +832,7 @@ 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(); + services.ConfigureTelemetry(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); @@ -1114,6 +1115,7 @@ namespace slskd endpoints.MapHub<LogsHub>("/hub/logs"); endpoints.MapHub<SearchHub>("/hub/search"); endpoints.MapHub<RelayHub>("/hub/relay"); + endpoints.MapHub<MetricsHub>("/hub/metrics"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); @@ -1301,6 +1303,134 @@ namespace slskd }; } + 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 => sources.Any(s => instrument?.Meter?.Name is string name && s.IsMatch(name)); + }); + + /* + 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 => sources.Any(s => name is string n && s.IsMatch(n)); + }); + + /* + 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<DiskCollectorConfig>(cfg => + cfg.DriveTypes = new HashSet<DriveType> { DriveType.Fixed }); + + return services; + } + private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) { configurationFile = Path.GetFullPath(configurationFile); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 5c5f9d38..fef16573 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -228,6 +228,7 @@ namespace slskd.Relay if (disposing) { _ = HubConnection?.DisposeAsync(); + StartCancellationTokenSource?.Dispose(); } Disposed = true; diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 5920b7ac..7c93d437 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -392,7 +392,10 @@ namespace slskd.Shares } finally { + var cts = CancellationTokenSource; CancellationTokenSource = null; + cts?.Dispose(); + SyncRoot.Release(); } } diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs new file mode 100644 index 00000000..5dcd4ecc --- /dev/null +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -0,0 +1,60 @@ +// <copyright file="MetricsHub.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Telemetry; + +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; +using Serilog; + +public interface IMetricsHub +{ + Task Update(object metrics); +} + +[Authorize] +public class MetricsHub : Hub<IMetricsHub> +{ + public MetricsHub(MetricsService metricsService) + { + Metrics = metricsService; + } + + private static ILogger Log { get; } = Serilog.Log.ForContext<MetricsHub>(); + private MetricsService Metrics { get; } + + public override async Task OnConnectedAsync() + { + await Clients.Caller.Update(Metrics.Current()); + } +}
\ No newline at end of file diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33e16873..822f6aeb 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; /// <summary> @@ -45,6 +46,31 @@ using Prometheus; /// </remarks> public static class Metrics { + private static SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// <summary> + /// Updates metrics under a mutex to prevent mismatches and under/overruns. + /// </summary> + /// <remarks> + /// This method uses a <see cref="SemaphoreSlim"/> for synchronization and it is therefore safe to do async work + /// inside of <paramref name="work"/>, though it is discouraged for causing un-needed contention. + /// </remarks> + /// <param name="work">Updates to execute.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + public static void Update(Action work, CancellationToken cancellationToken = default) + { + SyncRoot.Wait(cancellationToken); + + try + { + work.Invoke(); + } + finally + { + SyncRoot.Release(); + } + } + /// <summary> /// Metrics related to search requests and responses. /// </summary> @@ -265,6 +291,296 @@ public static class Metrics } /// <summary> + /// Metrics related to transfers. + /// </summary> + public static class Transfers + { + /// <summary> + /// Metrics related to uploads. + /// </summary> + public static class Uploads + { + /// <summary> + /// Metrics related to in-progress uploads. + /// </summary> + public static class InProgress + { + /// <summary> + /// Gets a gauge representing the current number of unique users with in-progress uploads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current number of in-progress uploads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_in_progress_files_current", + help: "Current number of in-progress uploads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of in-progress uploads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress uploads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress uploads. + /// </summary> + 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"); + } + + /// <summary> + /// Metrics related to queued uploads. + /// </summary> + public static class Queued + { + /// <summary> + /// Gets a gauge representing the current number of unique users with queued uploads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_users_current", + help: "Current number of unique users with queued uploads"); + + /// <summary> + /// Gets a gauge representing the current number of queued uploads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_files_current", + help: "Current number of queued uploads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of queued uploads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_uploads_queued_bytes_current", + help: "Current total size, in bytes, of queued uploads"); + } + + /// <summary> + /// Metrics related to completed uploads. + /// </summary> + public static class Completed + { + /// <summary> + /// Gets a counter representing the total number of uploads that completed successfully. + /// </summary> + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_succeeded", + help: "Total number of uploads that completed successfully"); + + /// <summary> + /// Gets a counter representing the total number of bytes transferred by successfully completed uploads. + /// </summary> + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_bytes", + help: "Total number of bytes transferred by successfully completed uploads"); + + /// <summary> + /// Gets a counter representing the total number of uploads that failed. + /// </summary> + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_uploads_completed_failed", + help: "Total number of uploads that failed"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// </summary> + 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"); + + /// <summary> + /// Gets a histogram representing the the average speed of completed uploads, in bytes per second. + /// </summary> + 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 + ], + }); + } + } + + /// <summary> + /// Metrics related to downloads. + /// </summary> + public static class Downloads + { + /// <summary> + /// Metrics related to in-progress downloads. + /// </summary> + public static class InProgress + { + /// <summary> + /// Gets a gauge representing the current number of unique users with in-progress downloads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current number of in-progress downloads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_in_progress_files_current", + help: "Current number of in-progress downloads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of in-progress downloads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current total speed, in bytes per second, of in-progress downloads. + /// </summary> + 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"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of in-progress downloads. + /// </summary> + 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"); + } + + /// <summary> + /// Metrics related to queued downloads. + /// </summary> + public static class Queued + { + /// <summary> + /// Gets a gauge representing the current number of unique users with queued downloads. + /// </summary> + public static Gauge Users { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_users_current", + help: "Current number of unique users with queued downloads"); + + /// <summary> + /// Gets a gauge representing the current number of queued downloads. + /// </summary> + public static Gauge Files { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_files_current", + help: "Current number of queued downloads"); + + /// <summary> + /// Gets a gauge representing the current total size, in bytes, of queued downloads. + /// </summary> + public static Gauge Bytes { get; } = Prometheus.Metrics.CreateGauge( + name: "slskd_transfers_downloads_queued_bytes_current", + help: "Current total size, in bytes, of queued downloads"); + } + + /// <summary> + /// Metrics related to completed downloads. + /// </summary> + public static class Completed + { + /// <summary> + /// Gets a counter representing the total number of downloads that completed successfully. + /// </summary> + public static Counter Succeeded { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_succeeded", + help: "Total number of downloads that completed successfully"); + + /// <summary> + /// Gets a counter representing the total number of bytes transferred by successfully completed downloads. + /// </summary> + public static Counter Bytes { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_bytes", + help: "Total number of bytes transferred by successfully completed downloads"); + + /// <summary> + /// Gets a counter representing the total number of downloads that failed. + /// </summary> + public static Counter Failed { get; } = Prometheus.Metrics.CreateCounter( + name: "slskd_transfers_downloads_completed_failed", + help: "Total number of downloads that failed"); + + /// <summary> + /// Gets a gauge representing the current average speed, in bytes per second, of completed downloads. + /// </summary> + 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"); + + /// <summary> + /// Gets a histogram representing the the average speed of completed downloads, in bytes per second. + /// </summary> + 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 + ], + }); + } + } + } + + /// <summary> /// Metrics related to the distributed network. /// </summary> public static class DistributedNetwork diff --git a/src/slskd/Telemetry/MetricsService.cs b/src/slskd/Telemetry/MetricsService.cs new file mode 100644 index 00000000..1c69ef85 --- /dev/null +++ b/src/slskd/Telemetry/MetricsService.cs @@ -0,0 +1,96 @@ +// <copyright file="MetricsService.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Telemetry; + +using Serilog; + +/// <summary> +/// Metrics. +/// </summary> +public class MetricsService +{ + private ILogger Log { get; } = Serilog.Log.ForContext<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 74800126..5085d6ed 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -30,16 +30,32 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> +using Microsoft.AspNetCore.SignalR; + namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, ReportsService reportsService) + public TelemetryService( + PrometheusService prometheusService, + ReportsService reportsService, + MetricsService metricsService, + IHubContext<MetricsHub, IMetricsHub> metricsHub) { Prometheus = prometheusService; Reports = reportsService; + Metrics = metricsService; + + MetricsHub = metricsHub; + + Clock.EverySecond += (_, _) => + { + MetricsHub.Clients.All.Update(Metrics.Current()); + }; } public PrometheusService Prometheus { get; } public ReportsService Reports { get; } + public MetricsService Metrics { get; } + private IHubContext<MetricsHub, IMetricsHub> MetricsHub { get; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3191e3a8..147921ef 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -64,7 +64,7 @@ namespace slskd.Transfers.API /// <param name="userService"></param> /// <param name="transferService"></param> public TransfersController( - ITransferService transferService, + TransferService transferService, IUserService userService, IOptionsSnapshot<Options> optionsSnapshot) { @@ -74,7 +74,7 @@ namespace slskd.Transfers.API } private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); - private ITransferService Transfers { get; } + private TransferService Transfers { get; } private IUserService Users { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>(); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 7c794e55..a4d48279 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -208,6 +208,7 @@ namespace slskd.Transfers.Downloads EventBus = eventBus; Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// <summary> @@ -1091,6 +1092,57 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); } + protected virtual void EmitMetrics() + { + void EmitQueuedMetrics() + { + var queued = Client.Downloads.Where(u => u.State.HasFlag(TransferStates.Queued)); + + Telemetry.Metrics.Transfers.Downloads.Queued.Users + .Set(queued.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Downloads.Queued.Files + .Set(queued.Count()); + + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes + .Set(queued.Sum(q => q.Size)); + } + + void EmitInProgressMetrics() + { + var inProgress = Client.Downloads.Where(u => u.State == TransferStates.InProgress); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Users + .Set(inProgress.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Files + .Set(inProgress.Count()); + + Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes + .Set(inProgress.Sum(u => u.Size)); + + if (inProgress.Any()) + { + 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); + } + else + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Reset(); + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Reset(); + } + } + + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); + } + /// <summary> /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user. /// </summary> @@ -1132,6 +1184,9 @@ namespace slskd.Transfers.Downloads var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; var updateSyncRoot = new SemaphoreSlim(1, 1); + var stateHistory = new List<TransferStates>(); + DateTime lastReportedAverageSpeed = default; + try { using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); @@ -1172,6 +1227,27 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Queued | TransferStates.Locally; } + transfer = transfer.WithSoulseekTransfer(args.Transfer); + + Telemetry.Metrics.Update(() => + { + 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); + } + }); + + stateHistory.Add(transfer.State); + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } @@ -1204,6 +1280,21 @@ namespace slskd.Transfers.Downloads context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + + // 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.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } } finally { @@ -1307,6 +1398,29 @@ namespace slskd.Transfers.Downloads && ex is not TransferSizeMismatchException, onRetry: (attempts, delay) => { + // an attempt failed and we have decided that we're going to retry instead of letting it throw + // we *MAY* have incremented queued/in progress metrics as part of the previous attempt + var mostRecentQueuedOrInProgressState = stateHistory + .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s)); + + Telemetry.Metrics.Update(() => + { + 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); + 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); transfer.Attempts = attempts; @@ -1335,6 +1449,13 @@ namespace slskd.Transfers.Downloads // todo: broadcast to signalr hub SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + 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); + }, cancellationToken); + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); /* @@ -1431,6 +1552,11 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) @@ -1442,10 +1568,39 @@ namespace slskd.Transfers.Downloads // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } finally { + 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) + // 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)); + + Telemetry.Metrics.Update(() => + { + 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) && 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.Transfers.Downloads.Queued.Files.Dec(1); + Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size); + } + }, cancellationToken); + if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) { storedCancellationTokenSource?.Dispose(); diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 6079dcd2..6dd852a0 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -30,51 +30,34 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </copyright> -namespace slskd.Transfers -{ - using slskd.Transfers.Downloads; - using slskd.Transfers.Uploads; +namespace slskd.Transfers; + +using slskd.Transfers.Downloads; +using slskd.Transfers.Uploads; +/// <summary> +/// Manages transfers. +/// </summary> +public class TransferService +{ /// <summary> - /// Manages transfers. + /// Initializes a new instance of the <see cref="TransferService"/> class. /// </summary> - public interface ITransferService + public TransferService( + IUploadService uploadService = null, + IDownloadService downloadService = null) { - /// <summary> - /// Gets the upload service. - /// </summary> - IUploadService Uploads { get; } - - /// <summary> - /// Gets the download service. - /// </summary> - IDownloadService Downloads { get; } + Uploads = uploadService; + Downloads = downloadService; } /// <summary> - /// Manages transfers. + /// Gets the upload service. /// </summary> - public class TransferService : ITransferService - { - /// <summary> - /// Initializes a new instance of the <see cref="TransferService"/> class. - /// </summary> - public TransferService( - IUploadService uploadService = null, - IDownloadService downloadService = null) - { - Uploads = uploadService; - Downloads = downloadService; - } + public virtual IUploadService Uploads { get; init; } - /// <summary> - /// Gets the upload service. - /// </summary> - public IUploadService Uploads { get; init; } - - /// <summary> - /// Gets the download service. - /// </summary> - public IDownloadService Downloads { get; init; } - } + /// <summary> + /// Gets the download service. + /// </summary> + public virtual IDownloadService Downloads { get; init; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 0929d761..2dca0d9e 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -32,7 +32,7 @@ using Microsoft.Extensions.Options; -namespace slskd.Transfers +namespace slskd.Transfers.Uploads { using System; using System.Collections.Concurrent; @@ -136,12 +136,18 @@ namespace slskd.Transfers private ILogger Log { get; } = Serilog.Log.ForContext<UploadQueue>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private ConcurrentDictionary<string, List<Upload>> Uploads { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); + private ConcurrentDictionary<string, List<Upload>> UploadDictionary { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); private IUserService Users { get; } /// <summary> - /// Awaits the start of an upload. + /// Returns a <see cref="Task"/> that, when complete, signals the underlying Soulseek.NET logic that + /// the 'wait for a free slot' permissive has been obtained. When the <see cref="Process"/> method is + /// ready, it will complete the Task and the upload will start. /// </summary> + /// <remarks> + /// This is the mechanism we use to control the queue; the Task we return here is completed in the + /// <see cref="Process"/> method once we have determined that this transfer is next to go. + /// </remarks> /// <param name="username">The username of the remote user.</param> /// <param name="filename">The filename for which to await the start.</param> /// <returns>The operation context.</returns> @@ -151,7 +157,7 @@ namespace slskd.Transfers try { - if (!Uploads.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(username, out var list)) { throw new SlskdException($"No enqueued uploads for user {username}"); } @@ -209,7 +215,7 @@ namespace slskd.Transfers try { - if (!Uploads.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(username, out var list)) { throw new SlskdException($"No enqueued uploads for user {username}"); } @@ -234,10 +240,12 @@ namespace slskd.Transfers Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); } - if (!list.Any() && Uploads.TryRemove(username, out _)) + if (list.Count == 0 && UploadDictionary.TryRemove(username, out _)) { Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", username); } + + EmitMetrics(); } finally { @@ -259,7 +267,7 @@ namespace slskd.Transfers { var upload = new Upload() { Username = username, Filename = filename }; - Uploads.AddOrUpdate( + UploadDictionary.AddOrUpdate( key: username, addValue: new List<Upload>(new[] { upload }), updateValueFactory: (key, list) => @@ -268,6 +276,7 @@ namespace slskd.Transfers return list; }); + EmitMetrics(); Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); } finally @@ -305,7 +314,7 @@ namespace slskd.Transfers var groupRecord = Groups.GetValueOrDefault(groupName); // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the @@ -314,7 +323,7 @@ namespace slskd.Transfers if (groupRecord.Strategy == QueueStrategy.RoundRobin) { // find this user's uploads - if (!Uploads.TryGetValue(username, out var uploadsForUser)) + if (!UploadDictionary.TryGetValue(username, out var uploadsForUser)) { throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } @@ -393,7 +402,7 @@ namespace slskd.Transfers } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. @@ -501,7 +510,7 @@ namespace slskd.Transfers // flip the uploads dictionary so that it is keyed by group instead of user. wait until just before we process the // queue to do this, and fetch each user's group as we do, to allow users to move between groups at run time. we // delay "pinning" an upload to a group (via UsedSlots, below) for the same reason. - var readyUploadsByGroup = Uploads.Aggregate( + var readyUploadsByGroup = UploadDictionary.Aggregate( seed: new ConcurrentDictionary<string, List<Upload>>(), func: (groups, user) => { @@ -544,6 +553,9 @@ namespace slskd.Transfers // release the upload upload.TaskCompletionSource.SetResult(); + + EmitMetrics(); + Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); @@ -557,5 +569,14 @@ namespace slskd.Transfers SyncRoot.Release(); } } + + private void EmitMetrics() + { + 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 9bb09f66..5f98afac 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> - /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks> /// <param name="transfer"></param> void AddOrSupersede(Transfer transfer); @@ -78,20 +78,22 @@ namespace slskd.Transfers.Uploads /// </summary> /// <param name="username">The username of the requesting user.</param> /// <param name="filename">The local filename of the requested file.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> - Task<Transfer> EnqueueAsync(string username, string filename); + Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default); /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> /// <param name="transfer">The Transfer to upload.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception> /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception> - Task<Transfer> UploadAsync(Transfer transfer); + Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default); /// <summary> /// Finds a single upload matching the specified <paramref name="expression"/>. @@ -194,6 +196,8 @@ namespace slskd.Transfers.Uploads Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); + + Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// <summary> @@ -221,7 +225,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> - /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks> + /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks> /// <param name="transfer"></param> public void AddOrSupersede(Transfer transfer) { @@ -248,20 +252,23 @@ namespace slskd.Transfers.Uploads /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> /// <param name="transfer">The Transfer to upload.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception> /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception> - public async Task<Transfer> UploadAsync(Transfer transfer) + public async Task<Transfer> 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<TransferStates>(); + DateTime lastReportedAverageSpeed = default; var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; @@ -345,6 +352,25 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(args.Transfer); + Telemetry.Metrics.Update(() => + { + 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); + } + }, cancellationToken); + + stateHistory.Add(transfer.State); + // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, @@ -372,6 +398,22 @@ namespace slskd.Transfers.Uploads context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + + // 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.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); + }, cancellationToken); + + lastReportedAverageSpeed = now; + } + } finally { @@ -444,6 +486,13 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + 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); + }, cancellationToken); + EventBus.Raise(new UploadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, @@ -463,6 +512,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) @@ -474,6 +528,11 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } catch (Exception ex) @@ -485,10 +544,37 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Telemetry.Metrics.Update(() => + { + Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); + }, cancellationToken); + throw; } finally { + 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 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)); + + Telemetry.Metrics.Update(() => + { + 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) && 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) { try @@ -506,7 +592,9 @@ namespace slskd.Transfers.Uploads Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); - CancellationTokens.TryRemove(transfer.Id, out _); + CancellationTokens.TryRemove(transfer.Id, out var registeredCts); + registeredCts?.TryDispose(); + cts?.TryDispose(); // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious @@ -525,8 +613,9 @@ namespace slskd.Transfers.Uploads /// </summary> /// <param name="username">The username of the requesting user.</param> /// <param name="filename">The local filename of the requested file.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> /// <returns>The operation context.</returns> - public async Task<Transfer> EnqueueAsync(string username, string filename) + public async Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -681,7 +770,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; } @@ -940,6 +1029,57 @@ namespace slskd.Transfers.Uploads return stats ?? new UserUploadStatistics(); } + protected virtual void EmitMetrics() + { + void EmitQueuedMetrics() + { + var queued = Client.Uploads.Where(u => u.State.HasFlag(TransferStates.Queued)); + + Telemetry.Metrics.Transfers.Uploads.Queued.Users + .Set(queued.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Uploads.Queued.Files + .Set(queued.Count()); + + Telemetry.Metrics.Transfers.Uploads.Queued.Bytes + .Set(queued.Sum(q => q.Size)); + } + + void EmitInProgressMetrics() + { + var inProgress = Client.Uploads.Where(u => u.State == TransferStates.InProgress); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Users + .Set(inProgress.Select(u => u.Username).Distinct().Count()); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Files + .Set(inProgress.Count()); + + Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes + .Set(inProgress.Sum(u => u.Size)); + + if (inProgress.Any()) + { + 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); + } + else + { + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Reset(); + Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Reset(); + } + } + + Telemetry.Metrics.Update(() => + { + EmitQueuedMetrics(); + EmitInProgressMetrics(); + }); + } + private bool TryFail(Guid id, string exception, TransferStates state) { var t = Find(t => t.Id == id); diff --git a/src/web/package-lock.json b/src/web/package-lock.json index e64bc38d..191d1cca 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -28,6 +28,7 @@ }, "devDependencies": { "@babel/plugin-proposal-private-property-in-object": "^7.21.11", + "@babel/plugin-syntax-import-assertions": "^7.29.7", "@craco/craco": "^7.0.0", "@semantic-ui-react/craco-less": "^3.0.0", "@semantic-ui-react/css-patch": "^1.0.0", @@ -510,10 +511,11 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", - "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -1014,12 +1016,13 @@ } }, "node_modules/@babel/plugin-syntax-import-assertions": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.22.5.tgz", - "integrity": "sha512-rdV97N7KqsRzeNGoWUOK6yUsWarLjE5Su/Snk9IYPU9CwkWHs4t+rTGOvffTR8XGkJMTAdLfO0xVnXm8wugIJg==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.29.7.tgz", + "integrity": "sha512-/An1OCBN93thpBAGyfsK2pcf0jvju1SAtKkL2Ny++B5Sy6sqgzXDQH1cZxWbF96Wuk+bn41MDA9bLd4VVAw6rw==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" + "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { "node": ">=6.9.0" diff --git a/src/web/package.json b/src/web/package.json index 00491c52..8fe233f4 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@babel/plugin-proposal-private-property-in-object": "^7.21.11", + "@babel/plugin-syntax-import-assertions": "^7.29.7", "@craco/craco": "^7.0.0", "@semantic-ui-react/craco-less": "^3.0.0", "@semantic-ui-react/css-patch": "^1.0.0", diff --git a/src/web/src/components/App.css b/src/web/src/components/App.css index 054fe1c4..1e2000f9 100644 --- a/src/web/src/components/App.css +++ b/src/web/src/components/App.css @@ -123,6 +123,13 @@ body { .pushable > .pusher.app-content { min-height: calc(100% - 71px); background: var(--background-color); + display: flex; + flex-direction: column; +} + +.app-content-body { + flex: 1; + padding-bottom: 40px; /* footer */ } .navigation { @@ -264,4 +271,50 @@ body { .message { padding: 8px 12px 8px 12px !important; +} + +.footer.ui.menu { + position: fixed !important; + bottom: 0 !important; + left: 0 !important; + right: 0 !important; + z-index: 1000 !important; + margin: 0 !important; + border-radius: 0 !important; +} + +.footer-logo { + height: 18px; + width: 18px !important; + vertical-align: middle; +} + +.footer-version { + margin-left: 6px; + font-family: monospace; + font-size: 14px; + opacity: 0.7; + margin-top: 1px; +} + +.footer-license { + margin-left: 6px; + font-family: monospace; + font-size: 14px; + opacity: 0.5; + margin-top: 1px; +} + +.footer-stat-detail { + margin-left: 6px; + font-size: 14px; + opacity: 0.7; +} + +.footer-download, +.footer-upload { + white-space: pre; + font-family: monospace; + font-size: 14px; + margin-top: 1px; }
\ No newline at end of file diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 92fe925b..9839bf35 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -1,12 +1,16 @@ import 'react-toastify/dist/ReactToastify.css'; import './App.css'; import { urlBase } from '../config'; -import { createApplicationHubConnection } from '../lib/hubFactory'; +import { + createApplicationHubConnection, + createMetricsHubConnection, +} from '../lib/hubFactory'; import * as relayAPI from '../lib/relay'; import { connect, disconnect } from '../lib/server'; import * as session from '../lib/session'; import { isPassthroughEnabled } from '../lib/token'; import AppContext from './AppContext'; +import AppFooter from './AppFooter'; import Browse from './Browse/Browse'; import Chat from './Chat/Chat'; import LoginForm from './LoginForm'; @@ -40,6 +44,7 @@ const initialState = { pending: false, }, retriesExhausted: false, + transferMetrics: {}, }; const ModeSpecificConnectButton = ({ @@ -151,6 +156,7 @@ class App extends Component { super(props); this.state = initialState; + this.hubConnections = {}; } componentDidMount() { @@ -203,7 +209,19 @@ 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(); + + metricsHub.on('Update', (metrics) => { + this.setState({ transferMetrics: metrics }); + }); + + await this.hubConnections.metricsHub?.stop(); + this.hubConnections.metricsHub = metricsHub; + await metricsHub.start(); } const savedTheme = this.getSavedTheme(); @@ -260,6 +278,10 @@ class App extends Component { logout = () => { session.logout(); + + this.hubConnections?.appHub?.stop(); + this.hubConnections?.metricsHub?.stop(); + this.setState({ login: { ...initialState.login } }); }; @@ -280,6 +302,7 @@ class App extends Component { (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'), + transferMetrics = {}, } = this.state; const { connectionWatchdog = {}, @@ -522,124 +545,132 @@ class App extends Component { </Menu> </Sidebar> <Sidebar.Pusher className="app-content"> - <AppContext.Provider - // eslint-disable-next-line no-warning-comments - // TODO: needs useMemo, but class component. yolo for now. - // eslint-disable-next-line react/jsx-no-constructed-context-values - value={{ options: applicationOptions, state: applicationState }} - > - {isAgent ? ( - <Switch> - <Route - path={`${urlBase}/system/:tab?`} - render={(props) => - this.withTokenCheck( - <System - {...props} - options={applicationOptions} - state={applicationState} - />, - ) - } - /> - <Redirect - from="*" - to={`${urlBase}/system`} - /> - </Switch> - ) : ( - <Switch> - <Route - path={`${urlBase}/searches/:id?`} - render={(props) => - this.withTokenCheck( - <div className="view"> - <Searches - server={applicationState.server} + <div className="app-content-body"> + <AppContext.Provider + // eslint-disable-next-line no-warning-comments + // TODO: needs useMemo, but class component. yolo for now. + // eslint-disable-next-line react/jsx-no-constructed-context-values + value={{ options: applicationOptions, state: applicationState }} + > + {isAgent ? ( + <Switch> + <Route + path={`${urlBase}/system/:tab?`} + render={(props) => + this.withTokenCheck( + <System {...props} - /> - </div>, - ) - } - /> - <Route - path={`${urlBase}/browse`} - render={(props) => - this.withTokenCheck(<Browse {...props} />) - } - /> - <Route - path={`${urlBase}/users`} - render={(props) => - this.withTokenCheck(<Users {...props} />) - } - /> - <Route - path={`${urlBase}/chat`} - render={(props) => - this.withTokenCheck( - <Chat - {...props} - state={applicationState} - />, - ) - } - /> - <Route - path={`${urlBase}/rooms`} - render={(props) => - this.withTokenCheck(<Rooms {...props} />) - } - /> - <Route - path={`${urlBase}/uploads`} - render={(props) => - this.withTokenCheck( - <div className="view"> - <Transfers + options={applicationOptions} + state={applicationState} + />, + ) + } + /> + <Redirect + from="*" + to={`${urlBase}/system`} + /> + </Switch> + ) : ( + <Switch> + <Route + path={`${urlBase}/searches/:id?`} + render={(props) => + this.withTokenCheck( + <div className="view"> + <Searches + server={applicationState.server} + {...props} + /> + </div>, + ) + } + /> + <Route + path={`${urlBase}/browse`} + render={(props) => + this.withTokenCheck(<Browse {...props} />) + } + /> + <Route + path={`${urlBase}/users`} + render={(props) => + this.withTokenCheck(<Users {...props} />) + } + /> + <Route + path={`${urlBase}/chat`} + render={(props) => + this.withTokenCheck( + <Chat {...props} - direction="upload" - /> - </div>, - ) - } - /> - <Route - path={`${urlBase}/downloads`} - render={(props) => - this.withTokenCheck( - <div className="view"> - <Transfers + state={applicationState} + />, + ) + } + /> + <Route + path={`${urlBase}/rooms`} + render={(props) => + this.withTokenCheck(<Rooms {...props} />) + } + /> + <Route + path={`${urlBase}/uploads`} + render={(props) => + this.withTokenCheck( + <div className="view"> + <Transfers + {...props} + direction="upload" + /> + </div>, + ) + } + /> + <Route + path={`${urlBase}/downloads`} + render={(props) => + this.withTokenCheck( + <div className="view"> + <Transfers + {...props} + direction="download" + server={applicationState.server} + /> + </div>, + ) + } + /> + <Route + path={`${urlBase}/system/:tab?`} + render={(props) => + this.withTokenCheck( + <System {...props} - direction="download" - server={applicationState.server} - /> - </div>, - ) - } - /> - <Route - path={`${urlBase}/system/:tab?`} - render={(props) => - this.withTokenCheck( - <System - {...props} - options={applicationOptions} - state={applicationState} - theme={theme} - />, - ) - } - /> - <Redirect - from="*" - to={`${urlBase}/searches`} - /> - </Switch> - )} - </AppContext.Provider> + options={applicationOptions} + state={applicationState} + theme={theme} + />, + ) + } + /> + <Redirect + from="*" + to={`${urlBase}/searches`} + /> + </Switch> + )} + </AppContext.Provider> + </div> </Sidebar.Pusher> </Sidebar.Pushable> + <AppFooter + server={server} + transferMetrics={transferMetrics} + user={user} + version={version} + /> <ToastContainer autoClose={5_000} closeOnClick diff --git a/src/web/src/components/AppFooter.jsx b/src/web/src/components/AppFooter.jsx new file mode 100644 index 00000000..261b5c11 --- /dev/null +++ b/src/web/src/components/AppFooter.jsx @@ -0,0 +1,83 @@ +import { formatBytes } from '../lib/util'; +import React from 'react'; +import { Icon, Menu } from 'semantic-ui-react'; + +const formatSpeed = (bytesPerSecond) => { + if (!bytesPerSecond || bytesPerSecond < 1) { + return ' 0 B/s'; + } + + return `${formatBytes(bytesPerSecond, 1, 4, ' ')}/s`; +}; + +const AppFooter = ({ + server = {}, + transferMetrics = {}, + user = {}, + version = {}, +}) => { + const { isConnected } = server; + const { username } = user; + const { current } = version; + // const { downloads, uploads } = transferMetrics ?? {}; + const downloadSpeed = transferMetrics?.downloads?.inProgress?.averageSpeed; + const downloadActive = transferMetrics?.downloads?.inProgress?.files ?? 0; + const downloadQueued = transferMetrics?.downloads?.queued?.files ?? 0; + const uploadSpeed = transferMetrics?.uploads?.inProgress?.averageSpeed; + const uploadActive = transferMetrics?.uploads?.inProgress?.files ?? 0; + const uploadQueued = transferMetrics?.uploads?.queued?.files ?? 0; + + return ( + <Menu + className="footer" + inverted + > + <Menu.Item> + <Icon + color={isConnected ? 'green' : 'red'} + name="circle" + /> + {isConnected ? username : 'Disconnected'} + </Menu.Item> + <Menu.Item> + <Icon + color="blue" + name="arrow down" + /> + <span className="footer-download">{formatSpeed(downloadSpeed)}</span> + <span className="footer-stat-detail"> + {downloadActive} active · {downloadQueued} queued + </span> + </Menu.Item> + <Menu.Item> + <Icon + color="orange" + name="arrow up" + /> + <span className="footer-upload">{formatSpeed(uploadSpeed)}</span> + <span className="footer-stat-detail"> + {uploadActive} active · {uploadQueued} queued + </span> + </Menu.Item> + <Menu.Menu position="right"> + <Menu.Item + as="a" + href="https://github.com/slskd/slskd" + rel="noreferrer" + target="_blank" + > + <img + alt="" + className="footer-logo" + src="/favicon.ico" + /> + slskd + {current && <span className="footer-version">{current}</span>} + <span className="footer-license">AGPLv3</span> + </Menu.Item> + </Menu.Menu> + </Menu> + ); +}; + +export default AppFooter; diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js index d5264e03..3b5e36f7 100644 --- a/src/web/src/lib/hubFactory.js +++ b/src/web/src/lib/hubFactory.js @@ -27,3 +27,6 @@ export const createLogsHubConnection = () => export const createSearchHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/search` }); + +export const createMetricsHubConnection = () => + createHubConnection({ url: `${hubBaseUrl}/metrics` }); diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index 755546de..caced7ac 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -19,8 +19,13 @@ export const formatBytesAsUnit = (bytes, unit, decimals = 2) => { return Number.parseFloat((bytes / k ** sizes[unit]).toFixed(dm)); }; -export const formatBytes = (bytes, decimals = 2) => { - if (bytes === 0) return '0 B'; +export const formatBytes = ( + bytes, + decimals = 2, + padding = 0, + paddingCharacter = ' ', +) => { + if (bytes === 0 || bytes < 1) return '0 B'; const k = 1_024; const dm = decimals < 0 ? 0 : decimals; @@ -28,9 +33,10 @@ export const formatBytes = (bytes, decimals = 2) => { const index = Math.floor(Math.log(bytes) / Math.log(k)); - return ( - Number.parseFloat((bytes / k ** index).toFixed(dm)) + ' ' + sizes[index] - ); + const number = Number.parseFloat((bytes / k ** index).toFixed(dm)); + const padded = number.toString().padStart(padding, paddingCharacter); + + return padded + ' ' + sizes[index]; }; export const formatDate = (date) => { diff --git a/src/web/src/lib/util.test.js b/src/web/src/lib/util.test.js index 9bf79fab..0113a290 100644 --- a/src/web/src/lib/util.test.js +++ b/src/web/src/lib/util.test.js @@ -5,3 +5,14 @@ describe('formatBytesAsUnit', () => { expect(utils.formatBytesAsUnit(1_234_567, 'MB', 2)).toBe(1.18); }); }); + +describe('formatBytes', () => { + it('returns 0 B for values under one byte', () => { + expect(utils.formatBytes(0.5)).toBe('0 B'); + }); + + it('formats byte values for one and above', () => { + expect(utils.formatBytes(1)).toBe('1 B'); + expect(utils.formatBytes(1_024)).toBe('1 KB'); + }); +}); |
