From b009d3f8248c92d6b9c0a3db39ab5474cb38c3c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Jun 2026 15:31:23 -0500 Subject: remove StartedAt from GetTransferExceptions query --- src/slskd/Telemetry/ReportsService.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index ae2d1129..c099ef32 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -361,7 +361,6 @@ public class ReportsService Direction, Filename, Size, - StartOffset, State, RequestedAt EnqueuedAt, -- cgit v1.2.3 From 8e420879481824bab8335578995f31b9e86bfdca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Jun 2026 13:56:48 -0500 Subject: add date range selection to exception reports --- src/slskd/Telemetry/ReportsService.cs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index c099ef32..e0304d2a 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -362,20 +362,22 @@ public class ReportsService Filename, Size, State, - RequestedAt + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, - CASE - WHEN INSTR(Exception, ':') > 0 + CASE + WHEN INSTR(Exception, ':') > 0 THEN SUBSTR(Exception, INSTR(Exception, ':') + 2) ELSE Exception END as Exception - FROM transfers + FROM transfers WHERE state & ~48 AND Direction = @Direction + AND EndedAt IS NOT NULL + AND EndedAt BETWEEN @Start AND @End {(username is not null ? "AND Username = @Username" : string.Empty)} ORDER BY EndedAt {sortOrder} LIMIT @Limit @@ -433,21 +435,23 @@ public class ReportsService } var sql = @$" - SELECT - CASE - WHEN INSTR(Exception, ':') > 0 + 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 + FROM transfers WHERE state & ~48 AND Direction = @Direction + AND EndedAt IS NOT NULL + AND EndedAt BETWEEN @Start AND @End {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Direction, - CASE - WHEN INSTR(Exception, ':') > 0 + CASE + WHEN INSTR(Exception, ':') > 0 THEN SUBSTR(Exception, INSTR(Exception, ':') + 2) ELSE Exception END -- cgit v1.2.3 From ff2c651aeed76b070969a9ce55b0c170c1ec9fb8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Jul 2026 19:04:22 -0500 Subject: couple tweaks --- src/slskd/Telemetry/ReportsService.cs | 4 ++-- src/web/src/components/Dashboard/Dashboard.jsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index e0304d2a..adc2febf 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -181,8 +181,8 @@ public class ReportsService StateDescription, SUM(Size) AS TotalBytes, COUNT(*) AS Count, - COUNT(DISTINCT Username) AS Users, - AVG(AverageSpeed) AS AverageSpeed, + COUNT(DISTINCT Username) AS DistinctUsers, + CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0) 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 diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 8043ab0b..302e0f0a 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -50,7 +50,7 @@ const Dashboard = ({ server } = {}) => { start: range.days != null ? new Date(now - range.days * 86_400_000).toISOString() - : null, + : new Date(0).toISOString(), }; }, [historyLabel]); -- cgit v1.2.3 From 81447958c009ed395d8fe68d27c6c6b6f5a3d2f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Jul 2026 15:21:06 -0500 Subject: add mutually exclusive 'buckets' parameter to histogram --- src/slskd/Telemetry/ReportsService.cs | 65 +++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 10 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index adc2febf..ed5f0416 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -137,32 +137,77 @@ public class ReportsService } /// - /// 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. + /// Returns a histogram of all transfer data, aggregated into either fixed size time intervals or a fixed + /// number of evenly sized buckets, 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 interval for the histogram. Mutually exclusive with ; exactly one must + /// be specified. + /// + /// + /// The number of evenly sized buckets into which the histogram window should be divided. Mutually + /// exclusive with ; exactly one must be specified. + /// /// 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. + /// + /// Thrown if either or is default, if both + /// and are specified, if neither is specified. + /// + /// + /// Thrown if is not later than , or if + /// is outside of the allowed range. + /// public Dictionary>> GetTransferHistogram( DateTime start, DateTime end, - TimeSpan interval, + TimeSpan? interval = null, + int? buckets = null, TransferDirection? direction = null, string username = null) { + if (start == default || end == default) + { + throw new ArgumentException("Start and end times are both required"); + } + if (end <= start) { - throw new ArgumentException("End time must be later than start time"); + throw new ArgumentOutOfRangeException(nameof(end), "End time must be later than start time"); + } + + if (interval.HasValue && buckets.HasValue) + { + throw new ArgumentException("Interval and buckets are mutually exclusive, provide one or the other, not both"); + } + + if (!interval.HasValue && !buckets.HasValue) + { + throw new ArgumentException("Either interval or buckets must be supplied"); } + if (buckets.HasValue && (buckets.Value > 5000 || buckets.Value < 1)) + { + throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 5000"); + } + + if (interval.HasValue && interval.Value <= TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be greater than zero"); + } + + // if interval was provided, just use that. otherwise, compute the interval from the seconds between start and end + // divided by the desired buckets + var effectiveInterval = interval ?? TimeSpan.FromSeconds(Math.Max(1, (long)(end - start).TotalSeconds / buckets!.Value)); + 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); + var currentInterval = new DateTime(start.Ticks / effectiveInterval.Ticks * effectiveInterval.Ticks, DateTimeKind.Utc); while (currentInterval < end) { @@ -171,7 +216,7 @@ public class ReportsService { TransferDirection.Download, new Dictionary() }, { TransferDirection.Upload, new Dictionary() }, }; - currentInterval = currentInterval.Add(interval); + currentInterval = currentInterval.Add(effectiveInterval); } var sql = @$" @@ -203,7 +248,7 @@ public class ReportsService Username = username, Start = start, End = end, - Interval = (int)interval.TotalSeconds, + Interval = (int)effectiveInterval.TotalSeconds, }; var results = connection.Query(sql, param); @@ -223,7 +268,7 @@ public class ReportsService 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); + var bucketInterval = new DateTime(result.Interval.Value.Ticks / effectiveInterval.Ticks * effectiveInterval.Ticks, DateTimeKind.Utc); if (dict.TryGetValue(bucketInterval, out var intervalDict)) { -- cgit v1.2.3 From c903bf5f13f7ac1cc9e4e9cdb514665f5dfe8417 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 16:23:28 -0500 Subject: cap buckets at 1000 --- src/slskd/Telemetry/ReportsService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index ed5f0416..d7baa3f0 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -190,7 +190,7 @@ public class ReportsService throw new ArgumentException("Either interval or buckets must be supplied"); } - if (buckets.HasValue && (buckets.Value > 5000 || buckets.Value < 1)) + if (buckets.HasValue && (buckets.Value > 1000 || buckets.Value < 1)) { throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 5000"); } -- cgit v1.2.3 From 1dd9e34d446338ebf071d35ea7c8a1ecb995bc57 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 16:24:49 -0500 Subject: validation, coalescing, etc --- src/slskd/Telemetry/API/ReportsController.cs | 47 +++++++++++++++++++++------- 1 file changed, 36 insertions(+), 11 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index 5ced2def..e2bf5963 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -40,6 +40,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; +using slskd.Transfers; using Soulseek; /// @@ -55,12 +56,16 @@ public class ReportsController : ControllerBase /// /// Initializes a new instance of the class. /// - public ReportsController(TelemetryService telemetryService) + public ReportsController( + TelemetryService telemetryService, + TransferService transferService) { Telemetry = telemetryService; + Transfers = transferService; } private TelemetryService Telemetry { get; } + private TransferService Transfers { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// @@ -128,7 +133,8 @@ public class ReportsController : ControllerBase /// /// The start time of the window (default: 7 days ago). /// The end time of the window (default: now). - /// The interval, in minutes (default: 60). + /// The number of evenly sized buckets that the data will be divided into (default: 100). + /// The interval, in minutes (default: null). /// An optional direction (Upload, Download) by which to filter records. /// An optional username by which to filter records. /// @@ -143,7 +149,8 @@ public class ReportsController : ControllerBase public IActionResult GetTransferHistogram( [FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null, - [FromQuery] int interval = 60, + [FromQuery] int? buckets = null, + [FromQuery] int? interval = null, [FromQuery] string direction = null, [FromQuery] string username = null) { @@ -157,20 +164,37 @@ public class ReportsController : 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) + if (buckets.HasValue && interval.HasValue) + { + return BadRequest("Specify either interval or buckets, not both"); + } + + if (buckets.HasValue && (buckets < 1 || buckets > 1000)) { - 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; + return BadRequest("Buckets must be between 1 and 1000, if specified"); } - if (interval < 5) + if (interval.HasValue && interval < 1) { - return BadRequest("Interval must be greater than or equal to 5"); + return BadRequest("Interval must be greater than 1"); } - var intervalTimeSpan = TimeSpan.FromMinutes(interval); + if (!buckets.HasValue && !interval.HasValue) + { + buckets = 100; // the default, according to API docs. update the docs if this changes + } + + // at this point it is either buckets or interval, and both would have valid values, so convert + // interval to a timespan if it exists and send both values into the service, it will sort things out + TimeSpan? intervalTimeSpan = !buckets.HasValue ? TimeSpan.FromMinutes(interval.Value) : null; + + // if a caller supplies a start timestamp that is equal to, or is earlier than the genesis time for slskd (12/30/2020 6:22:00 UTC) + // then replace the provided timestamp with the oldest transfer record (regardless of direction); there's no data older than that + // and this will let the caller avoid a bunch of empty series on their histogram + if (start < Program.GenesisDateTime) + { + start = Transfers.Query(q => q.Min(t => t.RequestedAt)) ?? Program.GenesisDateTime; + } TransferDirection? transferDirection = null; @@ -189,6 +213,7 @@ public class ReportsController : ControllerBase return Ok(Telemetry.Reports.GetTransferHistogram( start: start.Value, end: end.Value, + buckets: buckets, interval: intervalTimeSpan, direction: transferDirection, username: username)); -- cgit v1.2.3 From ac972c0c2578e6c532a22ec489672071be1cf02b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 22:04:04 -0500 Subject: tweaks --- src/slskd/Telemetry/API/ReportsController.cs | 2 +- src/slskd/Telemetry/ReportsService.cs | 4 ++-- src/web/src/lib/reports.js | 14 -------------- src/web/src/lib/reports.test.js | 8 ++++---- 4 files changed, 7 insertions(+), 21 deletions(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index e2bf5963..6192a4bd 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -193,7 +193,7 @@ public class ReportsController : ControllerBase // and this will let the caller avoid a bunch of empty series on their histogram if (start < Program.GenesisDateTime) { - start = Transfers.Query(q => q.Min(t => t.RequestedAt)) ?? Program.GenesisDateTime; + start = Transfers.Query(q => q.Select(t => (DateTime?)t.RequestedAt).Min()) ?? Program.GenesisDateTime; } TransferDirection? transferDirection = null; diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index d7baa3f0..965b95d0 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -192,7 +192,7 @@ public class ReportsService if (buckets.HasValue && (buckets.Value > 1000 || buckets.Value < 1)) { - throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 5000"); + throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 1000"); } if (interval.HasValue && interval.Value <= TimeSpan.Zero) @@ -227,7 +227,7 @@ public class ReportsService SUM(Size) AS TotalBytes, COUNT(*) AS Count, COUNT(DISTINCT Username) AS DistinctUsers, - CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0) AS AverageSpeed, + COALESCE(CAST(SUM(Size) AS REAL) / NULLIF(SUM(strftime('%s', EndedAt) - strftime('%s', StartedAt)), 0), 0.0) 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 diff --git a/src/web/src/lib/reports.js b/src/web/src/lib/reports.js index 17c6d214..9815fa9c 100644 --- a/src/web/src/lib/reports.js +++ b/src/web/src/lib/reports.js @@ -131,17 +131,3 @@ export const getExceptionPareto = async ({ ) ).data; }; - -export const getUserDetails = async ({ - username, - start = null, - end = null, -} = {}) => { - const parameters = new URLSearchParams(); - - parameters.append('username', username); - parameters.append('start', start); - parameters.append('end', end); - - return (await api.get(`/telemetry/reports/transfers/users/${username}`)).data; -}; diff --git a/src/web/src/lib/reports.test.js b/src/web/src/lib/reports.test.js index d4b3dece..2b73fdca 100644 --- a/src/web/src/lib/reports.test.js +++ b/src/web/src/lib/reports.test.js @@ -74,9 +74,9 @@ describe('reports', () => { expect(paramsOf().get('end')).toBe(end.toISOString()); }); - it('appends interval when provided', async () => { - await reports.getHistogram({ interval: 360 }); - expect(paramsOf().get('interval')).toBe('360'); + it('appends buckets when provided', async () => { + await reports.getHistogram({ buckets: 50 }); + expect(paramsOf().get('buckets')).toBe('50'); }); it('appends direction when provided', async () => { @@ -94,7 +94,7 @@ describe('reports', () => { const p = paramsOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); - expect(p.has('interval')).toBe(false); + expect(p.has('buckets')).toBe(false); expect(p.has('direction')).toBe(false); expect(p.has('username')).toBe(false); }); -- cgit v1.2.3 From 3313514f7793c40d9377f67aebbd832eb8daf822 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 10:25:35 -0500 Subject: tweak some guards in reports controller --- src/slskd/Telemetry/API/ReportsController.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index 6192a4bd..ccb45daf 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -164,6 +164,11 @@ public class ReportsController : ControllerBase return BadRequest("End time must be later than start time"); } + if (end < Program.GenesisDateTime) + { + return BadRequest($"End time impossibly early (earlier than slskd genesis time {Program.GenesisDateTime})"); + } + if (buckets.HasValue && interval.HasValue) { return BadRequest("Specify either interval or buckets, not both"); @@ -174,7 +179,7 @@ public class ReportsController : ControllerBase return BadRequest("Buckets must be between 1 and 1000, if specified"); } - if (interval.HasValue && interval < 1) + if (interval.HasValue && interval <= 1) { return BadRequest("Interval must be greater than 1"); } -- cgit v1.2.3 From 5bc50e07cfb9d2bdbc0c8f90d6a6eda24158076e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 10:26:58 -0500 Subject: remove StartOffset --- .../Telemetry/Types/TransferExceptionDetail.cs | 1 - .../components/Dashboard/HistoricalStatistics.jsx | 8 +- src/web/src/components/Dashboard/Leaderboard.jsx | 7 +- src/web/src/components/Dashboard/SearchBar.jsx | 6 +- .../src/components/Dashboard/TransferErrors.jsx | 48 +++++----- src/web/src/components/Shared/Graph.jsx | 19 +--- src/web/src/lib/util.js | 6 ++ .../Telemetry/ReportsServiceTests.cs | 104 +++++++++++++++++++++ 8 files changed, 148 insertions(+), 51 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs index af20cc63..ea0b2a67 100644 --- a/src/slskd/Telemetry/Types/TransferExceptionDetail.cs +++ b/src/slskd/Telemetry/Types/TransferExceptionDetail.cs @@ -42,7 +42,6 @@ public record TransferExceptionDetail 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; } diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index c14649c4..a640fc1b 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -1,4 +1,4 @@ -import { formatBytes, formatSpeed } from '../../lib/util'; +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; import { Graph, LoaderSegment } from '../Shared'; import Leaderboard from './Leaderboard'; import TopDirectories from './TopDirectories'; @@ -32,12 +32,6 @@ const errorCount = (directionData = {}) => (directionData.Cancelled?.count ?? 0) + (directionData.TimedOut?.count ?? 0); -const formatWait = (seconds) => { - if (!seconds || seconds === 0) return '0s'; - if (seconds < 60) return `${Math.round(seconds)}s`; - return `${(seconds / 60).toFixed(1)}m`; -}; - const buildChartData = (histogram) => Object.entries(histogram) .sort(([a], [b]) => new Date(a) - new Date(b)) diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index 4a37870c..a3df7d2c 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -1,6 +1,6 @@ import * as reports from '../../lib/reports'; import { formatBytes, formatSpeed } from '../../lib/util'; -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; const SORT_FIELDS = [ @@ -108,6 +108,7 @@ const initialState = { const Leaderboard = ({ downloads, end, start, uploads }) => { const [state, setState] = useState(initialState); + const sortRef = useRef(null); useEffect(() => { setState((previous) => ({ @@ -120,6 +121,8 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { const onSort = async (sort) => { if (sort === state.sortBy) return; + sortRef.current = sort; + setState((previous) => ({ ...previous, sortBy: sort, @@ -151,6 +154,8 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { console.error(error); } + if (sortRef.current !== sort) return; + setState((previous) => ({ ...previous, rows: { upload: newUploads, download: newDownloads }, diff --git a/src/web/src/components/Dashboard/SearchBar.jsx b/src/web/src/components/Dashboard/SearchBar.jsx index e8c0b7e4..43e7d18a 100644 --- a/src/web/src/components/Dashboard/SearchBar.jsx +++ b/src/web/src/components/Dashboard/SearchBar.jsx @@ -1,7 +1,7 @@ import '../Search/Search.css'; import { urlBase } from '../../config'; import * as library from '../../lib/searches'; -import React, { useRef, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { toast } from 'react-toastify'; import { Button, Icon, Input, Segment } from 'semantic-ui-react'; @@ -48,7 +48,9 @@ const SearchBar = ({ server } = {}) => { } }; - inputRef?.current?.inputRef?.current?.focus(); + useEffect(() => { + inputRef?.current?.inputRef?.current?.focus(); + }, []); return ( { setParetoDirection(d); setParetoLoading(true); - if (d === 'All') { - const [uploadRows, downloadRows] = await Promise.all([ - fetchPareto('Upload'), - fetchPareto('Download'), - ]); - setParetoRows(buildParetoRows(uploadRows, downloadRows)); - } else { - const rows = await fetchPareto(d); - setParetoRows(rows.map((r) => ({ ...r, direction: d }))); + try { + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchPareto('Upload'), + fetchPareto('Download'), + ]); + setParetoRows(buildParetoRows(uploadRows, downloadRows)); + } else { + const rows = await fetchPareto(d); + setParetoRows(rows.map((r) => ({ ...r, direction: d }))); + } + } finally { + setParetoLoading(false); } - - setParetoLoading(false); }; const onRecentDirectionChange = async (d) => { setRecentDirection(d); setRecentLoading(true); - if (d === 'All') { - const [uploadRows, downloadRows] = await Promise.all([ - fetchRecent('Upload'), - fetchRecent('Download'), - ]); - setRecentRows(mergeRecent(uploadRows, downloadRows)); - } else { - const rows = await fetchRecent(d); - setRecentRows(rows.map((r) => ({ ...r, direction: d }))); + try { + if (d === 'All') { + const [uploadRows, downloadRows] = await Promise.all([ + fetchRecent('Upload'), + fetchRecent('Download'), + ]); + setRecentRows(mergeRecent(uploadRows, downloadRows)); + } else { + const rows = await fetchRecent(d); + setRecentRows(rows.map((r) => ({ ...r, direction: d }))); + } + } finally { + setRecentLoading(false); } - - setRecentLoading(false); }; return ( diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index 4d672d3d..0f753b72 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -1,3 +1,4 @@ +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; import React, { useEffect, useMemo, useState } from 'react'; import { Area, @@ -26,24 +27,6 @@ export const useDarkMode = () => { return isDark; }; -const formatBytes = (bytes) => { - if (!bytes || bytes === 0) return '0 B'; - const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; - const index = Math.floor(Math.log(bytes) / Math.log(1_024)); - return `${(bytes / 1_024 ** index).toFixed(1)} ${units[index]}`; -}; - -const formatSpeed = (bytesPerSecond) => { - if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; - return `${formatBytes(bytesPerSecond)}/s`; -}; - -const formatWait = (seconds) => { - if (!seconds || seconds === 0) return '0s'; - if (seconds < 60) return `${Math.round(seconds)}s`; - return `${(seconds / 60).toFixed(1)}m`; -}; - const UNIT_FORMATTERS = { bytes: formatBytes, count: (v) => v.toLocaleString(), diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index b499f81e..854e625e 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -44,6 +44,12 @@ export const formatSpeed = (bytesPerSecond, decimals = 1) => { return `${formatBytes(bytesPerSecond, decimals)}/s`; }; +export const formatWait = (seconds) => { + if (!seconds || seconds === 0) return '0s'; + if (seconds < 60) return `${Math.round(seconds)}s`; + return `${(seconds / 60).toFixed(1)}m`; +}; + export const formatDate = (date) => { return new Date(date).toLocaleString(); }; diff --git a/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs b/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs new file mode 100644 index 00000000..9173b0e9 --- /dev/null +++ b/tests/slskd.Tests.Unit/Telemetry/ReportsServiceTests.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Dapper; +using Microsoft.Data.Sqlite; +using slskd.Telemetry; +using Soulseek; +using Xunit; + +namespace slskd.Tests.Unit.Telemetry; + +public class ReportsServiceTests : IDisposable +{ + private readonly SqliteConnection _anchor; + private readonly string _connectionString; + + public ReportsServiceTests() + { + var dbName = $"test_{Guid.NewGuid():N}"; + _connectionString = $"Data Source={dbName};Mode=Memory;Cache=Shared"; + + _anchor = new SqliteConnection(_connectionString); + _anchor.Open(); + + _anchor.Execute(@" + CREATE TABLE Transfers ( + Id TEXT PRIMARY KEY, + Username TEXT NOT NULL, + Direction TEXT NOT NULL, + Filename TEXT NOT NULL, + Size INTEGER NOT NULL DEFAULT 0, + State INTEGER NOT NULL DEFAULT 0, + StateDescription TEXT, + RequestedAt TEXT, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL DEFAULT 0, + AverageSpeed REAL NOT NULL DEFAULT 0.0, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL DEFAULT 0, + BatchId TEXT, + Attempts INTEGER NOT NULL DEFAULT 0, + NextAttemptAt TEXT + )"); + } + + public void Dispose() + { + _anchor.Dispose(); + } + + private ReportsService CreateService() => + new(new ConnectionStringDictionary( + new Dictionary { { Database.Transfers, _connectionString } })); + + [Fact] + public void GetTransferHistogram_DropsTransfersInFirstPartialBucket_WhenStartIsNotOnUnixBucketBoundary() + { + // start = 2026-01-04T00:00:00Z has Unix-epoch offset mod 6048 = 4320 seconds, + // so the first SQL bucket floor-snaps to 2026-01-03T22:33:36Z. The C# re-snap + // of that datetime gives 2026-01-03T21:07:12Z — a full 6048 s before the C# + // pre-fill first key (2026-01-03T22:48:00Z) — so TryGetValue misses and the + // transfer is silently dropped. + var state = TransferStates.Completed | TransferStates.Succeeded; + + _anchor.Execute(@" + INSERT INTO Transfers (Id, Username, Direction, Filename, Size, State, StateDescription, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed) + VALUES (@Id, @Username, @Direction, @Filename, @Size, @State, @StateDescription, + @RequestedAt, @EnqueuedAt, @StartedAt, @EndedAt, @BytesTransferred, @AverageSpeed)", + new + { + Id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + Username = "testuser", + Direction = TransferDirection.Upload.ToString(), + Filename = "test.mp3", + Size = 1_048_576L, + State = (int)state, + StateDescription = state.ToString(), + RequestedAt = "2026-01-04 00:00:00", + EnqueuedAt = "2026-01-04 00:00:00", + StartedAt = "2026-01-04 00:01:00", + EndedAt = "2026-01-04 00:10:00", + BytesTransferred = 1_048_576L, + AverageSpeed = 1748.0, + }); + + var sut = CreateService(); + + var start = new DateTime(2026, 1, 4, 0, 0, 0, DateTimeKind.Utc); + var end = new DateTime(2026, 1, 11, 0, 0, 0, DateTimeKind.Utc); + + var histogram = sut.GetTransferHistogram(start: start, end: end, buckets: 100); + + var totalCount = histogram.Values + .SelectMany(directions => directions.Values) + .SelectMany(states => states.Values) + .Sum(summary => summary.Count); + + Assert.Equal(1, totalCount); + } +} -- cgit v1.2.3 From ada8c819946892bf680fc59202f2620f1aba4368 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 12:39:03 -0500 Subject: add tests for GetTransferHistogram --- src/slskd/Telemetry/ReportsService.cs | 8 +- .../ReportsService/GetTransferHistogramTests.cs | 724 +++++++++++++++++++++ 2 files changed, 729 insertions(+), 3 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Telemetry/ReportsService/GetTransferHistogramTests.cs (limited to 'src/slskd/Telemetry') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index 965b95d0..7cd245bf 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -207,7 +207,10 @@ public class ReportsService var dict = new Dictionary>>(); // fill the dictionary with gapless intervals and empty dictionaries - var currentInterval = new DateTime(start.Ticks / effectiveInterval.Ticks * effectiveInterval.Ticks, DateTimeKind.Utc); + // snap to Unix epoch to match the SQL bucket formula: strftime('%s', ...) / interval * interval, otherwise + // we may end up with an empty/partial first bucket + var intervalSeconds = (long)effectiveInterval.TotalSeconds; + var currentInterval = DateTime.UnixEpoch.AddSeconds((long)(start - DateTime.UnixEpoch).TotalSeconds / intervalSeconds * intervalSeconds); while (currentInterval < end) { @@ -267,8 +270,7 @@ public class ReportsService if (result.Interval.HasValue) { - // normalize the result interval to match the bucket interval - var bucketInterval = new DateTime(result.Interval.Value.Ticks / effectiveInterval.Ticks * effectiveInterval.Ticks, DateTimeKind.Utc); + var bucketInterval = DateTime.SpecifyKind(result.Interval.Value, DateTimeKind.Utc); if (dict.TryGetValue(bucketInterval, out var intervalDict)) { diff --git a/tests/slskd.Tests.Unit/Telemetry/ReportsService/GetTransferHistogramTests.cs b/tests/slskd.Tests.Unit/Telemetry/ReportsService/GetTransferHistogramTests.cs new file mode 100644 index 00000000..fe51e6bd --- /dev/null +++ b/tests/slskd.Tests.Unit/Telemetry/ReportsService/GetTransferHistogramTests.cs @@ -0,0 +1,724 @@ +namespace slskd.Tests.Unit.Telemetry; + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using slskd.Telemetry; +using slskd.Transfers; +using Soulseek; +using Xunit; + +public class GetTransferHistogramTests +{ + // Use 2024-01-01T00:00:00Z as the base start time. Its Unix timestamp (1704067200) + // is exactly divisible by 3600, so hour-aligned bucket keys snap cleanly to the + // expected boundaries without off-by-one surprises. + private static readonly DateTime Start = new(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime End = new(2024, 1, 1, 3, 0, 0, DateTimeKind.Utc); + + // ── Argument validation ──────────────────────────────────────────────────── + + [Fact] + public void Throws_ArgumentException_When_Start_Is_Default() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(default, End, buckets: 3)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentException_When_End_Is_Default() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, default, buckets: 3)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_End_Equals_Start() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, Start, buckets: 3)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_End_Is_Before_Start() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(End, Start, buckets: 3)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentException_When_Both_Interval_And_Buckets_Are_Provided() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => + sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1), buckets: 3)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentException_When_Neither_Interval_Nor_Buckets_Are_Provided() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_Buckets_Exceeds_1000() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, buckets: 1001)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_Buckets_Is_Zero() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, buckets: 0)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_Buckets_Is_Negative() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, buckets: -1)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_Interval_Is_Zero() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, interval: TimeSpan.Zero)); + Assert.IsType(ex); + } + + [Fact] + public void Throws_ArgumentOutOfRangeException_When_Interval_Is_Negative() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => + sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromSeconds(-1))); + Assert.IsType(ex); + } + + [Fact] + public void Does_Not_Throw_When_Buckets_Is_1() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, buckets: 1)); + Assert.Null(ex); + } + + [Fact] + public void Does_Not_Throw_When_Buckets_Is_1000() + { + var (_, sut) = GetFixture(); + var ex = Record.Exception(() => sut.GetTransferHistogram(Start, End, buckets: 1000)); + Assert.Null(ex); + } + + // ── Bucket structure ─────────────────────────────────────────────────────── + + [Fact] + public void Returns_Three_Bucket_Keys_For_Three_Hour_Window_With_Three_Buckets() + { + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, buckets: 3); + Assert.Equal(3, histogram.Count); + } + + [Fact] + public void Returns_Three_Bucket_Keys_For_Three_Hour_Window_With_One_Hour_Interval() + { + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + Assert.Equal(3, histogram.Count); + } + + [Fact] + public void Bucket_Keys_Are_Spaced_By_The_Configured_Interval() + { + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + var keys = histogram.Keys.OrderBy(k => k).ToList(); + + Assert.Equal(TimeSpan.FromHours(1), keys[1] - keys[0]); + Assert.Equal(TimeSpan.FromHours(1), keys[2] - keys[1]); + } + + [Fact] + public void All_Buckets_Contain_Entries_For_Both_Upload_And_Download_Directions() + { + // Gapless pre-fill must include both directions even for empty buckets. + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, buckets: 3); + + foreach (var bucket in histogram.Values) + { + Assert.True(bucket.ContainsKey(TransferDirection.Upload)); + Assert.True(bucket.ContainsKey(TransferDirection.Download)); + } + } + + [Fact] + public void All_Buckets_Contain_Empty_State_Dictionaries_When_No_Data() + { + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, buckets: 3); + + foreach (var bucket in histogram.Values) + { + Assert.Empty(bucket[TransferDirection.Upload]); + Assert.Empty(bucket[TransferDirection.Download]); + } + } + + [Fact] + public void First_Bucket_Key_Is_Not_Later_Than_Start() + { + // The first bucket must cover Start; it may be snapped earlier due to epoch alignment. + var (_, sut) = GetFixture(); + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + Assert.True(histogram.Keys.Min() <= Start); + } + + [Fact] + public void Interval_And_Equivalent_Buckets_Count_Produce_Same_Number_Of_Bucket_Keys() + { + // 3 buckets over 3 hours computes an effective interval of 3600 s — same as + // specifying the interval explicitly. + var (_, sut) = GetFixture(); + + var byBuckets = sut.GetTransferHistogram(Start, End, buckets: 3); + var byInterval = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + + Assert.Equal(byInterval.Count, byBuckets.Count); + } + + // ── Time window filtering ────────────────────────────────────────────────── + + [Fact] + public void Excludes_Transfer_Whose_EndedAt_Is_Before_Start() + { + var (mocks, sut) = GetFixture(); + mocks.Insert(startedAt: Start.AddHours(-2), endedAt: Start.AddSeconds(-1)); + + Assert.Equal(0, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Excludes_Transfer_Whose_EndedAt_Is_After_End() + { + var (mocks, sut) = GetFixture(); + mocks.Insert(startedAt: Start.AddMinutes(10), endedAt: End.AddSeconds(1)); + + Assert.Equal(0, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Includes_Transfer_Whose_EndedAt_Is_Within_Window() + { + var (mocks, sut) = GetFixture(); + mocks.Insert(startedAt: Start.AddMinutes(10), endedAt: Start.AddMinutes(30)); + + Assert.Equal(1, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Includes_Transfer_Whose_EndedAt_Is_One_Second_Before_End() + { + var (mocks, sut) = GetFixture(); + mocks.Insert(startedAt: End.AddMinutes(-10), endedAt: End.AddSeconds(-1)); + + Assert.Equal(1, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Excludes_Transfer_Whose_EndedAt_Is_Exactly_At_End() + { + // SQLite BETWEEN is inclusive, so the FILTER passes, but the bucket formula + // strftime('%s', EndedAt) / interval * interval + // snaps EndedAt == End to a bucket that starts AT End. The C# pre-fill loop + // (`while (currentInterval < end)`) never adds that bucket, so TryGetValue + // misses and the result is silently dropped. End is an exclusive upper bound + // in practice despite the inclusive BETWEEN clause. + var (mocks, sut) = GetFixture(); + mocks.Insert(startedAt: End.AddMinutes(-10), endedAt: End); + + Assert.Equal(0, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Excludes_Transfer_With_Null_EndedAt() + { + // The query requires EndedAt IS NOT NULL. A completed-state transfer whose + // EndedAt was somehow never set should still be excluded. + var (mocks, sut) = GetFixture(); + mocks.Insert( + startedAt: Start.AddMinutes(10), + endedAt: null, + state: TransferStates.Completed | TransferStates.Succeeded); + + Assert.Equal(0, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + // ── State filtering ──────────────────────────────────────────────────────── + + [Fact] + public void Excludes_Transfer_With_Non_Completed_State() + { + // InProgress (8) is not in TransferStateCategories.Completed, so even if the + // record has a non-null EndedAt it must be excluded by the State IN filter. + var (mocks, sut) = GetFixture(); + mocks.Insert( + startedAt: Start.AddMinutes(10), + endedAt: Start.AddMinutes(30), + state: TransferStates.InProgress); + + Assert.Equal(0, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Includes_Succeeded_Transfers() + { + var (mocks, sut) = GetFixture(); + mocks.Insert( + startedAt: Start.AddMinutes(10), + endedAt: Start.AddMinutes(30), + state: TransferStates.Completed | TransferStates.Succeeded); + + Assert.Equal(1, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + [Fact] + public void Includes_Failed_Transfers_Of_All_Terminal_States() + { + // Errored, Cancelled, TimedOut, Rejected, and Aborted are all in + // TransferStateCategories.Completed and must be included. + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Errored); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Cancelled); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.TimedOut); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Rejected); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Aborted); + + Assert.Equal(5, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + // ── Data aggregation ─────────────────────────────────────────────────────── + + [Fact] + public void TotalBytes_Is_Sum_Of_Size_Across_All_Transfers_In_Bucket() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, size: 1_000); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, size: 2_000); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, size: 3_000); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(6_000, summary.TotalBytes); + } + + [Fact] + public void Count_Is_Number_Of_Transfers_In_Bucket() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(3, summary.Count); + } + + [Fact] + public void DistinctUsers_Counts_Only_Unique_Usernames_Not_Transfer_Count() + { + // 3 transfers from 2 users → DistinctUsers should be 2, not 3. + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(username: "alice", startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(username: "alice", startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(username: "bob", startedAt: t.AddMinutes(-5), endedAt: t); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(2, summary.DistinctUsers); + } + + [Fact] + public void AverageSpeed_Is_Total_Bytes_Divided_By_Total_Duration_Seconds() + { + // The query computes SUM(Size) / SUM(duration_seconds) — aggregate throughput, + // not the average of each transfer's individual speed. + // + // Two transfers each lasting 60 s: + // - 600 bytes → 10 B/s + // - 1 200 bytes → 20 B/s + // Aggregate: 1 800 bytes / 120 s = 15 B/s + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddSeconds(-60), endedAt: t, size: 600); + mocks.Insert(startedAt: t.AddSeconds(-60), endedAt: t, size: 1_200); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(15.0, summary.AverageSpeed, precision: 2); + } + + [Fact] + public void AverageSpeed_Is_Zero_When_All_Transfers_Have_Zero_Duration() + { + // When StartedAt == EndedAt the total duration is 0. The query uses + // NULLIF(SUM(duration), 0) to avoid division by zero, and COALESCE returns 0.0. + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t, endedAt: t, size: 1_000_000); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(0.0, summary.AverageSpeed); + } + + [Fact] + public void AverageWait_Is_Mean_Seconds_Between_EnqueuedAt_And_StartedAt() + { + // Transfer A: enqueued 70 s before started → waited 60 s (started 10 s before ended) + // Transfer B: enqueued 130 s before started → waited 120 s + // Average: (60 + 120) / 2 = 90 s + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(enqueuedAt: t.AddSeconds(-70), startedAt: t.AddSeconds(-10), endedAt: t); + mocks.Insert(enqueuedAt: t.AddSeconds(-130), startedAt: t.AddSeconds(-10), endedAt: t); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(90.0, summary.AverageWait, precision: 1); + } + + [Fact] + public void AverageDuration_Is_Mean_Seconds_Between_StartedAt_And_EndedAt() + { + // Transfer A: ran 60 s; Transfer B: ran 120 s → average 90 s + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddSeconds(-60), endedAt: t); + mocks.Insert(startedAt: t.AddSeconds(-120), endedAt: t); + + var summary = histogram(sut).Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(90.0, summary.AverageDuration, precision: 1); + } + + // ── Grouping ─────────────────────────────────────────────────────────────── + + [Fact] + public void Uploads_And_Downloads_In_Same_Bucket_Are_In_Separate_Direction_Entries() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(direction: TransferDirection.Upload, startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(direction: TransferDirection.Download, startedAt: t.AddMinutes(-5), endedAt: t); + + var bucket = histogram(sut).Values.Single(); + + Assert.Equal(1, bucket[TransferDirection.Upload].Values.Sum(s => s.Count)); + Assert.Equal(1, bucket[TransferDirection.Download].Values.Sum(s => s.Count)); + } + + [Fact] + public void Different_Terminal_States_In_Same_Bucket_And_Direction_Are_Separate_Keys() + { + // A succeeded and an errored upload in the same bucket must appear as two + // separate entries in the direction's state dictionary, not aggregated together. + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Succeeded); + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Errored); + + var uploadStates = histogram(sut).Values.Single()[TransferDirection.Upload]; + + Assert.Equal(2, uploadStates.Count); + Assert.True(uploadStates.ContainsKey(TransferStates.Succeeded)); + Assert.True(uploadStates.ContainsKey(TransferStates.Errored)); + } + + [Fact] + public void State_Key_Has_The_Completed_Flag_Stripped() + { + // The code maps state keys via `StateDescription & ~TransferStates.Completed`, + // so a transfer stored as Completed|Succeeded (48) should appear under + // key TransferStates.Succeeded (32), not the combined value. + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(startedAt: t.AddMinutes(-5), endedAt: t, + state: TransferStates.Completed | TransferStates.Succeeded); + + var uploadStates = histogram(sut).Values.Single()[TransferDirection.Upload]; + + Assert.True(uploadStates.ContainsKey(TransferStates.Succeeded)); + Assert.False(uploadStates.ContainsKey(TransferStates.Completed | TransferStates.Succeeded)); + } + + // ── Direction filter ─────────────────────────────────────────────────────── + + [Fact] + public void Direction_Filter_Upload_Includes_Only_Uploads() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(direction: TransferDirection.Upload, startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(direction: TransferDirection.Download, startedAt: t.AddMinutes(-5), endedAt: t); + + var histogram = sut.GetTransferHistogram(Start, End, buckets: 1, direction: TransferDirection.Upload); + + Assert.All(histogram.Values, bucket => Assert.Empty(bucket[TransferDirection.Download])); + Assert.Equal(1, TotalCount(histogram)); + } + + [Fact] + public void Direction_Filter_Download_Includes_Only_Downloads() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(direction: TransferDirection.Upload, startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(direction: TransferDirection.Download, startedAt: t.AddMinutes(-5), endedAt: t); + + var histogram = sut.GetTransferHistogram(Start, End, buckets: 1, direction: TransferDirection.Download); + + Assert.All(histogram.Values, bucket => Assert.Empty(bucket[TransferDirection.Upload])); + Assert.Equal(1, TotalCount(histogram)); + } + + [Fact] + public void No_Direction_Filter_Includes_Both_Directions() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(direction: TransferDirection.Upload, startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(direction: TransferDirection.Download, startedAt: t.AddMinutes(-5), endedAt: t); + + var bucket = sut.GetTransferHistogram(Start, End, buckets: 1).Values.Single(); + + Assert.Equal(1, bucket[TransferDirection.Upload].Values.Sum(s => s.Count)); + Assert.Equal(1, bucket[TransferDirection.Download].Values.Sum(s => s.Count)); + } + + // ── Username filter ──────────────────────────────────────────────────────── + + [Fact] + public void Username_Filter_Includes_Only_Matching_User() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(username: "alice", startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(username: "bob", startedAt: t.AddMinutes(-5), endedAt: t); + + var histogram = sut.GetTransferHistogram(Start, End, buckets: 1, username: "alice"); + var summary = histogram.Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(1, summary.Count); + Assert.Equal(1, summary.DistinctUsers); + } + + [Fact] + public void No_Username_Filter_Includes_All_Users() + { + var (mocks, sut) = GetFixture(); + var t = Start.AddMinutes(30); + + mocks.Insert(username: "alice", startedAt: t.AddMinutes(-5), endedAt: t); + mocks.Insert(username: "bob", startedAt: t.AddMinutes(-5), endedAt: t); + + var summary = sut.GetTransferHistogram(Start, End, buckets: 1) + .Values.Single()[TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(2, summary.Count); + Assert.Equal(2, summary.DistinctUsers); + } + + // ── Bucket assignment ────────────────────────────────────────────────────── + + [Fact] + public void Transfer_Ending_At_01_30_Falls_In_01_00_Bucket_With_One_Hour_Interval() + { + // The SQL bucket formula floors each EndedAt to the nearest interval boundary: + // strftime('%s', '2024-01-01 01:30:00') / 3600 * 3600 → Unix timestamp of 01:00:00 + // So a transfer ending at 01:30 must land in the 01:00 bucket, not 00:00 or 02:00. + var (mocks, sut) = GetFixture(); + var endedAt = Start.AddMinutes(90); // 01:30:00 + + mocks.Insert(startedAt: endedAt.AddMinutes(-5), endedAt: endedAt); + + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + var bucket01 = new DateTime(2024, 1, 1, 1, 0, 0, DateTimeKind.Utc); + + Assert.True(histogram[bucket01][TransferDirection.Upload].ContainsKey(TransferStates.Succeeded)); + + // The other two buckets (00:00 and 02:00) should be empty. + var otherKeys = histogram.Keys.Where(k => k != bucket01); + foreach (var key in otherKeys) + { + Assert.Empty(histogram[key][TransferDirection.Upload]); + } + } + + [Fact] + public void Multiple_Transfers_In_Same_Bucket_Are_Aggregated_Together() + { + // Both transfers end in the 01:xx hour window → single aggregated entry in the 01:00 bucket. + var (mocks, sut) = GetFixture(); + + mocks.Insert(startedAt: Start.AddMinutes(65), endedAt: Start.AddMinutes(70), size: 1_000); + mocks.Insert(startedAt: Start.AddMinutes(75), endedAt: Start.AddMinutes(80), size: 2_000); + + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + var bucket01 = new DateTime(2024, 1, 1, 1, 0, 0, DateTimeKind.Utc); + var summary = histogram[bucket01][TransferDirection.Upload][TransferStates.Succeeded]; + + Assert.Equal(2, summary.Count); + Assert.Equal(3_000, summary.TotalBytes); + } + + [Fact] + public void Transfers_Ending_In_Different_Buckets_Are_Not_Aggregated() + { + // One transfer in hour 0, one in hour 1 — they must stay in separate buckets. + var (mocks, sut) = GetFixture(); + + mocks.Insert(startedAt: Start.AddMinutes(25), endedAt: Start.AddMinutes(30), size: 1_000); + mocks.Insert(startedAt: Start.AddMinutes(85), endedAt: Start.AddMinutes(90), size: 2_000); + + var histogram = sut.GetTransferHistogram(Start, End, interval: TimeSpan.FromHours(1)); + var bucket00 = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var bucket01 = new DateTime(2024, 1, 1, 1, 0, 0, DateTimeKind.Utc); + + Assert.Equal(1_000, histogram[bucket00][TransferDirection.Upload][TransferStates.Succeeded].TotalBytes); + Assert.Equal(2_000, histogram[bucket01][TransferDirection.Upload][TransferStates.Succeeded].TotalBytes); + } + + [Fact] + public void Single_Bucket_Aggregates_Transfers_Spread_Across_The_Window() + { + var (mocks, sut) = GetFixture(); + + mocks.Insert(startedAt: Start.AddMinutes(25), endedAt: Start.AddMinutes(30)); + mocks.Insert(startedAt: Start.AddMinutes(85), endedAt: Start.AddMinutes(90)); + mocks.Insert(startedAt: Start.AddMinutes(145), endedAt: Start.AddMinutes(150)); + + // buckets=1 puts the entire window in a single bucket + Assert.Equal(3, TotalCount(sut.GetTransferHistogram(Start, End, buckets: 1))); + } + + // ── Helpers ──────────────────────────────────────────────────────────────── + + // Shorthand to call GetTransferHistogram with the standard 3-bucket window. + private static Dictionary>> + histogram(ReportsService sut) => + sut.GetTransferHistogram(Start, End, buckets: 1); + + private static long TotalCount( + Dictionary>> h) => + h.Values + .SelectMany(d => d.Values) + .SelectMany(s => s.Values) + .Sum(summary => summary.Count); + + private static (Mocks mocks, ReportsService sut) GetFixture() + { + var mocks = new Mocks(); + var sut = new ReportsService(new ConnectionStringDictionary( + new Dictionary { { Database.Transfers, mocks.ConnectionString } })); + return (mocks, sut); + } + + private class Mocks + { + private readonly SqliteConnection _anchor; + private readonly DbContextOptions _dbContextOptions; + + public Mocks() + { + var dbName = $"hist_{Guid.NewGuid():N}"; + ConnectionString = $"Data Source={dbName};Mode=Memory;Cache=Shared"; + + // keep the shared-cache in-memory database alive for the life of this fixture + _anchor = new SqliteConnection(ConnectionString); + _anchor.Open(); + + _dbContextOptions = new DbContextOptionsBuilder() + .UseSqlite(ConnectionString) + .Options; + + // derive the schema from the EF model so column/type regressions are caught at insert time + using var context = new TransfersDbContext(_dbContextOptions); + context.Database.EnsureCreated(); + } + + public string ConnectionString { get; } + + public void Insert( + string username = "user", + TransferDirection direction = TransferDirection.Upload, + TransferStates? state = null, + DateTime? enqueuedAt = null, + DateTime? startedAt = null, + DateTime? endedAt = null, + long size = 1_000_000) + { + using var context = new TransfersDbContext(_dbContextOptions); + context.Transfers.Add(new slskd.Transfers.Transfer + { + Id = Guid.NewGuid(), + Username = username, + Direction = direction, + Filename = "file.mp3", + Size = size, + State = state ?? (TransferStates.Completed | TransferStates.Succeeded), + RequestedAt = endedAt ?? DateTime.UtcNow, + EnqueuedAt = enqueuedAt, + StartedAt = startedAt, + EndedAt = endedAt, + BytesTransferred = size, + }); + // SaveChanges sets StateDescription = State.ToString() via the DbContext override + context.SaveChanges(); + } + } +} -- cgit v1.2.3