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 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