From f2460e95bfdcf7c800a2ef2b26af17dcf9210e65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Dec 2025 16:08:34 -0600 Subject: Statistics -> Reports --- src/slskd/Program.cs | 2 +- src/slskd/Telemetry/API/ReportsController.cs | 557 ++++++++++++++++++++++++ src/slskd/Telemetry/API/StatisticsController.cs | 557 ------------------------ src/slskd/Telemetry/ReportsService.cs | 542 +++++++++++++++++++++++ src/slskd/Telemetry/StatisticsService.cs | 542 ----------------------- src/slskd/Telemetry/TelemetryService.cs | 6 +- 6 files changed, 1103 insertions(+), 1103 deletions(-) create mode 100644 src/slskd/Telemetry/API/ReportsController.cs delete mode 100644 src/slskd/Telemetry/API/StatisticsController.cs create mode 100644 src/slskd/Telemetry/ReportsService.cs delete mode 100644 src/slskd/Telemetry/StatisticsService.cs diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b6713e15..aa320961 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -644,7 +644,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); 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 (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/. +// + +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; + +/// +/// Reports. +/// +[Route("api/v{version:apiVersion}/telemetry/[controller]")] +[Tags("Telemetry")] +[ApiVersion("0")] +[ApiController] +[Produces("application/json")] +public class ReportsController : ControllerBase +{ + /// + /// Initializes a new instance of the class. + /// + public ReportsController(TelemetryService telemetryService) + { + Telemetry = telemetryService; + } + + private TelemetryService Telemetry { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state. + /// + /// The start time of the window (default: 7 days ago). + /// The end time of the window (default: now). + /// An optional direction (Upload, Download) by which to filter records. + /// An optional username by which to filter records. + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/summary")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 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(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); + } + } + + /// + /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals + /// and grouped by direction and final state. + /// + /// The start time of the window (default: 7 days ago). + /// The end time of the window (default: now). + /// The interval, in minutes (default: 60). + /// An optional direction (Upload, Download) by which to filter records. + /// An optional username by which to filter records. + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/histogram")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>>), 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(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); + } + } + + /// + /// Gets the top N user summaries by count, total bytes, or average speed. + /// + /// The direction (Upload, Download). + /// The start time of the window (default: 12/30/2025). + /// The end time of the window (default: now). + /// The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count). + /// The sort order (ASC, DESC. Default: DESC). + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/leaderboard")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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(sortBy, out var parsedSortBy)) + { + return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); + } + + if (!Enum.TryParse(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); + } + } + + /// + /// Gets detailed transfer activity for the specified user. + /// + /// The username of the user. + /// The start time of the summary window (default: 7 days ago). + /// The end time of the summary window (default: now). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/users/{username}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary), 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 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(); + + 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); + } + } + + /// + /// Gets a list of transfer exceptions by direction. + /// + /// The direction. + /// The start time. + /// The end time. + /// An optional username by which to filter exceptions. + /// The sort order (ASC, DESC. Default: DESC). + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/exceptions")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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, 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); + } + } + + /// + /// Gets the top N exceptions by total count and direction. + /// + /// The direction. + /// The start time. + /// The end time. + /// An optional username by which to filter exceptions. + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/exceptions/pareto")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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(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); + } + } + + /// + /// Gets the top N most frequently downloaded directories by total count and distinct users. + /// + /// The start time of the window (default: 12/30/2025). + /// The end time of the window (default: now). + /// An optional username by which to filter records. + /// The number of records to return (Default: 25). + /// The record offset (if paginating). + /// + /// The request completed successfully. + /// Bad request. + /// An error occurred. + [HttpGet("transfers/directories")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(List), 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/API/StatisticsController.cs b/src/slskd/Telemetry/API/StatisticsController.cs deleted file mode 100644 index b535d31d..00000000 --- a/src/slskd/Telemetry/API/StatisticsController.cs +++ /dev/null @@ -1,557 +0,0 @@ -// -// 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/. -// - -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; - -/// -/// Statistics. -/// -[Route("api/v{version:apiVersion}/telemetry/[controller]")] -[Tags("Telemetry")] -[ApiVersion("0")] -[ApiController] -[Produces("application/json")] -public class StatisticsController : ControllerBase -{ - /// - /// Initializes a new instance of the class. - /// - public StatisticsController(TelemetryService telemetryService) - { - Telemetry = telemetryService; - } - - private TelemetryService Telemetry { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Gets a summary of all transfer activity over the specified timeframe, grouped by direction and final state. - /// - /// The start time of the window (default: 7 days ago). - /// The end time of the window (default: now). - /// An optional direction (Upload, Download) by which to filter records. - /// An optional username by which to filter records. - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/summary")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary>), 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(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.Statistics.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); - } - } - - /// - /// Gets a histogram of all transfer activity over the specified timeframe, aggregated into fixed size time intervals - /// and grouped by direction and final state. - /// - /// The start time of the window (default: 7 days ago). - /// The end time of the window (default: now). - /// The interval, in minutes (default: 60). - /// An optional direction (Upload, Download) by which to filter records. - /// An optional username by which to filter records. - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/histogram")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary>>), 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(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.Statistics.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); - } - } - - /// - /// Gets the top N user summaries by count, total bytes, or average speed. - /// - /// The direction (Upload, Download). - /// The start time of the window (default: 12/30/2025). - /// The end time of the window (default: now). - /// The property by which to sort (Count, TotalBytes, AverageSpeed. Default: Count). - /// The sort order (ASC, DESC. Default: DESC). - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/leaderboard")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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(sortBy, out var parsedSortBy)) - { - return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); - } - - if (!Enum.TryParse(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.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); - } - } - - /// - /// Gets detailed transfer activity for the specified user. - /// - /// The username of the user. - /// The start time of the summary window (default: 7 days ago). - /// The end time of the summary window (default: now). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/users/{username}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(Dictionary), 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 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(); - - var summary = Telemetry.Statistics.GetTransferSummary(start, end, username: username); - - results.Add(TransferDirection.Upload, new UserDirectionTransferSummary - { - Summary = summary[TransferDirection.Upload], - Statistics = GetStatistics(summary[TransferDirection.Upload]), - Exceptions = Telemetry.Statistics.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.Statistics.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); - } - } - - /// - /// Gets a list of transfer exceptions by direction. - /// - /// The direction. - /// The start time. - /// The end time. - /// An optional username by which to filter exceptions. - /// The sort order (ASC, DESC. Default: DESC). - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/exceptions")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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, 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( - 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); - } - } - - /// - /// Gets the top N exceptions by total count and direction. - /// - /// The direction. - /// The start time. - /// The end time. - /// An optional username by which to filter exceptions. - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/exceptions/pareto")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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(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.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); - } - } - - /// - /// Gets the top N most frequently downloaded directories by total count and distinct users. - /// - /// The start time of the window (default: 12/30/2025). - /// The end time of the window (default: now). - /// An optional username by which to filter records. - /// The number of records to return (Default: 25). - /// The record offset (if paginating). - /// - /// The request completed successfully. - /// Bad request. - /// An error occurred. - [HttpGet("transfers/directories")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(List), 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.Statistics.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/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 (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/. +// + +namespace slskd.Telemetry; + +using System; +using System.Collections.Generic; +using System.Linq; +using Dapper; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// Reports. +/// +public class ReportsService +{ + /// + /// Initializes a new instance of the class. + /// + public ReportsService(ConnectionStringDictionary connectionStringDictionary) + { + ConnectionStrings = connectionStringDictionary; + } + + private ConnectionStringDictionary ConnectionStrings { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only + /// completed transfers. + /// + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional direction (Upload or Download) for the summary. + /// The optional username by which to filter results. + /// A nested dictionary keyed by direction and state and containing summary information. + /// Thrown if end time is not later than start time. + public Dictionary> 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.Download, new Dictionary() }, + { TransferDirection.Upload, new Dictionary() }, + }; + + 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(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; + } + + /// + /// 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. + /// + /// The start time of the histogram window. + /// The end time of the histogram window. + /// The interval for the histogram. + /// The optional direction (Upload or Download) by which to filter results. + /// The optional username by which to filter results. + /// A nested dictionary keyed by direction and state and containing summary information. + /// Thrown if end time is not later than start time. + public Dictionary>> 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>>(); + + // 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.Download, new Dictionary() }, + { TransferDirection.Upload, new Dictionary() }, + }; + 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(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; + } + + /// + /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts. + /// + /// The direction (Upload or Download). + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The property by which to sort. + /// The sort order. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A dictionary keyed by username and containing summary information. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(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; + } + + /// + /// Returns a list of transfer exceptions. + /// + /// The direction (Upload or Download). + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional username by which to filter results. + /// The sort order. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A list of exceptions. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(sql, param); + return results.ToList(); + } + + /// + /// Returns a summary of distinct transfer exceptions and the number of times they occurred. + /// + /// The direction (Upload or Download) for the summary. + /// The optional start time of the summary window. + /// The optional end time of the summary window. + /// The optional username by which to filter results. + /// The number of records to return (default: 25). + /// The record offset (if paginating). + /// A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred. + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(sql, param); + return results.ToList(); + } + + /// + /// Returns a list of directories and the frequency at which they have been downloaded. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Thrown if end time is not later than start time, or limit is not greater than zero. + /// + public List 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(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/StatisticsService.cs b/src/slskd/Telemetry/StatisticsService.cs deleted file mode 100644 index 53b543f4..00000000 --- a/src/slskd/Telemetry/StatisticsService.cs +++ /dev/null @@ -1,542 +0,0 @@ -// -// 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/. -// - -namespace slskd.Telemetry; - -using System; -using System.Collections.Generic; -using System.Linq; -using Dapper; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// Statistics. -/// -public class StatisticsService -{ - /// - /// Initializes a new instance of the class. - /// - public StatisticsService(ConnectionStringDictionary connectionStringDictionary) - { - ConnectionStrings = connectionStringDictionary; - } - - private ConnectionStringDictionary ConnectionStrings { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Returns a summary of all transfer data grouped by direction and final transfer state. Includes only - /// completed transfers. - /// - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional direction (Upload or Download) for the summary. - /// The optional username by which to filter results. - /// A nested dictionary keyed by direction and state and containing summary information. - /// Thrown if end time is not later than start time. - public Dictionary> 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.Download, new Dictionary() }, - { TransferDirection.Upload, new Dictionary() }, - }; - - 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(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; - } - - /// - /// 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. - /// - /// The start time of the histogram window. - /// The end time of the histogram window. - /// The interval for the histogram. - /// The optional direction (Upload or Download) by which to filter results. - /// The optional username by which to filter results. - /// A nested dictionary keyed by direction and state and containing summary information. - /// Thrown if end time is not later than start time. - public Dictionary>> 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>>(); - - // 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.Download, new Dictionary() }, - { TransferDirection.Upload, new Dictionary() }, - }; - 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(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; - } - - /// - /// Returns the top N users summaries by count, total bytes, or average speed. Only successful transfers are included in counts. - /// - /// The direction (Upload or Download). - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The property by which to sort. - /// The sort order. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A dictionary keyed by username and containing summary information. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(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; - } - - /// - /// Returns a list of transfer exceptions. - /// - /// The direction (Upload or Download). - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional username by which to filter results. - /// The sort order. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A list of exceptions. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(sql, param); - return results.ToList(); - } - - /// - /// Returns a summary of distinct transfer exceptions and the number of times they occurred. - /// - /// The direction (Upload or Download) for the summary. - /// The optional start time of the summary window. - /// The optional end time of the summary window. - /// The optional username by which to filter results. - /// The number of records to return (default: 25). - /// The record offset (if paginating). - /// A dictionary keyed by direction and containing a list of exceptions and the number of times they occurred. - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(sql, param); - return results.ToList(); - } - - /// - /// Returns a list of directories and the frequency at which they have been downloaded. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// Thrown if end time is not later than start time, or limit is not greater than zero. - /// - public List 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(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 f0914fb8..e122cbe4 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -19,12 +19,12 @@ namespace slskd.Telemetry; public class TelemetryService { - public TelemetryService(PrometheusService prometheusService, StatisticsService statisticsService) + public TelemetryService(PrometheusService prometheusService, ReportsService reportsService) { Prometheus = prometheusService; - Statistics = statisticsService; + Reports = reportsService; } public PrometheusService Prometheus { get; } - public StatisticsService Statistics { get; } + public ReportsService Reports { get; } } \ No newline at end of file -- cgit v1.2.3