aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-07 19:26:08 -0600
committerGitHub <noreply@github.com>2025-12-07 19:26:08 -0600
commitae7256b4d6ac9a00600c07af75b3097b4d4f4cbf (patch)
tree2d47fd53fb9951be663e71b1a3071d401dea6683 /src
parenta73633f5fc421b4f3f14536867aa2f24914cd4c4 (diff)
parent5e5126028ae7cf9a9d4ad87bc24033af69ec8e8e (diff)
downloadslskd-ae7256b4d6ac9a00600c07af75b3097b4d4f4cbf.tar.gz
Merge branch 'master' into add-rev-proxy-instructions
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs1
-rw-r--r--src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs100
-rw-r--r--src/slskd/Core/Data/Databases.cs2
-rw-r--r--src/slskd/Core/Data/SqlitePragmaInterceptor.cs55
-rw-r--r--src/slskd/Core/Options.cs24
-rw-r--r--src/slskd/Events/EventsDbContext.cs1
-rw-r--r--src/slskd/Events/Types/Events.cs1
-rw-r--r--src/slskd/Messaging/MessagingDbContext.cs1
-rw-r--r--src/slskd/Program.cs75
-rw-r--r--src/slskd/Search/SearchDbContext.cs1
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs4
-rw-r--r--src/slskd/Telemetry/API/MetricsController.cs (renamed from src/slskd/Telemetry/API/TelemetryController.cs)82
-rw-r--r--src/slskd/Telemetry/API/ReportsController.cs557
-rw-r--r--src/slskd/Telemetry/Metrics.cs242
-rw-r--r--src/slskd/Telemetry/PrometheusService.cs27
-rw-r--r--src/slskd/Telemetry/ReportsService.cs542
-rw-r--r--src/slskd/Telemetry/TelemetryService.cs8
-rw-r--r--src/slskd/Telemetry/Types/DirectoryDetail.cs23
-rw-r--r--src/slskd/Telemetry/Types/LeaderboardSorting.cs25
-rw-r--r--src/slskd/Telemetry/Types/PrometheusMetric.cs4
-rw-r--r--src/slskd/Telemetry/Types/SortOrder.cs24
-rw-r--r--src/slskd/Telemetry/Types/TransferExceptionDetail.cs39
-rw-r--r--src/slskd/Telemetry/Types/TransferExceptionSummary.cs25
-rw-r--r--src/slskd/Telemetry/Types/TransferSummary.cs29
-rw-r--r--src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs36
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs7
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs52
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs1
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs132
-rw-r--r--src/slskd/slskd.csproj5
-rw-r--r--src/web/package-lock.json76
-rw-r--r--src/web/package.json2
-rw-r--r--src/web/src/components/Browse/Browse.jsx2
-rw-r--r--src/web/src/components/Rooms/RoomJoinModal.jsx4
-rw-r--r--src/web/src/components/Search/Response.jsx4
-rw-r--r--src/web/src/components/System/System.css4
36 files changed, 1963 insertions, 254 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index c1e09d42..1a18790f 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -47,6 +47,7 @@ namespace slskd
using slskd.Relay;
using slskd.Search;
using slskd.Shares;
+ using slskd.Telemetry;
using slskd.Transfers;
using slskd.Users;
using Soulseek;
diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
new file mode 100644
index 00000000..db5c4baa
--- /dev/null
+++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
@@ -0,0 +1,100 @@
+// <copyright file="ContentNegotiationOperationFilter.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd;
+
+using System.Linq;
+using System.Reflection;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Formatters;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+
+/// <summary>
+/// OpenAPI operation filter that properly handles content negotiation with different response schemas.
+/// </summary>
+public class ContentNegotiationOperationFilter : IOperationFilter
+{
+ public void Apply(OpenApiOperation operation, OperationFilterContext context)
+ {
+ // check to see if the current operation is decorated with [Produces], which is what enables content negotiation
+ var producesAttribute = context.MethodInfo
+ .GetCustomAttributes(typeof(ProducesAttribute), false)
+ .Cast<ProducesAttribute>()
+ .FirstOrDefault();
+
+ if (producesAttribute == null || producesAttribute.ContentTypes.Count == 0)
+ {
+ return;
+ }
+
+ // next, get all of the [ProducesResponseType] attributes, if any
+ var producesResponseTypeAttributes = context.MethodInfo
+ .GetCustomAttributes(typeof(ProducesResponseTypeAttribute), false)
+ .Cast<ProducesResponseTypeAttribute>()
+ .ToList();
+
+ if (producesResponseTypeAttributes.Count == 0)
+ {
+ return;
+ }
+
+ // map over the list of status codes; we need to (attempt to) perform this mapping for each status code and each
+ // content type listed in [Produces]
+ foreach (var statusCodeGroup in producesResponseTypeAttributes.GroupBy(x => x.StatusCode))
+ {
+ foreach (var contentType in producesAttribute.ContentTypes)
+ {
+ // find the first [ProducesResponseType] that contains this content type in its list of content types
+ var attribute = statusCodeGroup.FirstOrDefault(x => GetContentTypes(x).Contains(contentType));
+
+ if (attribute is not null)
+ {
+ var response = operation.Responses[statusCodeGroup.Key.ToString()];
+ response.Content[contentType] = new OpenApiMediaType
+ {
+ Schema = context.SchemaGenerator.GenerateSchema(attribute.Type, context.SchemaRepository),
+ };
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Extracts the value of the _contentTypes field of <see cref="ProducesResponseTypeAttribute"/>.
+ ///
+ /// This is necessary because Microsoft didn't see fit to bless us with the ability to retrieve the content types
+ /// we specifify along with our [ProducesResponseType] attributes.
+ ///
+ /// It will most likely break at some point.
+ /// </summary>
+ /// <param name="attribute">The attribute from which to extract the _contentTypes field.</param>
+ /// <returns>The value of the extracted field.</returns>
+ private MediaTypeCollection GetContentTypes(ProducesResponseTypeAttribute attribute)
+ {
+ var contentTypesField = typeof(ProducesResponseTypeAttribute).GetField("_contentTypes", BindingFlags.NonPublic | BindingFlags.Instance);
+
+ MediaTypeCollection value = (MediaTypeCollection)contentTypesField.GetValue(attribute);
+
+ if (value is null)
+ {
+ return [];
+ }
+
+ return value;
+ }
+}
diff --git a/src/slskd/Core/Data/Databases.cs b/src/slskd/Core/Data/Databases.cs
index f118ad2a..a5d51ea6 100644
--- a/src/slskd/Core/Data/Databases.cs
+++ b/src/slskd/Core/Data/Databases.cs
@@ -15,6 +15,8 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+namespace slskd;
+
/// <summary>
/// A primitive type for Database names and a static value for each of them. And a list.
/// </summary>
diff --git a/src/slskd/Core/Data/SqlitePragmaInterceptor.cs b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs
new file mode 100644
index 00000000..b32982b1
--- /dev/null
+++ b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs
@@ -0,0 +1,55 @@
+// <copyright file="SqlitePragmaInterceptor.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd
+{
+ using System.Data.Common;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using Microsoft.Data.Sqlite;
+ using Microsoft.EntityFrameworkCore.Diagnostics;
+
+ /// <summary>
+ /// Intercepts SQLite database connections to set PRAGMAs immediately after opening.
+ /// </summary>
+ public class SqliteConnectionOpenedInterceptor : DbConnectionInterceptor
+ {
+ public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData)
+ {
+ if (connection is SqliteConnection)
+ {
+ using var cmd = connection.CreateCommand();
+ cmd.CommandText = "PRAGMA synchronous=1;";
+ cmd.ExecuteNonQuery();
+ }
+
+ base.ConnectionOpened(connection, eventData);
+ }
+
+ public override async Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData eventData, CancellationToken cancellationToken = default)
+ {
+ if (connection is SqliteConnection)
+ {
+ using var cmd = connection.CreateCommand();
+ cmd.CommandText = "PRAGMA synchronous=1;";
+ await cmd.ExecuteNonQueryAsync(cancellationToken);
+ }
+
+ await base.ConnectionOpenedAsync(connection, eventData, cancellationToken);
+ }
+ }
+}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 38416ca2..76dcd45c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -418,6 +418,15 @@ namespace slskd
public bool LogSQL { get; init; } = false;
/// <summary>
+ /// Gets a value indicating whether to log unobserved Exceptions.
+ /// </summary>
+ [Argument(default, "log-unobserved-exceptions")]
+ [EnvironmentVariable("LOG_UNOBSERVED_EXCEPTIONS")]
+ [Description("log unobserved exceptions (caution: verbose)")]
+ [RequiresRestart]
+ public bool LogUnobservedExceptions { get; init; } = false;
+
+ /// <summary>
/// Gets a value indicating whether the application should run in experimental mode.
/// </summary>
[Argument(default, "experimental")]
@@ -461,6 +470,14 @@ namespace slskd
[EnvironmentVariable("OPTIMISTIC_RELAY_FILE_INFO")]
[Description("use uploaded relay shares as source of truth for file existence and size")]
public bool OptimisticRelayFileInfo { get; init; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether SQLite pooling should be disabled.
+ /// </summary>
+ [Argument(default, "no-sqlite-pooling")]
+ [EnvironmentVariable("NO_SQLITE_POOLING")]
+ [Description("disable SQLite pooling")]
+ public bool NoSqlitePooling { get; init; } = false;
}
/// <summary>
@@ -1235,6 +1252,12 @@ namespace slskd
return results;
}
+ if (string.IsNullOrWhiteSpace(File))
+ {
+ results.Add(new ValidationResult("The Enabled field is true, but no File has been specified."));
+ return results;
+ }
+
// loading/validating the entire list will be costly on low spec systems
// just make sure that we can detect a valid format and leave it at that
// if there's a problem with any of the entries, the load will fail and
@@ -1821,7 +1844,6 @@ namespace slskd
[Argument(default, "http-socket")]
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
- [FileDoesNotExist]
[AbsoluteFilePath]
[RequiresRestart]
public string Socket { get; init; }
diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs
index a86f5d1c..8b45a803 100644
--- a/src/slskd/Events/EventsDbContext.cs
+++ b/src/slskd/Events/EventsDbContext.cs
@@ -25,7 +25,6 @@ public class EventsDbContext : DbContext
public EventsDbContext(DbContextOptions<EventsDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<EventRecord> Events { get; set; }
diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs
index 6e99b800..577e41e3 100644
--- a/src/slskd/Events/Types/Events.cs
+++ b/src/slskd/Events/Types/Events.cs
@@ -28,6 +28,7 @@ public enum EventType
DownloadFileComplete = 2,
DownloadDirectoryComplete = 3,
UploadFileComplete = 4,
+
// UploadDirectoryComplete = 5,
PrivateMessageReceived = 6,
RoomMessageReceived = 7,
diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs
index 5acb94ae..c6352c6e 100644
--- a/src/slskd/Messaging/MessagingDbContext.cs
+++ b/src/slskd/Messaging/MessagingDbContext.cs
@@ -25,7 +25,6 @@ namespace slskd.Messaging
public MessagingDbContext(DbContextOptions<MessagingDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Conversation> Conversations { get; set; }
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index bf0428d7..aa320961 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -23,8 +23,6 @@ namespace slskd
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
- using System.Diagnostics;
-
using System.IO;
using System.Linq;
using System.Net;
@@ -70,6 +68,7 @@ namespace slskd
using slskd.Search;
using slskd.Search.API;
using slskd.Shares;
+ using slskd.Telemetry;
using slskd.Transfers;
using slskd.Transfers.Downloads;
using slskd.Transfers.Uploads;
@@ -91,6 +90,11 @@ namespace slskd
public static readonly string AppName = "slskd";
/// <summary>
+ /// The DateTime of the 'genesis' of the application (the initial commit).
+ /// </summary>
+ public static readonly DateTime GenesisDateTime = new(2020, 12, 30, 6, 22, 0, DateTimeKind.Utc);
+
+ /// <summary>
/// The name of the local share host.
/// </summary>
public static readonly string LocalHostName = "local";
@@ -610,9 +614,11 @@ namespace slskd
var connectionStringDictionary = new ConnectionStringDictionary(Database.List
.Select(database =>
{
+ var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing
+
var connStr = OptionsAtStartup.Flags.Volatile
- ? $"Data Source=file:{database}?mode=memory;Cache=shared;Pooling=True;"
- : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache=shared;Pooling=True;";
+ ? $"Data Source=file:{database}?mode=memory;Pooling={pooling};"
+ : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Pooling={pooling}";
return new KeyValuePair<Database, ConnectionString>(database, connStr);
})
@@ -637,8 +643,9 @@ namespace slskd
services.AddSingleton<EventService>();
services.AddSingleton<EventBus>();
- services.AddSingleton<TelemetryService>();
services.AddSingleton<PrometheusService>();
+ services.AddSingleton<ReportsService>();
+ services.AddSingleton<TelemetryService>();
services.AddSingleton<ScriptService>();
services.AddSingleton<WebhookService>();
@@ -901,6 +908,9 @@ namespace slskd
},
});
+ // allow endpoints marked with multiple content types in [Produces] to generate properly
+ options.OperationFilter<ContentNegotiationOperationFilter>();
+
if (IOFile.Exists(XmlDocumentationFile))
{
options.IncludeXmlComments(XmlDocumentationFile);
@@ -1140,12 +1150,15 @@ namespace slskd
}))
.CreateLogger();
- // // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process.
- // TaskScheduler.UnobservedTaskException += (sender, e) =>
- // {
- // Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message);
- // e.SetObserved();
- // };
+ if (OptionsAtStartup.Flags.LogUnobservedExceptions)
+ {
+ // log Exceptions raised on fired-and-forgotten tasks, which adds very little value but might help debug someday
+ TaskScheduler.UnobservedTaskException += (sender, e) =>
+ {
+ Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message);
+ e.SetObserved();
+ };
+ }
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
@@ -1206,6 +1219,7 @@ namespace slskd
services.AddDbContextFactory<T>(options =>
{
options.UseSqlite(connectionString);
+ options.AddInterceptors(new SqliteConnectionOpenedInterceptor());
if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL)
{
@@ -1213,11 +1227,50 @@ namespace slskd
}
});
+ /*
+ instantiate the DbContext and make sure it is created
+ */
using var ctx = services
.BuildServiceProvider()
.GetRequiredService<IDbContextFactory<T>>()
.CreateDbContext();
+ Log.Debug("Ensuring {Contex} is created", typeof(T).Name);
+ ctx.Database.EnsureCreated();
+
+ /*
+ set (and validate) our desired PRAGMAs
+
+ synchronous mode is also set upon every connection via SqliteConnectionOpenedInterceptor.
+ */
+ ctx.Database.OpenConnection();
+ var conn = ctx.Database.GetDbConnection();
+
+ Log.Debug("Setting PRAGMAs for {Contex}", typeof(T).Name);
+ using var initCommand = conn.CreateCommand();
+ initCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=1; PRAGMA optimize;";
+ initCommand.ExecuteNonQuery();
+
+ using var journalCmd = conn.CreateCommand();
+ journalCmd.CommandText = "PRAGMA journal_mode;";
+ var journalMode = journalCmd.ExecuteScalar()?.ToString();
+
+ if (!journalMode.Equals("WAL", StringComparison.OrdinalIgnoreCase))
+ {
+ Log.Warning("Failed to set database {Type} journal_mode PRAGMA to WAL; performance may be reduced", typeof(T).Name);
+ }
+
+ using var syncCmd = conn.CreateCommand();
+ syncCmd.CommandText = "PRAGMA synchronous;";
+ var sync = syncCmd.ExecuteScalar()?.ToString();
+
+ if (!sync.Equals("1", StringComparison.OrdinalIgnoreCase))
+ {
+ Log.Warning("Failed to set database {Type} synchronous PRAGMA to 1; performance may be reduced", typeof(T).Name);
+ }
+
+ Log.Debug("PRAGMAs for {Context}: journal_mode={JournalMode}, synchronous={Synchronous}", typeof(T).Name, journalMode, sync);
+
return services;
}
catch (Exception ex)
diff --git a/src/slskd/Search/SearchDbContext.cs b/src/slskd/Search/SearchDbContext.cs
index bc6ee147..1d710e42 100644
--- a/src/slskd/Search/SearchDbContext.cs
+++ b/src/slskd/Search/SearchDbContext.cs
@@ -25,7 +25,6 @@ namespace slskd.Search
public SearchDbContext(DbContextOptions<SearchDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Search> Searches { get; set; }
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index f457adba..711bb21e 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -157,7 +157,9 @@ namespace slskd.Shares
{
using var conn = GetConnection();
- conn.ExecuteNonQuery("PRAGMA journal_mode=WAL");
+ // warning: with synchronous=0, an operating system crash can leave the database corrupted.
+ // if this occurs we should generate a new one, so this is _probably_ ok
+ conn.ExecuteNonQuery("PRAGMA journal_mode=WAL; PRAGMA synchronous=0;");
if (discardExisting)
{
diff --git a/src/slskd/Telemetry/API/TelemetryController.cs b/src/slskd/Telemetry/API/MetricsController.cs
index 2207ac8c..3ed7c1e2 100644
--- a/src/slskd/Telemetry/API/TelemetryController.cs
+++ b/src/slskd/Telemetry/API/MetricsController.cs
@@ -1,4 +1,4 @@
-// <copyright file="TelemetryController.cs" company="slskd Team">
+// <copyright file="MetricsController.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -23,30 +23,33 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
+using Serilog;
/// <summary>
/// Telemetry.
/// </summary>
-[Route("api/v{version:apiVersion}/[controller]")]
+[Route("api/v{version:apiVersion}/telemetry/[controller]")]
+[Tags("Telemetry")]
[ApiVersion("0")]
[ApiController]
[Produces("application/json")]
-public class TelemetryController : ControllerBase
+public class MetricsController : ControllerBase
{
/// <summary>
- /// Initializes a new instance of the <see cref="TelemetryController"/> class.
+ /// Initializes a new instance of the <see cref="MetricsController"/> class.
/// </summary>
- /// <param name="telemetryService"></param>
- public TelemetryController(TelemetryService telemetryService)
+ public MetricsController(TelemetryService telemetryService)
{
Telemetry = telemetryService;
}
private TelemetryService Telemetry { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<MetricsController>();
/// <summary>
- /// KPIs for the app, based on the Prometheus dashboard
+ /// Gets KPIs for the app, based on the Prometheus dashboard
/// * process_Working_set_bytes = total memory used
/// * dotnet_total_memory_bytes = sum of all managed memory
/// * process_cpu_seconds_total = total cpu time spent (not a great measure)
@@ -57,10 +60,10 @@ public class TelemetryController : ControllerBase
/// * node_filesystem_avail_bytes = how much space is left on the system
/// * node_network = info about network adapters on the system
/// Other
- /// * process_start_time_seconds = unix timestamp of start time
+ /// * process_start_time_seconds = unix timestamp of start time.
/// </summary>
- private List<Regex> KpiRegexes { get; } = new List<Regex>
- {
+ private List<Regex> KpiRegexes { get; } =
+ [
new Regex("slskd_.*", RegexOptions.Compiled),
new Regex("node_(?!cpu)", RegexOptions.Compiled),
new Regex("process_.*", RegexOptions.Compiled),
@@ -68,36 +71,65 @@ public class TelemetryController : ControllerBase
new Regex("system_runtime_[cpu_usage|working_set|alloc_total]", RegexOptions.Compiled),
new Regex("system_net_sockets.*", RegexOptions.Compiled),
new Regex("microsoft_aspnetcore_server_kestrel_[current|total]_connections", RegexOptions.Compiled),
- };
+ ];
/// <summary>
- /// Gets application metrics.
+ /// Gets all application metrics.
/// </summary>
- /// <returns></returns>
- [HttpGet("metrics")]
+ /// <remarks>
+ /// If the 'Accept' header is set to 'text/plain', the response is in Prometheus format. Otherwise if 'application/json' is set,
+ /// the metrics are formatted into a dictionary.
+ /// </remarks>
+ /// <returns>A flat Prometheus-formatted list of all metrics given text/plain, a dictionary keyed by metric name otherwise.</returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("")]
[Authorize(Policy = AuthPolicy.Any)]
[Produces("text/plain", "application/json")]
+ [ProducesResponseType(typeof(string), 200, "text/plain")]
+ [ProducesResponseType(typeof(Dictionary<string, PrometheusMetric>), 200, "application/json")]
+ [ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> Get()
{
- if (Request.Headers.Accept.ToString().Equals("application/json", StringComparison.OrdinalIgnoreCase))
+ try
{
- Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject();
- return Ok(dict);
- }
+ if (Request.Headers.Accept.ToString().Equals("application/json", StringComparison.OrdinalIgnoreCase))
+ {
+ Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject();
+ return Ok(dict);
+ }
- var response = await Telemetry.Prometheus.GetMetricsAsString();
- return Content(response, "text/plain");
+ var response = await Telemetry.Prometheus.GetMetricsAsString();
+ return Content(response, "text/plain");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching metrics: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
+ }
}
/// <summary>
- /// Gets gets key performance indicators for the application.
+ /// Gets gets key performance indicators (KPIs) for the application.
/// </summary>
- /// <returns></returns>
- [HttpGet("metrics/kpi")]
+ /// <returns>A dictionary keyed by metric name.</returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("kpis")]
[Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<string, PrometheusMetric>), 200)]
+ [ProducesResponseType(typeof(string), 500)]
public async Task<IActionResult> GetKpis()
{
- Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject(include: KpiRegexes);
- return Ok(dict);
+ try
+ {
+ Dictionary<string, PrometheusMetric> dict = await Telemetry.Prometheus.GetMetricsAsObject(include: KpiRegexes);
+ return Ok(dict);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching KPIs: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
+ }
}
}
diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs
new file mode 100644
index 00000000..da088800
--- /dev/null
+++ b/src/slskd/Telemetry/API/ReportsController.cs
@@ -0,0 +1,557 @@
+// <copyright file="ReportsController.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Asp.Versioning;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Serilog;
+using Soulseek;
+
+/// <summary>
+/// Reports.
+/// </summary>
+[Route("api/v{version:apiVersion}/telemetry/[controller]")]
+[Tags("Telemetry")]
+[ApiVersion("0")]
+[ApiController]
+[Produces("application/json")]
+public class ReportsController : ControllerBase
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReportsController"/> class.
+ /// </summary>
+ public ReportsController(TelemetryService telemetryService)
+ {
+ Telemetry = telemetryService;
+ }
+
+ private TelemetryService Telemetry { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ReportsController>();
+
+ /// <summary>
+ /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="direction">An optional direction (Upload, Download) by which to filter records.</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/summary")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferSummary(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string direction = null,
+ [FromQuery] string username = null)
+ {
+ var now = DateTime.UtcNow;
+
+ start ??= now.AddDays(-7);
+ end ??= now;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ TransferDirection? transferDirection = null;
+
+ if (!string.IsNullOrWhiteSpace(direction))
+ {
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ transferDirection = parsedDirection;
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferSummary(
+ start: start.Value,
+ end: end,
+ direction: transferDirection,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer summary over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals
+ /// and grouped by direction and final state.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="interval">The interval, in minutes (default: 60).</param>
+ /// <param name="direction">An optional direction (Upload, Download) by which to filter records.</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/histogram")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferHistogram(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] int interval = 60,
+ [FromQuery] string direction = null,
+ [FromQuery] string username = null)
+ {
+ var now = DateTime.UtcNow;
+
+ start ??= now.AddDays(-7);
+ end ??= now;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ // clamp the start time to the earliest reasonable date to avoid returning a ton of empty intervals
+ // and introducing performance issues client side
+ if (start < Program.GenesisDateTime)
+ {
+ Log.Warning("A start time prior to the genesis date of the application was supplied; the start time has been adjusted to the genesis time {Genesis}", Program.GenesisDateTime);
+ start = Program.GenesisDateTime;
+ }
+
+ if (interval < 5)
+ {
+ return BadRequest("Interval must be greater than or equal to 5");
+ }
+
+ var intervalTimeSpan = TimeSpan.FromMinutes(interval);
+
+ TransferDirection? transferDirection = null;
+
+ if (!string.IsNullOrWhiteSpace(direction))
+ {
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ transferDirection = parsedDirection;
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferHistogram(
+ start: start.Value,
+ end: end.Value,
+ interval: intervalTimeSpan,
+ direction: transferDirection,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer histogram over {Start}-{End}/{Interval}: {Message}", start, end, interval, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N user summaries by count, total bytes, or average speed.
+ /// </summary>
+ /// <param name="direction">The direction (Upload, Download).</param>
+ /// <param name="start">The start time of the window (default: 12/30/2025).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="sortBy">The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count).</param>
+ /// <param name="sortOrder">The sort order (ASC, DESC. Default: DESC).</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/leaderboard")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferLeaderboard(
+ [FromQuery] string direction,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string sortBy = "Count",
+ [FromQuery] string sortOrder = "DESC",
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.UtcNow;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (!Enum.TryParse<LeaderboardSortBy>(sortBy, out var parsedSortBy))
+ {
+ return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}");
+ }
+
+ if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder))
+ {
+ return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferLeaderboard(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end,
+ sortBy: parsedSortBy,
+ sortOrder: parsedSortOrder,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer leaderboard over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets detailed transfer activity for the specified user.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="start">The start time of the summary window (default: 7 days ago).</param>
+ /// <param name="end">The end time of the summary window (default: now).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/users/{username}")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(Dictionary<TransferDirection, UserDirectionTransferSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetUserDetails(
+ [FromRoute] string username,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null)
+ {
+ if (string.IsNullOrWhiteSpace(username))
+ {
+ return BadRequest("Username is required");
+ }
+
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.UtcNow;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ static UserDirectionTransferStatistics GetStatistics(Dictionary<TransferStates, TransferSummary> summary)
+ {
+ var totalTransfers = summary.Values.Sum(x => x.Count);
+ var successful = summary.Where(x => x.Key == TransferStates.Succeeded).Sum(x => x.Value.Count);
+ var errored = summary.Where(x => new[] { TransferStates.Errored, TransferStates.TimedOut, TransferStates.Rejected, TransferStates.Aborted }.Contains(x.Key)).Sum(x => x.Value.Count);
+ var cancelled = summary.Where(x => x.Key == TransferStates.Cancelled).Sum(x => x.Value.Count);
+
+ return new UserDirectionTransferStatistics
+ {
+ Total = totalTransfers,
+ Successful = successful,
+ Errored = errored,
+ Cancelled = cancelled,
+ };
+ }
+
+ try
+ {
+ var results = new Dictionary<TransferDirection, UserDirectionTransferSummary>();
+
+ var summary = Telemetry.Reports.GetTransferSummary(start, end, username: username);
+
+ results.Add(TransferDirection.Upload, new UserDirectionTransferSummary
+ {
+ Summary = summary[TransferDirection.Upload],
+ Statistics = GetStatistics(summary[TransferDirection.Upload]),
+ Exceptions = Telemetry.Reports.GetTransferExceptionsPareto(TransferDirection.Upload, start, end, username: username, limit: 25, offset: 0),
+ });
+
+ results.Add(TransferDirection.Download, new UserDirectionTransferSummary
+ {
+ Summary = summary[TransferDirection.Download],
+ Statistics = GetStatistics(summary[TransferDirection.Download]),
+ Exceptions = Telemetry.Reports.GetTransferExceptionsPareto(TransferDirection.Download, start, end, username: username, limit: 25, offset: 0),
+ });
+
+ return Ok(results);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching user details for {Username}: {Message}", username, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets a list of transfer exceptions by direction.
+ /// </summary>
+ /// <param name="direction">The direction.</param>
+ /// <param name="start">The start time.</param>
+ /// <param name="end">The end time.</param>
+ /// <param name="username">An optional username by which to filter exceptions.</param>
+ /// <param name="sortOrder">The sort order (ASC, DESC. Default: DESC).</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/exceptions")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferExceptionDetail>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferExceptions(
+ [FromQuery] string direction = null,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] string sortOrder = "DESC",
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder))
+ {
+ return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferExceptions(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end.Value,
+ username: username,
+ sortOrder: parsedSortOrder,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer exceptions over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N exceptions by total count and direction.
+ /// </summary>
+ /// <param name="direction">The direction.</param>
+ /// <param name="start">The start time.</param>
+ /// <param name="end">The end time.</param>
+ /// <param name="username">An optional username by which to filter exceptions.</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/exceptions/pareto")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferExceptionSummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferExceptionsPareto(
+ [FromQuery] string direction,
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ if (string.IsNullOrWhiteSpace(direction))
+ {
+ return BadRequest("Direction is required");
+ }
+
+ if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection))
+ {
+ return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}");
+ }
+
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferExceptionsPareto(
+ direction: parsedDirection,
+ start: start.Value,
+ end: end.Value,
+ limit: limit,
+ offset: offset,
+ username: username));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer exceptions over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+
+ /// <summary>
+ /// Gets the top N most frequently downloaded directories by total count and distinct users.
+ /// </summary>
+ /// <param name="start">The start time of the window (default: 12/30/2025).</param>
+ /// <param name="end">The end time of the window (default: now).</param>
+ /// <param name="username">An optional username by which to filter records.</param>
+ /// <param name="limit">The number of records to return (Default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns></returns>
+ /// <response code="200">The request completed successfully.</response>
+ /// <response code="400">Bad request.</response>
+ /// <response code="500">An error occurred.</response>
+ [HttpGet("transfers/directories")]
+ [Authorize(Policy = AuthPolicy.Any)]
+ [ProducesResponseType(typeof(List<TransferDirectorySummary>), 200)]
+ [ProducesResponseType(typeof(string), 400)]
+ [ProducesResponseType(typeof(string), 500)]
+ public IActionResult GetTransferDirectoryFrequency(
+ [FromQuery] DateTime? start = null,
+ [FromQuery] DateTime? end = null,
+ [FromQuery] string username = null,
+ [FromQuery] int limit = 25,
+ [FromQuery] int offset = 0)
+ {
+ start ??= Program.GenesisDateTime;
+ end ??= DateTime.MaxValue;
+
+ if (start >= end)
+ {
+ return BadRequest("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ return BadRequest("Limit must be greater than zero");
+ }
+
+ if (offset < 0)
+ {
+ return BadRequest("Offset must be greater than or equal to zero");
+ }
+
+ try
+ {
+ return Ok(Telemetry.Reports.GetTransferDirectoryFrequency(
+ start: start,
+ end: end,
+ username: username,
+ limit: limit,
+ offset: offset));
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Error fetching transfer directories over {Start}-{End}: {Message}", start, end, ex.Message);
+ return StatusCode(500, ex.Message);
+ }
+ }
+}
diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs
index 0525a81a..7bc6fd25 100644
--- a/src/slskd/Telemetry/Metrics.cs
+++ b/src/slskd/Telemetry/Metrics.cs
@@ -15,126 +15,134 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd
+namespace slskd.Telemetry;
+
+using System;
+using Prometheus;
+
+/// <summary>
+/// This class contains all of the custom Prometheus metrics for slskd. These represent a small subset of the metrics
+/// available, with the rest coming from the .NET and ASP.NET frameworks and the host system.
+/// </summary>
+/// <remarks>
+/// These metrics and their names are part of the public API contract; avoid renaming or removing them, and think
+/// carefully about naming when adding new metrics.
+/// </remarks>
+public static class Metrics
{
- using System;
- using Prometheus;
+ /// <summary>
+ /// Metrics related to search requests and responses.
+ /// </summary>
+ public static class Search
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_search_response_latency",
+ "The time taken to resolve a response to an incoming search request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets an automatically resetting counter of the number of search requests received.
+ /// </summary>
+ public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count));
+
+ /// <summary>
+ /// Gets a counter representing the total number of search requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of search responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds");
+ private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last second");
+ }
+
+ /// <summary>
+ /// Metrics related to browse requests and responses.
+ /// </summary>
+ public static class Browse
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_browse_response_latency",
+ "The time taken to resolve a response to an incoming browse request, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(1, 2, 10),
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_requests_received", "Total number of browse requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of browse responses sent.
+ /// </summary>
+ public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_responses_sent", "Total number of browse responses sent");
+
+ private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds");
+ }
/// <summary>
- /// This class contains all of the custom Prometheus metrics for slskd. These represent a small subset of the metrics
- /// available, with the rest coming from the .NET and ASP.NET frameworks and the host system.
+ /// Metrics related to the distributed network.
/// </summary>
- /// <remarks>
- /// These metrics and their names are part of the public API contract; avoid renaming or removing them, and think
- /// carefully about naming when adding new metrics.
- /// </remarks>
- public static class Metrics
+ public static class DistributedNetwork
{
- public static class Search
- {
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_search_response_latency",
- "The time taken to resolve a response to an incoming search request, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
- });
-
- /// <summary>
- /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
-
- /// <summary>
- /// Gets an automatically resetting counter of the number of search requests received.
- /// </summary>
- public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count));
-
- /// <summary>
- /// Gets a counter representing the total number of search requests received.
- /// </summary>
- public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received");
-
- /// <summary>
- /// Gets a counter representing the total number of search responses sent.
- /// </summary>
- public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent");
-
- private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds");
- private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last second");
- }
-
- public static class Browse
- {
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
- /// </summary>
- public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_browse_response_latency",
- "The time taken to resolve a response to an incoming browse request, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(1, 2, 10),
- });
-
- /// <summary>
- /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds.
- /// </summary>
- public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
-
- /// <summary>
- /// Gets a counter representing the total number of browse requests received.
- /// </summary>
- public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_requests_received", "Total number of browse requests received");
-
- /// <summary>
- /// Gets a counter representing the total number of browse responses sent.
- /// </summary>
- public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_browse_responses_sent", "Total number of browse responses sent");
-
- private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds");
- }
-
- public static class DistributedNetwork
- {
- /// <summary>
- /// Gets a gauge representing the current number of connected distributed children.
- /// </summary>
- public static Gauge Children { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_children", "Current number of connected distributed children");
-
- /// <summary>
- /// Gets a gauge representing the current distributed child limit.
- /// </summary>
- public static Gauge ChildLimit { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_child_limit", "Current distributed child limit");
-
- /// <summary>
- /// Gets a gauge indicating whether a distributed parent connection is established.
- /// </summary>
- public static Gauge HasParent { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_has_parent", "A value indicating whether a distributed parent connection is established");
-
- /// <summary>
- /// Gets a gauge representing the current distributed branch level.
- /// </summary>
- public static Gauge BranchLevel { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_branch_level", "Current distributed branch level");
-
- /// <summary>
- /// Gets a gauge representing the most recent average time taken to broadcast incoming search requests to connected children.
- /// </summary>
- public static Gauge CurrentBroadcastLatency { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_broadcast_latency_current", "The average time taken to broadcast incoming search requests to connected children");
-
- /// <summary>
- /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
- /// </summary>
- public static Histogram BroadcastLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_dnet_broadcast_latency",
- "The time taken to broadcast incoming search requests to connected children, in milliseconds",
- new HistogramConfiguration
- {
- Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
- });
- }
+ /// <summary>
+ /// Gets a gauge representing the current number of connected distributed children.
+ /// </summary>
+ public static Gauge Children { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_children", "Current number of connected distributed children");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed child limit.
+ /// </summary>
+ public static Gauge ChildLimit { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_child_limit", "Current distributed child limit");
+
+ /// <summary>
+ /// Gets a gauge indicating whether a distributed parent connection is established.
+ /// </summary>
+ public static Gauge HasParent { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_has_parent", "A value indicating whether a distributed parent connection is established");
+
+ /// <summary>
+ /// Gets a gauge representing the current distributed branch level.
+ /// </summary>
+ public static Gauge BranchLevel { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_branch_level", "Current distributed branch level");
+
+ /// <summary>
+ /// Gets a gauge representing the most recent average time taken to broadcast incoming search requests to connected children.
+ /// </summary>
+ public static Gauge CurrentBroadcastLatency { get; } = Prometheus.Metrics.CreateGauge("slskd_dnet_broadcast_latency_current", "The average time taken to broadcast incoming search requests to connected children");
+
+ /// <summary>
+ /// Gets a histogram representing the time taken to resolve a response to an incoming browse request, in milliseconds.
+ /// </summary>
+ public static Histogram BroadcastLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_dnet_broadcast_latency",
+ "The time taken to broadcast incoming search requests to connected children, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(0.1, 2, 11),
+ });
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs
index 249319d5..06235981 100644
--- a/src/slskd/Telemetry/PrometheusService.cs
+++ b/src/slskd/Telemetry/PrometheusService.cs
@@ -15,7 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
using System;
using System.Collections.Generic;
@@ -30,6 +30,25 @@ public class PrometheusService
private static Regex PrometheusLabelSplittingRegex { get; } = new Regex("([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*\"([^\"]*)\"", RegexOptions.Compiled);
/// <summary>
+ /// These metrics repeat many times with disambiguating labels, and this conflicts with the current approach
+ /// for building metrics in object format; dictionary entries (keyed by the names seen in this list) conflict,
+ /// and values are merged and potentially collide. This could be fixed by pulling disambiguating labels up into
+ /// the names, but these labels are things like HTTP route names, exception types, and server addresses. All of
+ /// which has very little value to an application that wants to display metrics to an end user (which is why this exists).
+ ///
+ /// The easy solution is to just ignore these classes of metrics, and that's what I'm going to do.
+ ///
+ /// This can be revisited if someone feels very strongly.
+ /// </summary>
+ private static Regex[] ExcludedMetrics { get; } = new[]
+ {
+ new Regex("^microsoft_aspnetcore_hosting_http_server_request_duration.*", RegexOptions.Compiled),
+ new Regex("^system_net_http_http_client_request_time_in_queue.*", RegexOptions.Compiled),
+ new Regex("^system_net_http_http_client_request_duration.*", RegexOptions.Compiled),
+ new Regex("^microsoft_aspnetcore_server_kestrel_kestrel_connection_duration.*", RegexOptions.Compiled),
+ };
+
+ /// <summary>
/// Get the current list of Prometheus metrics in Prometheus exposition format (text based).
/// </summary>
/// <returns></returns>
@@ -85,6 +104,12 @@ public class PrometheusService
continue;
}
+ // see the note above about excluded metrics and why this is necessary
+ if (ExcludedMetrics.Any(regex => regex.IsMatch(name)))
+ {
+ continue;
+ }
+
var type = lines[startIndex + 1].Substring(7).Split(' ', 2)[1];
var metric = new PrometheusMetric() { Name = name, Help = help, Type = type };
diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs
new file mode 100644
index 00000000..da325dc0
--- /dev/null
+++ b/src/slskd/Telemetry/ReportsService.cs
@@ -0,0 +1,542 @@
+// <copyright file="ReportsService.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Dapper;
+using Microsoft.Data.Sqlite;
+using Serilog;
+using Soulseek;
+
+/// <summary>
+/// Reports.
+/// </summary>
+public class ReportsService
+{
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ReportsService"/> class.
+ /// </summary>
+ public ReportsService(ConnectionStringDictionary connectionStringDictionary)
+ {
+ ConnectionStrings = connectionStringDictionary;
+ }
+
+ private ConnectionStringDictionary ConnectionStrings { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ReportsService>();
+
+ /// <summary>
+ /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only
+ /// completed transfers.
+ /// </summary>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="direction">The optional direction (Upload or Download) for the summary.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns>
+ /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception>
+ public Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>> GetTransferSummary(
+ DateTime? start = null,
+ DateTime? end = null,
+ TransferDirection? direction = null,
+ string username = null)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ var dict = new Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>()
+ {
+ { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() },
+ { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() },
+ };
+
+ var sql = @$"
+ SELECT
+ Direction,
+ StateDescription,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ COUNT(DISTINCT Username) AS DistinctUsers,
+ AVG(AverageSpeed) AS AverageSpeed,
+ AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
+ AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
+ FROM Transfers
+ WHERE EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(direction is not null ? "AND Direction = @Direction" : string.Empty)}
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Direction, StateDescription
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction?.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ foreach (var result in results)
+ {
+ var record = new TransferSummary
+ {
+ TotalBytes = result.TotalBytes,
+ Count = result.Count,
+ DistinctUsers = result.DistinctUsers,
+ AverageSpeed = result.AverageSpeed,
+ AverageWait = result.AverageWait,
+ AverageDuration = result.AverageDuration,
+ };
+
+ dict[result.Direction].Add(result.StateDescription & ~TransferStates.Completed, record);
+ }
+
+ return dict;
+ }
+
+ /// <summary>
+ /// Returns a histogram of all transfer data, aggregated into fixed size time intervals and grouped by
+ /// direction and final transfer state. Includes only completed transfers.
+ /// </summary>
+ /// <param name="start">The start time of the histogram window.</param>
+ /// <param name="end">The end time of the histogram window.</param>
+ /// <param name="interval">The interval for the histogram.</param>
+ /// <param name="direction">The optional direction (Upload or Download) by which to filter results.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns>
+ /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception>
+ public Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>> GetTransferHistogram(
+ DateTime start,
+ DateTime end,
+ TimeSpan interval,
+ TransferDirection? direction = null,
+ string username = null)
+ {
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ var dict = new Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>();
+
+ // fill the dictionary with gapless intervals and empty dictionaries
+ var currentInterval = new DateTime(start.Ticks / interval.Ticks * interval.Ticks, DateTimeKind.Utc);
+
+ while (currentInterval < end)
+ {
+ dict[currentInterval] = new Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>()
+ {
+ { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() },
+ { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() },
+ };
+ currentInterval = currentInterval.Add(interval);
+ }
+
+ var sql = @$"
+ SELECT
+ datetime(strftime('%s', EndedAt) / CAST(@Interval AS INTEGER) * CAST(@Interval AS INTEGER), 'unixepoch') AS Interval,
+ Direction,
+ StateDescription,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ COUNT(DISTINCT Username) AS Users,
+ AVG(AverageSpeed) AS AverageSpeed,
+ COALESCE(AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)), 0.0) AS AverageWait,
+ COALESCE(AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0.0) AS AverageDuration
+ FROM Transfers
+ WHERE EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(direction is not null ? "AND Direction = @Direction" : string.Empty)}
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Interval, Direction, StateDescription
+ ORDER BY Interval, Direction, StateDescription;
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction?.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Interval = (int)interval.TotalSeconds,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ foreach (var result in results)
+ {
+ var record = new TransferSummary
+ {
+ TotalBytes = result.TotalBytes,
+ Count = result.Count,
+ DistinctUsers = result.DistinctUsers,
+ AverageSpeed = result.AverageSpeed,
+ AverageWait = result.AverageWait,
+ AverageDuration = result.AverageDuration,
+ };
+
+ if (result.Interval.HasValue)
+ {
+ // normalize the result interval to match the bucket interval
+ var bucketInterval = new DateTime(result.Interval.Value.Ticks / interval.Ticks * interval.Ticks, DateTimeKind.Utc);
+
+ if (dict.TryGetValue(bucketInterval, out var intervalDict))
+ {
+ intervalDict[result.Direction][result.StateDescription & ~TransferStates.Completed] = record;
+ }
+ }
+ }
+
+ return dict;
+ }
+
+ /// <summary>
+ /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download).</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="sortBy">The property by which to sort.</param>
+ /// <param name="sortOrder">The sort order.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A dictionary keyed by username and containing summary information.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferSummary> GetTransferLeaderboard(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ LeaderboardSortBy sortBy = LeaderboardSortBy.Count,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ Username,
+ Direction,
+ State,
+ SUM(Size) AS TotalBytes,
+ COUNT(*) AS Count,
+ AVG(AverageSpeed) AS AverageSpeed,
+ AVG(strftime('%s', StartedAt) - strftime('%s', EnqueuedAt)) AS AverageWait,
+ AVG(strftime('%s', EndedAt) - strftime('%s', StartedAt)) AS AverageDuration
+ FROM Transfers
+ WHERE Direction = @Direction
+ AND State = 48
+ AND EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ GROUP BY Username, Direction, StateDescription
+ ORDER BY {sortBy} {sortOrder}, Username DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Limit = limit,
+ Offset = offset,
+ Start = start,
+ End = end,
+ };
+
+ var results = connection.Query<TransferSummaryRow>(sql, param);
+
+ var list = results.Select(row => new TransferSummary
+ {
+ Username = row.Username,
+ TotalBytes = row.TotalBytes,
+ Count = row.Count,
+ AverageSpeed = row.AverageSpeed,
+ AverageWait = row.AverageWait,
+ AverageDuration = row.AverageDuration,
+ }).ToList();
+
+ return list;
+ }
+
+ /// <summary>
+ /// Returns a list of transfer exceptions.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download).</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <param name="sortOrder">The sort order.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A list of exceptions.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferExceptionDetail> GetTransferExceptions(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ Id,
+ Username,
+ Direction,
+ Filename,
+ Size,
+ StartOffset,
+ State,
+ RequestedAt
+ EnqueuedAt,
+ StartedAt,
+ EndedAt,
+ BytesTransferred,
+ AverageSpeed,
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END as Exception
+ FROM transfers
+ WHERE state & ~48
+ AND Direction = @Direction
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ ORDER BY EndedAt {sortOrder}
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ };
+
+ var results = connection.Query<TransferExceptionDetail>(sql, param);
+ return results.ToList();
+ }
+
+ /// <summary>
+ /// Returns a summary of distinct transfer exceptions and the number of times they occurred.
+ /// </summary>
+ /// <param name="direction">The direction (Upload or Download) for the summary.</param>
+ /// <param name="start">The optional start time of the summary window.</param>
+ /// <param name="end">The optional end time of the summary window.</param>
+ /// <param name="username">The optional username by which to filter results.</param>
+ /// <param name="limit">The number of records to return (default: 25).</param>
+ /// <param name="offset">The record offset (if paginating).</param>
+ /// <returns>A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred.</returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferExceptionSummary> GetTransferExceptionsPareto(
+ TransferDirection direction,
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ SELECT
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END as Exception,
+ COUNT(*) as Count,
+ COUNT(DISTINCT Username) as DistinctUsers
+ FROM transfers
+ WHERE state & ~48
+ AND Direction = @Direction
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ GROUP BY Direction,
+ CASE
+ WHEN INSTR(Exception, ':') > 0
+ THEN SUBSTR(Exception, INSTR(Exception, ':') + 2)
+ ELSE Exception
+ END
+ ORDER BY Count DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Direction = direction.ToString(),
+ Username = username,
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ };
+
+ var results = connection.Query<TransferExceptionSummary>(sql, param);
+ return results.ToList();
+ }
+
+ /// <summary>
+ /// Returns a list of directories and the frequency at which they have been downloaded.
+ /// </summary>
+ /// <param name="start"></param>
+ /// <param name="end"></param>
+ /// <param name="username"></param>
+ /// <param name="sortOrder"></param>
+ /// <param name="limit"></param>
+ /// <param name="offset"></param>
+ /// <returns></returns>
+ /// <exception cref="ArgumentException">
+ /// Thrown if end time is not later than start time, or limit is not greater than zero.
+ /// </exception>
+ public List<TransferDirectorySummary> GetTransferDirectoryFrequency(
+ DateTime? start = null,
+ DateTime? end = null,
+ string username = null,
+ SortOrder sortOrder = SortOrder.DESC,
+ int limit = 25,
+ int offset = 0)
+ {
+ start ??= DateTime.MinValue;
+ end ??= DateTime.MaxValue;
+
+ if (end <= start)
+ {
+ throw new ArgumentException("End time must be later than start time");
+ }
+
+ if (limit <= 0)
+ {
+ throw new ArgumentOutOfRangeException("Limit must be greater than zero");
+ }
+
+ var sql = @$"
+ WITH directories AS (
+ SELECT
+ RTRIM(
+ RTRIM(filename, REPLACE(REPLACE(filename, '/', ''), '\', '')), '/\'
+ ) AS Directory,
+ Username
+ FROM transfers
+ WHERE Direction = 'Upload'
+ AND State = 48
+ AND EndedAt IS NOT NULL
+ AND EndedAt BETWEEN @Start AND @End
+ {(username is not null ? "AND Username = @Username" : string.Empty)}
+ )
+ SELECT Directory, COUNT(*) AS Count, COUNT(DISTINCT Username) AS DistinctUsers
+ FROM directories
+ GROUP BY Directory
+ ORDER BY DistinctUsers DESC, Count DESC
+ LIMIT @Limit
+ OFFSET @Offset
+ ";
+
+ using var connection = new SqliteConnection(ConnectionStrings[Database.Transfers]);
+
+ var param = new
+ {
+ Start = start,
+ End = end,
+ Limit = limit,
+ Offset = offset,
+ Username = username,
+ };
+
+ var results = connection.Query<TransferDirectorySummary>(sql, param);
+ return results.ToList();
+ }
+
+ private record TransferSummaryRow
+ {
+ public DateTime? Interval { get; init; }
+ public string Username { get; init; }
+ public TransferDirection Direction { get; init; }
+ public TransferStates StateDescription { get; init; }
+ public long TotalBytes { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+ public double AverageSpeed { get; init; }
+ public double AverageWait { get; init; }
+ public double AverageDuration { get; init; }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs
index c3d66196..e122cbe4 100644
--- a/src/slskd/Telemetry/TelemetryService.cs
+++ b/src/slskd/Telemetry/TelemetryService.cs
@@ -1,4 +1,4 @@
-// <copyright file="MetricsService.cs" company="slskd Team">
+// <copyright file="TelemetryService.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -15,14 +15,16 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
public class TelemetryService
{
- public TelemetryService(PrometheusService prometheusService)
+ public TelemetryService(PrometheusService prometheusService, ReportsService reportsService)
{
Prometheus = prometheusService;
+ Reports = reportsService;
}
public PrometheusService Prometheus { get; }
+ public ReportsService Reports { get; }
} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/DirectoryDetail.cs b/src/slskd/Telemetry/Types/DirectoryDetail.cs
new file mode 100644
index 00000000..54901507
--- /dev/null
+++ b/src/slskd/Telemetry/Types/DirectoryDetail.cs
@@ -0,0 +1,23 @@
+// <copyright file="DirectoryDetail.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+public record TransferDirectorySummary
+{
+ public string Directory { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/LeaderboardSorting.cs b/src/slskd/Telemetry/Types/LeaderboardSorting.cs
new file mode 100644
index 00000000..e90a8c3d
--- /dev/null
+++ b/src/slskd/Telemetry/Types/LeaderboardSorting.cs
@@ -0,0 +1,25 @@
+// <copyright file="LeaderboardSorting.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+public enum LeaderboardSortBy
+{
+ Count,
+ TotalBytes,
+ AverageSpeed,
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/PrometheusMetric.cs b/src/slskd/Telemetry/Types/PrometheusMetric.cs
index 53b8dc10..05e2446d 100644
--- a/src/slskd/Telemetry/Types/PrometheusMetric.cs
+++ b/src/slskd/Telemetry/Types/PrometheusMetric.cs
@@ -1,4 +1,4 @@
-// <copyright file="Types.cs" company="slskd Team">
+// <copyright file="PrometheusMetric.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -15,7 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
-namespace slskd;
+namespace slskd.Telemetry;
using System.Collections.Generic;
diff --git a/src/slskd/Telemetry/Types/SortOrder.cs b/src/slskd/Telemetry/Types/SortOrder.cs
new file mode 100644
index 00000000..7f70fd21
--- /dev/null
+++ b/src/slskd/Telemetry/Types/SortOrder.cs
@@ -0,0 +1,24 @@
+// <copyright file="SortOrder.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+public enum SortOrder
+{
+ ASC,
+ DESC,
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs
new file mode 100644
index 00000000..a749c6a5
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs
@@ -0,0 +1,39 @@
+// <copyright file="TransferExceptionDetail.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+using System;
+using Soulseek;
+
+public record TransferExceptionDetail
+{
+ public string Id { get; init; }
+ public string Username { get; init; }
+ public TransferDirection Direction { get; init; }
+ public string Filename { get; init; }
+ public long Size { get; set; }
+ public long StartOffset { get; init; }
+ public TransferStates State { get; set; } = TransferStates.None;
+ public DateTime RequestedAt { get; set; }
+ public DateTime? EnqueuedAt { get; set; }
+ public DateTime? StartedAt { get; set; }
+ public DateTime? EndedAt { get; set; }
+ public long BytesTransferred { get; set; }
+ public double AverageSpeed { get; set; }
+ public string Exception { get; set; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferExceptionSummary.cs b/src/slskd/Telemetry/Types/TransferExceptionSummary.cs
new file mode 100644
index 00000000..03b64df5
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferExceptionSummary.cs
@@ -0,0 +1,25 @@
+// <copyright file="TransferExceptionSummary.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+public record TransferExceptionSummary
+{
+ public string Exception { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/TransferSummary.cs b/src/slskd/Telemetry/Types/TransferSummary.cs
new file mode 100644
index 00000000..c25f81fc
--- /dev/null
+++ b/src/slskd/Telemetry/Types/TransferSummary.cs
@@ -0,0 +1,29 @@
+// <copyright file="TransferSummary.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+public record TransferSummary
+{
+ public string Username { get; init; }
+ public long TotalBytes { get; init; }
+ public long Count { get; init; }
+ public long DistinctUsers { get; init; }
+ public double AverageSpeed { get; init; }
+ public double AverageWait { get; init; }
+ public double AverageDuration { get; init; }
+} \ No newline at end of file
diff --git a/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs b/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs
new file mode 100644
index 00000000..c6d30a04
--- /dev/null
+++ b/src/slskd/Telemetry/Types/UserDirectionTransferSummary.cs
@@ -0,0 +1,36 @@
+// <copyright file="UserDirectionTransferSummary.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// 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, either version 3 of the License, or
+// (at your option) any later version.
+//
+// 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/.
+// </copyright>
+
+namespace slskd.Telemetry;
+
+using System.Collections.Generic;
+using Soulseek;
+
+public record UserDirectionTransferSummary
+{
+ public Dictionary<TransferStates, TransferSummary> Summary { get; init; }
+ public UserDirectionTransferStatistics Statistics { get; init; }
+ public List<TransferExceptionSummary> Exceptions { get; init; }
+}
+
+public record UserDirectionTransferStatistics
+{
+ public long Total { get; init; }
+ public long Successful { get; init; }
+ public long Errored { get; init; }
+ public long Cancelled { get; init; }
+} \ 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 f38c4b87..6be11b2d 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -53,7 +53,7 @@ namespace slskd.Transfers.API
OptionsSnapshot = optionsSnapshot;
}
- private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(1, 1);
+ private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2);
private ITransferService Transfers { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>();
@@ -226,8 +226,9 @@ namespace slskd.Transfers.API
try
{
- await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken);
- return StatusCode(201);
+ var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken);
+
+ return StatusCode(201, new { Enqueued = enqueued, Failed = failed });
}
catch (Exception ex)
{
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 9d0a8ed9..9bc25373 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -108,6 +108,20 @@ namespace slskd.Transfers.Downloads
bool TryCancel(Guid id);
/// <summary>
+ /// Fails the download matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
+ /// and sets the final state accordingly.
+ /// </summary>
+ /// <remarks>
+ /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
+ /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
+ /// the terminal Completed flag, it is unchanged.
+ /// </remarks>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <param name="exception">The exception that caused the failure.</param>
+ /// <returns>A value indicating whether the download was successfully failed.</returns>
+ bool TryFail(Guid id, Exception exception);
+
+ /// <summary>
/// Updates the specified <paramref name="transfer"/>.
/// </summary>
/// <param name="transfer">The transfer to update.</param>
@@ -785,26 +799,38 @@ namespace slskd.Transfers.Downloads
{
var t = Find(t => t.Id == id);
- if (t is not null)
+ if (t is null)
{
- t.EndedAt ??= DateTime.UtcNow;
- t.Exception ??= exception.Message;
+ return false;
+ }
- if (!t.State.HasFlag(TransferStates.Completed))
+ t.EndedAt ??= DateTime.UtcNow;
+
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = exception.Message;
+ t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
+
+ if (!t.State.HasFlag(TransferStates.Completed))
+ {
+ t.State = TransferStates.Completed | exception switch
{
- t.State = TransferStates.Completed | exception switch
- {
- OperationCanceledException => TransferStates.Cancelled,
- TimeoutException => TransferStates.TimedOut,
- _ => TransferStates.Errored,
- };
- }
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
+ }
+ try
+ {
Update(t);
return true;
}
-
- return false;
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to update database: {Message}", ex.Message);
+ return false;
+ }
}
/// <summary>
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index ea138bcd..eac4935b 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -26,7 +26,6 @@ namespace slskd.Transfers
public TransfersDbContext(DbContextOptions<TransfersDbContext> options)
: base(options)
{
- Database.EnsureCreated();
}
public DbSet<Transfer> Transfers { get; set; }
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 4b35bffb..c96d1131 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -126,6 +126,20 @@ namespace slskd.Transfers.Uploads
bool TryCancel(Guid id);
/// <summary>
+ /// Fails the upload matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
+ /// and sets the final state accordingly.
+ /// </summary>
+ /// <remarks>
+ /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
+ /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
+ /// the terminal Completed flag, it is unchanged.
+ /// </remarks>
+ /// <param name="id">The unique identifier for the upload.</param>
+ /// <param name="exception">The exception that caused the failure.</param>
+ /// <returns>A value indicating whether the upload was successfully failed.</returns>
+ bool TryFail(Guid id, Exception exception);
+
+ /// <summary>
/// Synchronously updates the specified <paramref name="transfer"/>.
/// </summary>
/// <param name="transfer">The transfer to update.</param>
@@ -418,28 +432,22 @@ namespace slskd.Transfers.Uploads
return transfer;
}
- catch (NotFoundException)
+ catch (NotFoundException ex)
{
- transfer.EndedAt = DateTime.Now;
- transfer.Exception = "File could not be found";
- transfer.State = TransferStates.Completed | TransferStates.Aborted;
+ Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
+
+ TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted);
+ // todo: broadcast
SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
throw;
}
catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
{
- transfer.EndedAt = DateTime.UtcNow;
- transfer.Exception = ex.Message;
- transfer.State = TransferStates.Completed;
+ Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
- transfer.State |= ex switch
- {
- OperationCanceledException => TransferStates.Cancelled,
- TimeoutException => TransferStates.TimedOut,
- _ => TransferStates.Errored,
- };
+ TryFail(transfer.Id, exception: ex);
// todo: broadcast
SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
@@ -450,9 +458,7 @@ namespace slskd.Transfers.Uploads
{
Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
- transfer.EndedAt = DateTime.UtcNow;
- transfer.Exception = ex.Message;
- transfer.State = TransferStates.Completed | TransferStates.Errored;
+ TryFail(transfer.Id, exception: ex);
// todo: broadcast
SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
@@ -488,7 +494,6 @@ namespace slskd.Transfers.Uploads
catch (Exception ex)
{
Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
- throw;
}
}
}
@@ -651,23 +656,9 @@ namespace slskd.Transfers.Uploads
*/
Log.Error(task.Exception, "Task for upload of {Filename} to {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message);
- try
- {
- var transfer = Find(t => t.Id == id);
-
- if (transfer is not null)
- {
- transfer.EndedAt ??= DateTime.UtcNow;
- transfer.Exception ??= task.Exception.Message;
- transfer.State = TransferStates.Completed | transfer.State;
-
- Update(transfer);
- }
- }
- catch (Exception ex)
+ if (!TryFail(id, task.Exception))
{
- Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message);
- throw;
+ Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", id, task.Exception.Message);
}
});
@@ -677,22 +668,9 @@ namespace slskd.Transfers.Uploads
{
Log.Error(ex, "Failed to enqueue upload of {Filename} to {Username}: {Message}", filename, username, ex.Message);
- try
+ if (!TryFail(id, exception: ex))
{
- var transfer = Find(t => t.Id == id);
-
- if (transfer is not null)
- {
- transfer.EndedAt ??= DateTime.UtcNow;
- transfer.Exception ??= ex.Message;
- transfer.State = TransferStates.Completed | transfer.State;
-
- Update(transfer);
- }
- }
- catch (Exception innerEx)
- {
- Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message);
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, ex.Message);
throw;
}
@@ -899,6 +877,31 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
+ /// Fails the upload matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
+ /// and sets the final state accordingly.
+ /// </summary>
+ /// <remarks>
+ /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
+ /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
+ /// the terminal Completed flag, it is unchanged.
+ /// </remarks>
+ /// <param name="id">The unique identifier for the upload.</param>
+ /// <param name="exception">The exception that caused the failure.</param>
+ /// <returns>A value indicating whether the upload was successfully failed.</returns>
+ public bool TryFail(Guid id, Exception exception)
+ {
+ var state = exception switch
+ {
+ NotFoundException => TransferStates.Aborted,
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
+
+ return TryFail(id, exception.Message, state);
+ }
+
+ /// <summary>
/// Synchronously updates the specified <paramref name="transfer"/>.
/// </summary>
/// <param name="transfer">The transfer to update.</param>
@@ -910,6 +913,39 @@ namespace slskd.Transfers.Uploads
context.SaveChanges();
}
+ private bool TryFail(Guid id, string exception, TransferStates state)
+ {
+ var t = Find(t => t.Id == id);
+
+ if (t is null)
+ {
+ return false;
+ }
+
+ t.EndedAt ??= DateTime.UtcNow;
+
+ // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
+ // exceptions in a database. when we encounter one of these, drop the first segment.
+ var m = exception;
+ t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
+
+ if (!t.State.HasFlag(TransferStates.Completed))
+ {
+ t.State = TransferStates.Completed | state;
+ }
+
+ try
+ {
+ Update(t);
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to update database: {Message}", ex.Message);
+ return false;
+ }
+ }
+
/// <summary>
/// Resolves a remote file's location and size from shares and potentially disk.
/// </summary>
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 63dd6937..ce5a7d54 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -17,11 +17,11 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
- <NoWarn>1701;1702;1591;S1133;S2094;S1135;S3925;S125</NoWarn>
+ <NoWarn>1701;1702;1591;S1133;S2094;S1135;S3925;S125;IDE0290;IDE0130</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <NoWarn>1591;S1133;S2094;S1135;S3925;S125</NoWarn>
+ <NoWarn>1591;S1133;S2094;S1135;S3925;S125;IDE0290;IDE0130</NoWarn>
</PropertyGroup>
<ItemGroup>
@@ -44,6 +44,7 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
+ <PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="FluentFTP" Version="49.0.2" />
<PackageReference Include="IPAddressRange" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 7d0f2427..5d0ae3d2 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -13,7 +13,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^0.30.0",
+ "axios": "^0.30.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
@@ -180,6 +180,7 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz",
"integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==",
"dev": true,
+ "peer": true,
"dependencies": {
"@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.23.5",
@@ -225,6 +226,7 @@
"resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.10.tgz",
"integrity": "sha512-3wSYDPZVnhseRnxRJH6ZVTNknBz76AEnyC+AYYhasjP3Yy23qz0ERR7Fcd2SHmYuSFJ2kY9gaaDd3vyqU09eSw==",
"dev": true,
+ "peer": true,
"dependencies": {
"@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1",
"eslint-visitor-keys": "^2.1.0",
@@ -1003,6 +1005,7 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.22.5.tgz",
"integrity": "sha512-9RdCl0i+q0QExayk2nOS7853w08yLucnnPML6EN9S8fgMPVtdLDCdx/cOQ/i44Lb9UeQX9A35yaqBBOMMZxPxQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@babel/helper-plugin-utils": "^7.22.5"
},
@@ -1877,6 +1880,7 @@
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.22.5.tgz",
"integrity": "sha512-rog5gZaVbUip5iWDMTYbVM15XQq+RkUKhET/IHR6oizR+JEoN6CAfTTuHcK4vwUyzca30qqHqEpzBOnaRMWYMA==",
"dev": true,
+ "peer": true,
"dependencies": {
"@babel/helper-annotate-as-pure": "^7.22.5",
"@babel/helper-module-imports": "^7.22.5",
@@ -2505,6 +2509,7 @@
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz",
"integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==",
+ "peer": true,
"dependencies": {
"@codemirror/state": "^6.1.4",
"style-mod": "^4.0.0",
@@ -2516,6 +2521,7 @@
"resolved": "https://registry.npmjs.org/@craco/craco/-/craco-7.1.0.tgz",
"integrity": "sha512-oRAcPIKYrfPXp9rSzlsDNeOaVtDiKhoyqSXUoqiK24jCkHr4T8m/a2f74yXIzCbIheoUWDOIfWZyRgFgT+cpqA==",
"dev": true,
+ "peer": true,
"dependencies": {
"autoprefixer": "^10.4.12",
"cosmiconfig": "^7.0.1",
@@ -3424,10 +3430,11 @@
}
},
"node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": {
- "version": "3.14.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
- "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
+ "version": "3.14.2",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
+ "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@@ -4131,6 +4138,7 @@
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
+ "peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
@@ -4655,6 +4663,7 @@
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz",
"integrity": "sha512-vRb792M4mF1FBT+eoLecmkpLXwxsBHvWWRGJjzbYANBM6DtiJc6yETyv4rqDA6QNjF1pkj1U7LMA6dGb3VYlHw==",
"dev": true,
+ "peer": true,
"dependencies": {
"@types/estree": "*",
"@types/json-schema": "*"
@@ -4898,6 +4907,7 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.9.tgz",
"integrity": "sha512-4uQIBq1ffXd2YvF7MAvehWKW3zVv/w+mSfRAu+8cKbfj3nwzyqJLNcZJpQ/WZ1HLbJDiowwmQ6NO+63nCA+fqA==",
"dev": true,
+ "peer": true,
"dependencies": {
"@eslint-community/regexpp": "^4.4.0",
"@typescript-eslint/scope-manager": "5.59.9",
@@ -4951,6 +4961,7 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.9.tgz",
"integrity": "sha512-FsPkRvBtcLQ/eVK1ivDiNYBjn3TGJdXy2fhXX+rc7czWl4ARwnpArwbihSOHI2Peg9WbtGHrbThfBUkZZGTtvQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "5.59.9",
"@typescript-eslint/types": "5.59.9",
@@ -5398,6 +5409,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
"integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==",
"dev": true,
+ "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5493,6 +5505,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -5948,13 +5961,13 @@
}
},
"node_modules/axios": {
- "version": "0.30.0",
- "resolved": "https://registry.npmjs.org/axios/-/axios-0.30.0.tgz",
- "integrity": "sha512-Z4F3LjCgfjZz8BMYalWdMgAQUnEtKDmpwNHjh/C8pQZWde32TF64cqnSeyL3xD/aTIASRU30RHTNzRiV/NpGMg==",
+ "version": "0.30.2",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-0.30.2.tgz",
+ "integrity": "sha512-0pE4RQ4UQi1jKY6p7u6i1Tkzqmu+d+/tHS7Q7rKunWLB9WyilBTpHHpXzPNMDj5hTbK0B0PTLSz07yqMBiF6xg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.4",
- "form-data": "^4.0.0",
+ "form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@@ -6427,6 +6440,7 @@
"url": "https://github.com/sponsors/ai"
}
],
+ "peer": true,
"dependencies": {
"caniuse-lite": "^1.0.30001646",
"electron-to-chromium": "^1.5.4",
@@ -7364,6 +7378,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -8506,6 +8521,7 @@
"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz",
"integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1",
@@ -8703,6 +8719,7 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz",
"integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "6.21.0",
"@typescript-eslint/types": "6.21.0",
@@ -8952,6 +8969,7 @@
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz",
"integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==",
"dev": true,
+ "peer": true,
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
@@ -9364,6 +9382,7 @@
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz",
"integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==",
"dev": true,
+ "peer": true,
"dependencies": {
"array-includes": "^3.1.6",
"array.prototype.flat": "^1.3.1",
@@ -10124,6 +10143,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -12765,6 +12785,7 @@
"resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz",
"integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@jest/core": "^27.5.1",
"import-local": "^3.0.2",
@@ -13942,10 +13963,11 @@
}
},
"node_modules/js-yaml": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
- "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
},
@@ -14208,6 +14230,7 @@
"resolved": "https://registry.npmjs.org/less/-/less-4.1.3.tgz",
"integrity": "sha512-w16Xk/Ta9Hhyei0Gpz9m7VS8F28nieJaL/VyShID7cYvP6IL5oHeL6p4TXSDJqZE/lNv0oJ2pGVjJsRkfwm5FA==",
"dev": true,
+ "peer": true,
"dependencies": {
"copy-anything": "^2.0.1",
"parse-node-version": "^1.0.1",
@@ -14747,6 +14770,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -14967,10 +14991,11 @@
}
},
"node_modules/node-forge": {
- "version": "1.3.1",
- "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz",
- "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==",
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.2.tgz",
+ "integrity": "sha512-6xKiQ+cph9KImrRh0VsjH2d8/GXA4FIMlgU4B757iI1ApvcyA9VlouP0yZJha01V+huImO+kKMU7ih+2+E14fw==",
"dev": true,
+ "license": "(BSD-3-Clause OR GPL-2.0)",
"engines": {
"node": ">= 6.13.0"
}
@@ -15696,6 +15721,7 @@
"url": "https://github.com/sponsors/ai"
}
],
+ "peer": true,
"dependencies": {
"nanoid": "^3.3.6",
"picocolors": "^1.0.0",
@@ -16830,6 +16856,7 @@
"resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz",
"integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
@@ -16954,6 +16981,7 @@
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
"dev": true,
+ "peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -17267,6 +17295,7 @@
"version": "16.14.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz",
"integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
@@ -17357,6 +17386,7 @@
"version": "16.14.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz",
"integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
@@ -17402,6 +17432,7 @@
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz",
"integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==",
"dev": true,
+ "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -17464,6 +17495,7 @@
"resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz",
"integrity": "sha512-8VAmEm/ZAwQzJ+GOMLbBsTdDKOpuZh7RPs0UymvBR2vRk4iZWCskjbFnxqjrzoIvlNNRZ3QJFx6/qDSi6zSnaQ==",
"dev": true,
+ "peer": true,
"dependencies": {
"@babel/core": "^7.16.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
@@ -18126,6 +18158,7 @@
"resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz",
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
+ "peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
@@ -19412,10 +19445,11 @@
}
},
"node_modules/svgo/node_modules/js-yaml": {
- "version": "3.14.1",
- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
- "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
+ "version": "3.14.2",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
+ "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@@ -19948,6 +19982,7 @@
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
"dev": true,
+ "peer": true,
"engines": {
"node": ">=10"
},
@@ -20047,7 +20082,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true,
- "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -20466,6 +20500,7 @@
"resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz",
"integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==",
"dev": true,
+ "peer": true,
"dependencies": {
"@types/estree": "^1.0.5",
"@webassemblyjs/ast": "^1.12.1",
@@ -20535,6 +20570,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -20588,6 +20624,7 @@
"resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.15.1.tgz",
"integrity": "sha512-5hbAst3h3C3L8w6W4P96L5vaV0PxSmJhxZvWKYIdgxOQm8pNZ5dEOmmSLBVpP85ReeyRt6AS1QJNyo/oFFPeVA==",
"dev": true,
+ "peer": true,
"dependencies": {
"@types/bonjour": "^3.5.9",
"@types/connect-history-api-fallback": "^1.3.5",
@@ -20647,6 +20684,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -21061,6 +21099,7 @@
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz",
"integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==",
"dev": true,
+ "peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
@@ -21325,6 +21364,7 @@
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz",
"integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==",
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=8.3.0"
},
diff --git a/src/web/package.json b/src/web/package.json
index 46835e0e..73dde026 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -18,7 +18,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^0.30.0",
+ "axios": "^0.30.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx
index d5e16cb3..4f36dfe7 100644
--- a/src/web/src/components/Browse/Browse.jsx
+++ b/src/web/src/components/Browse/Browse.jsx
@@ -306,7 +306,7 @@ class Browse extends Component {
<div className="browse-container">
{emptyTree ? (
<PlaceholderSegment
- caption="No user share to display"
+ caption="User is not sharing any files"
icon="folder open"
/>
) : (
diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx
index 39c46248..5a6cf0c2 100644
--- a/src/web/src/components/Rooms/RoomJoinModal.jsx
+++ b/src/web/src/components/Rooms/RoomJoinModal.jsx
@@ -33,7 +33,9 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => {
}, [open]);
const sortedAvailable = useMemo(() => {
- const sorted = [...available].filter((room) => room.name.includes(filter));
+ const sorted = [...available].filter((room) =>
+ room.name.toLowerCase().includes(filter.toLowerCase()),
+ );
sorted.sort((a, b) => {
if (sortOrder === 'asc') {
diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx
index 0d94ee8c..567b80a3 100644
--- a/src/web/src/components/Search/Response.jsx
+++ b/src/web/src/components/Search/Response.jsx
@@ -203,9 +203,9 @@ class Response extends Component {
>
<Icon
loading={fetchingDirectoryContents}
- name={fetchingDirectoryContents ? 'circle notch' : 'folder'}
+ name={fetchingDirectoryContents ? 'circle notch' : 'search'}
/>
- Get Full Directory Contents
+ Search for Additional Files in This Directory
</button>
}
key={directory}
diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css
index a3a2c83a..bd9a6f99 100644
--- a/src/web/src/components/System/System.css
+++ b/src/web/src/components/System/System.css
@@ -8,6 +8,10 @@
margin-bottom: 16px;
}
+.system .menu.tabular {
+ overflow: auto hidden;
+}
+
.logs-table, .events-table {
font-size: smaller;
}