diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-11-30 18:46:20 -0600 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-11-30 18:46:20 -0600 |
| commit | 91cb8165cb59744d959337a4a0b2793afcc88fe4 (patch) | |
| tree | 72e7d88db03101d7b8adc4c9fc5a515144dc9a29 /src | |
| parent | 47b106fcd88200755c15eed8b9014761c48b2e24 (diff) | |
| download | slskd-91cb8165cb59744d959337a4a0b2793afcc88fe4.tar.gz | |
add leaderboard
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Telemetry/API/StatisticsController.cs | 154 | ||||
| -rw-r--r-- | src/slskd/Telemetry/StatisticsService.cs | 19 | ||||
| -rw-r--r-- | src/slskd/Telemetry/Types/LeaderboardSorting.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Telemetry/Types/SortOrder.cs | 24 |
4 files changed, 169 insertions, 53 deletions
diff --git a/src/slskd/Telemetry/API/StatisticsController.cs b/src/slskd/Telemetry/API/StatisticsController.cs index 302c0705..5da2f979 100644 --- a/src/slskd/Telemetry/API/StatisticsController.cs +++ b/src/slskd/Telemetry/API/StatisticsController.cs @@ -119,7 +119,7 @@ public class StatisticsController : ControllerBase /// <response code="200">The request completed successfully.</response> /// <response code="400">Bad request.</response> /// <response code="500">An error occurred.</response> - [HttpGet("transfers/summary/histogram")] + [HttpGet("transfers/histogram")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>), 200)] [ProducesResponseType(typeof(string), 400)] @@ -141,6 +141,14 @@ public class StatisticsController : ControllerBase 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"); @@ -177,28 +185,28 @@ public class StatisticsController : ControllerBase } /// <summary> - /// Returns a list of transfer exceptions by direction. + /// Gets the top N user summaries by total count and direction. /// </summary> - /// <param name="direction">The direction by which to filter activity.</param> + /// <param name="direction">The direction (Upload, Download).</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="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/exceptions")] + [HttpGet("transfers/leaderboard")] [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List<UserTransferSummary>), 200)] [ProducesResponseType(typeof(List<TransferExceptionSummary>), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] - public IActionResult GetTransferExceptions( - [FromQuery] string direction = null, + public IActionResult GetSuccessfulTransferSummaryByUsername( + [FromQuery] string direction, [FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null, - [FromQuery] string username = null, + [FromQuery] string sortBy = "Count", + [FromQuery] string sortOrder = "ASC", [FromQuery] int limit = 25, [FromQuery] int offset = 0) { @@ -220,27 +228,48 @@ public class StatisticsController : ControllerBase 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.Statistics.GetTransferExceptions( + return Ok(Telemetry.Statistics.GetTransferRanking( + direction: parsedDirection, start: start.Value, - end: end.Value, + end: end, + sortBy: parsedSortBy, + sortOrder: parsedSortOrder, limit: limit, - offset: offset, - direction: parsedDirection, - username: username)); + offset: offset)); } catch (Exception ex) { - Log.Error(ex, "Error fetching transfer exceptions over {Start}-{End}: {Message}", start, end, ex.Message); + Log.Error(ex, "Error fetching transfer leaderboard over {Start}-{End}: {Message}", start, end, ex.Message); return StatusCode(500, ex.Message); } } /// <summary> - /// Returns the top N exceptions by total count and direction. + /// Gets a list of transfer exceptions by direction. /// </summary> - /// <param name="direction">The direction by which to filter activity.</param> + /// <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> @@ -250,13 +279,13 @@ public class StatisticsController : ControllerBase /// <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")] + [HttpGet("transfers/exceptions")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary<TransferDirection, List<TransferExceptionSummary>>), 200)] + [ProducesResponseType(typeof(List<TransferExceptionSummary>), 200)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] - public IActionResult GetTransferExceptionsPareto( - [FromQuery] string direction, + public IActionResult GetTransferExceptions( + [FromQuery] string direction = null, [FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null, [FromQuery] string username = null, @@ -281,14 +310,24 @@ public class StatisticsController : ControllerBase 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.Statistics.GetTransferExceptionsPareto( - direction: parsedDirection, + return Ok(Telemetry.Statistics.GetTransferExceptions( start: start.Value, end: end.Value, limit: limit, offset: offset, + direction: parsedDirection, username: username)); } catch (Exception ex) @@ -299,26 +338,43 @@ public class StatisticsController : ControllerBase } /// <summary> - /// Returns the top N user summaries by total count and direction. + /// 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> - [HttpGet("transfers/users")] + /// <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(Dictionary<TransferDirection, List<UserTransferSummary>>), 200)] - public IActionResult GetSuccessfulTransferSummaryByUsername( + [ProducesResponseType(typeof(Dictionary<TransferDirection, 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] int? limit = null, - [FromQuery] int? offset = 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; - limit ??= 25; - offset ??= 0; if (start >= end) { @@ -335,16 +391,21 @@ public class StatisticsController : ControllerBase return BadRequest("Offset must be greater than or equal to zero"); } - var downloads = Telemetry.Statistics.GetTransferRanking(direction: TransferDirection.Download, start.Value, end, limit: limit.Value, offset: offset.Value); - var uploads = Telemetry.Statistics.GetTransferRanking(direction: TransferDirection.Upload, start.Value, end, limit: limit.Value, offset: offset.Value); - - var dict = new Dictionary<TransferDirection, List<TransferSummary>>() + try { - { TransferDirection.Download, downloads }, - { TransferDirection.Upload, uploads }, - }; - - return Ok(dict); + return Ok(Telemetry.Statistics.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); + } } [HttpGet("transfers/directories")] @@ -357,4 +418,13 @@ public class StatisticsController : ControllerBase // todo: get a list of all directories downloaded at least once, along with the number of times downloaded (doesn't matter what status) return null; } + + [HttpGet("users/{base64Name}")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult GetUser( + [FromRoute] string base64Name) + { + // todo: get everything we can about the user + return null; + } } diff --git a/src/slskd/Telemetry/StatisticsService.cs b/src/slskd/Telemetry/StatisticsService.cs index 3bd9b26b..c528b8f3 100644 --- a/src/slskd/Telemetry/StatisticsService.cs +++ b/src/slskd/Telemetry/StatisticsService.cs @@ -144,8 +144,9 @@ public class StatisticsService var dict = new Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>(); - // Fill the dictionary with gapless intervals and empty dictionaries + // 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>>() @@ -203,7 +204,7 @@ public class StatisticsService if (result.Interval.HasValue) { - // Normalize the result interval to match the bucket interval + // 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)) @@ -366,6 +367,8 @@ public class StatisticsService /// <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="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> @@ -376,6 +379,8 @@ public class StatisticsService TransferDirection direction, DateTime? start = null, DateTime? end = null, + LeaderboardSortBy sortBy = LeaderboardSortBy.Count, + SortOrder sortOrder = SortOrder.DESC, int limit = 25, int offset = 0) { @@ -408,7 +413,7 @@ public class StatisticsService AND EndedAt IS NOT NULL AND EndedAt BETWEEN @Start AND @End GROUP BY Username, Direction, StateDescription - ORDER BY Count DESC, TotalBytes DESC, Username ASC + ORDER BY {sortBy} {sortOrder}, Username DESC LIMIT @Limit OFFSET @Offset "; @@ -452,12 +457,4 @@ public class StatisticsService public double AverageWait { get; init; } public double AverageDuration { get; init; } } - - private record ExceptionSummaryRow - { - public TransferDirection Direction { get; init; } - 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/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/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 |
