aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-07 17:06:26 -0600
committerGitHub <noreply@github.com>2025-12-07 17:06:26 -0600
commit5e5126028ae7cf9a9d4ad87bc24033af69ec8e8e (patch)
tree76e4d1e91f8b1de41729c475f8a1f47231a4a183 /src
parent869c5535218a8fc7bff2c10ae73d59847b19b55f (diff)
parent49bf81959177a2c3139d83fe3498c574bf325acd (diff)
downloadslskd-5e5126028ae7cf9a9d4ad87bc24033af69ec8e8e.tar.gz
Merge pull request #1547 from slskd/statistics
Add statistics
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/Program.cs14
-rw-r--r--src/slskd/Telemetry/API/MetricsController.cs (renamed from src/slskd/Telemetry/API/TelemetryController.cs)80
-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.cs6
-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.cs2
-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/Downloads/DownloadService.cs6
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs6
-rw-r--r--src/slskd/slskd.csproj5
21 files changed, 1639 insertions, 152 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/Program.cs b/src/slskd/Program.cs
index 6b50aedb..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";
@@ -639,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>();
@@ -903,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);
diff --git a/src/slskd/Telemetry/API/TelemetryController.cs b/src/slskd/Telemetry/API/MetricsController.cs
index d5c44c1a..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)
@@ -59,8 +62,8 @@ public class TelemetryController : ControllerBase
/// Other
/// * 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 1c124610..e122cbe4 100644
--- a/src/slskd/Telemetry/TelemetryService.cs
+++ b/src/slskd/Telemetry/TelemetryService.cs
@@ -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 93ca6422..05e2446d 100644
--- a/src/slskd/Telemetry/Types/PrometheusMetric.cs
+++ b/src/slskd/Telemetry/Types/PrometheusMetric.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.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/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index d906688a..9bc25373 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -805,7 +805,11 @@ namespace slskd.Transfers.Downloads
}
t.EndedAt ??= DateTime.UtcNow;
- t.Exception ??= exception.Message;
+
+ // 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))
{
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index c541d4f0..c96d1131 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -923,7 +923,11 @@ namespace slskd.Transfers.Uploads
}
t.EndedAt ??= DateTime.UtcNow;
- t.Exception ??= exception;
+
+ // 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))
{
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" />