From da96e0dce5fa398dab65b6085bc4d040001bf70a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 21 Jun 2026 15:44:03 +0000 Subject: Bump form-data in /src/web Bumps and [form-data](https://github.com/form-data/form-data). These dependencies needed to be updated together. Updates `form-data` from 4.0.5 to 4.0.6 - [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md) - [Commits](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6) Updates `form-data` from 3.0.4 to 3.0.5 - [Changelog](https://github.com/form-data/form-data/blob/master/CHANGELOG.md) - [Commits](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6) --- updated-dependencies: - dependency-name: form-data dependency-version: 3.0.5 dependency-type: indirect - dependency-name: form-data dependency-version: 4.0.6 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 191d1cca..17e00d08 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -5998,16 +5998,16 @@ } }, "node_modules/axios/node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -11051,16 +11051,16 @@ } }, "node_modules/form-data": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.4.tgz", - "integrity": "sha512-f0cRzm6dkyVYV3nPoooP8XlccPQukegwhAnpoLcXy+X+A8KfpGOoXwDr9FLZd3wzgLaBGQBE3lY93Zm/i1JvIQ==", + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.5.tgz", + "integrity": "sha512-j23EibVLnp4zNXGW7LjryXYa2X6U/M96yoOX+ybZxwkYajdxRNEqYY3zhh7y0i6kfISKS2jr+EJq1YTUDEv5+w==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", + "hasown": "^2.0.4", "mime-types": "^2.1.35" }, "engines": { @@ -11661,9 +11661,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" -- cgit v1.2.3 From 651d94a28ddced7e65c005448dabce7075505625 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Jun 2026 14:11:56 -0500 Subject: stub dashboard --- src/web/src/components/Dashboard/Dashboard.jsx | 12 +++ src/web/src/components/Dashboard/SearchBar.jsx | 102 +++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 src/web/src/components/Dashboard/Dashboard.jsx create mode 100644 src/web/src/components/Dashboard/SearchBar.jsx (limited to 'src') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx new file mode 100644 index 00000000..01dd1aa0 --- /dev/null +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -0,0 +1,12 @@ +import SearchBar from './SearchBar'; +import React from 'react'; + +const Dashboard = ({ server } = {}) => { + return ( +
+ +
+ ); +}; + +export default Dashboard; diff --git a/src/web/src/components/Dashboard/SearchBar.jsx b/src/web/src/components/Dashboard/SearchBar.jsx new file mode 100644 index 00000000..e8c0b7e4 --- /dev/null +++ b/src/web/src/components/Dashboard/SearchBar.jsx @@ -0,0 +1,102 @@ +import '../Search/Search.css'; +import { urlBase } from '../../config'; +import * as library from '../../lib/searches'; +import React, { 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'; +import { v4 as uuidv4 } from 'uuid'; + +const SearchBar = ({ server } = {}) => { + const [creating, setCreating] = useState(false); + + const inputRef = useRef(); + const history = useHistory(); + + const create = async ({ navigate = false } = {}) => { + const ref = inputRef?.current?.inputRef?.current; + const searchText = ref.value; + const id = uuidv4(); + + try { + setCreating(true); + await library.create({ id, searchText }); + + ref.value = ''; + ref.focus(); + + setCreating(false); + + if (navigate) { + history.push(`${urlBase}/searches/${id}`); + } else { + const label = + searchText.length > 30 ? `${searchText.slice(0, 15)}...` : searchText; + toast.info( + + Search for ‘{label}’ started.{' '} + View results + , + ); + } + } catch (createError) { + console.error(createError); + toast.error( + createError?.response?.data ?? createError?.message ?? createError, + ); + setCreating(false); + } + }; + + inputRef?.current?.inputRef?.current?.focus(); + + return ( + +
+ +
+ + + ))} + + + + + + + {formatBytesParts(sumBytes(summary.Download ?? {})).value} + + {formatBytesParts(sumBytes(summary.Download ?? {})).unit} + + + + Downloaded ·{' '} + {sumCounts(summary.Download ?? {}).toLocaleString()} files + + + + + + {formatBytesParts(sumBytes(summary.Upload ?? {})).value} + + {formatBytesParts(sumBytes(summary.Upload ?? {})).unit} + + + + Uploaded · {sumCounts(summary.Upload ?? {}).toLocaleString()}{' '} + files + + + + + + {shareRatio !== null ? shareRatio.toFixed(2) : '—'} + + Share ratio (↑/↓) + + + + + {( + (summary.Upload?.Succeeded?.distinctUsers ?? 0) + + (summary.Download?.Succeeded?.distinctUsers ?? 0) + ).toLocaleString()} + + Distinct peers + + +
+ +
+ + onTabChange(activeIndex)} + panes={historyPanes} + /> + + )} +
+ ); +}; + +export default HistoricalStatistics; diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx new file mode 100644 index 00000000..b983dc5a --- /dev/null +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -0,0 +1,213 @@ +import * as reports from '../../lib/reports'; +import React, { useEffect, useState } from 'react'; +import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; + +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 SORT_FIELDS = [ + { label: 'Count', sort: 'Count' }, + { label: 'Total Size', sort: 'TotalBytes' }, + { label: 'Avg Speed', sort: 'AverageSpeed' }, +]; + +const sortHeaderStyle = { cursor: 'pointer', userSelect: 'none' }; + +const LeaderboardTable = ({ loading, onSort, rows, sortBy }) => ( + + + + + # + + Username + {SORT_FIELDS.map(({ label, sort }) => ( + onSort(sort)} + style={sortHeaderStyle} + textAlign="right" + > + {label} + {sortBy === sort && ( + + )} + + ))} + + + + {loading && ( + + + + + + )} + {!loading && (!rows || rows.length === 0) && ( + + + No data to display + + + )} + {!loading && + rows && + rows.map((row, index) => ( + + + {index + 1} + + {row.username} + + {row.count.toLocaleString()} + + + {formatBytes(row.totalBytes)} + + + {formatSpeed(row.averageSpeed)} + + + ))} + +
+); + +const initialState = { + sortBy: 'Count', + rows: { + upload: [], + download: [], + }, + loading: { + upload: false, + download: false, + }, +}; + +const Leaderboard = ({ downloads, end, start, uploads }) => { + const [state, setState] = useState(initialState); + + useEffect(() => { + setState((previous) => ({ + ...previous, + sortBy: 'Count', + rows: { upload: uploads, download: downloads }, + })); + }, [downloads, uploads]); + + const onSort = async (sort) => { + if (sort === state.sortBy) return; + + setState((previous) => ({ + ...previous, + sortBy: sort, + loading: { upload: true, download: true }, + })); + + const startDate = start ? new Date(start) : undefined; + const endDate = end ? new Date(end) : new Date(); + + const [newUploads, newDownloads] = await Promise.all([ + reports + .getLeaderboard({ + direction: 'Upload', + end: endDate, + sortBy: sort, + start: startDate, + }) + .catch((error) => { + console.error(error); + return state.rows.upload; + }), + reports + .getLeaderboard({ + direction: 'Download', + end: endDate, + sortBy: sort, + start: startDate, + }) + .catch((error) => { + console.error(error); + return state.rows.download; + }), + ]); + + setState((previous) => ({ + ...previous, + rows: { upload: newUploads, download: newDownloads }, + loading: { upload: false, download: false }, + })); + }; + + return ( + + +
+ Downloads +
+ +
+ + +
+ Uploads +
+ +
+
+ ); +}; + +export default Leaderboard; diff --git a/src/web/src/components/Dashboard/TopDirectories.jsx b/src/web/src/components/Dashboard/TopDirectories.jsx new file mode 100644 index 00000000..00eae5d9 --- /dev/null +++ b/src/web/src/components/Dashboard/TopDirectories.jsx @@ -0,0 +1,71 @@ +import React from 'react'; +import { Table } from 'semantic-ui-react'; + +const getLastTwoSegments = (path) => { + if (!path) { + return path; + } + + const parts = path.split(/[/\\]/u).filter((p) => p.length > 0); + + if (parts.length <= 2) { + return parts.join('/'); + } + + return parts.slice(-2).join('/'); +}; + +const TopDirectories = ({ rows }) => ( + + + + + # + + Directory + Downloads + Distinct Users + + + + {(!rows || rows.length === 0) && ( + + + No data to display. + + + )} + {rows && + rows.map((row, index) => ( + + + {index + 1} + + + {getLastTwoSegments(row.directory)} + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+); + +export default TopDirectories; diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx new file mode 100644 index 00000000..c0b79cf1 --- /dev/null +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -0,0 +1,242 @@ +import { Graph, useDarkMode } from '../Shared'; +import React, { useMemo } from 'react'; +import { Divider, Header, Table } from 'semantic-ui-react'; + +const truncate = (text, maxLength) => { + if (!text) { + return ''; + } + + if (text.length <= maxLength) { + return text; + } + + return `${text.slice(0, maxLength)}…`; +}; + +const getFilename = (path) => { + if (!path) { + return ''; + } + + const parts = path.replaceAll('\\', '/').split('/'); + return parts[parts.length - 1] || path; +}; + +const formatDateTime = (isoString) => { + if (!isoString) { + return ''; + } + + return new Date(isoString).toLocaleString(); +}; + +const mergePareto = (uploadRows, downloadRows) => { + const combined = {}; + for (const row of [...(uploadRows || []), ...(downloadRows || [])]) { + const key = row.exception ?? ''; + combined[key] = combined[key] + ? { + exception: key, + count: combined[key].count + row.count, + distinctUsers: combined[key].distinctUsers + row.distinctUsers, + } + : { ...row }; + } + + return Object.values(combined) + .sort((a, b) => b.count - a.count) + .slice(0, 10); +}; + +const mergeRecent = (uploadRows, downloadRows) => + [ + ...(uploadRows || []).map((r) => ({ ...r, direction: 'Upload' })), + ...(downloadRows || []).map((r) => ({ ...r, direction: 'Download' })), + ] + .sort((a, b) => new Date(b.endedAt) - new Date(a.endedAt)) + .slice(0, 10); + +const ERRORS_SERIES = [ + { + color: '#db2828', + format: (v) => v.toLocaleString(), + key: 'uploadErrors', + name: 'Upload Errors', + }, + { + color: '#a333c8', + format: (v) => v.toLocaleString(), + key: 'downloadErrors', + name: 'Download Errors', + }, +]; + +const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); + +const TransferErrors = ({ + chartData, + download, + historyDays, + upload, +}) => { + const isDark = useDarkMode(); + + const paretoRows = useMemo( + () => mergePareto(upload.pareto, download.pareto), + [upload.pareto, download.pareto], + ); + const recentRows = useMemo( + () => mergeRecent(upload.recent, download.recent), + [upload.recent, download.recent], + ); + + const xFormatter = (timestamp) => { + if (historyDays === 1) { + return new Date(timestamp).toLocaleTimeString(undefined, { + hour: '2-digit', + minute: '2-digit', + }); + } + + return new Date(timestamp).toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); + }; + + const maxParetoCount = + paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; + + return ( +
+
Error Count Over Time
+ v.toLocaleString()} + /> + +
+ Top Fault Types + + pareto + +
+ + + + Exception + + Count + + Distinct Users + + + + + {(!paretoRows || paretoRows.length === 0) && ( + + + No data to display. + + + )} + {paretoRows && + paretoRows.map((row) => ( + + + {truncate(row.exception, 80)} + + +
+
+
+ + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+ +
Recent Errors
+ + + + Time + Direction + Username + Filename + Exception + + + + {(!recentRows || recentRows.length === 0) && ( + + + No data to display. + + + )} + {recentRows && + recentRows.map((row) => ( + + + {formatDateTime(row.endedAt)} + + {row.direction} + {row.username} + + {getFilename(row.filename)} + + + {truncate(row.exception, 80)} + + + ))} + +
+
+ ); +}; + +export default TransferErrors; -- cgit v1.2.3 From 7bdc1e5d5f64c5095cdd7659795a535697b403e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Jun 2026 18:43:17 -0500 Subject: initial swag at a shared graph component --- src/web/src/components/Dashboard/Dashboard.jsx | 1 - .../components/Dashboard/HistoricalStatistics.jsx | 30 +-- .../src/components/Dashboard/TransferErrors.jsx | 29 +-- src/web/src/components/Shared/Graph.jsx | 284 +++++++++++++++++++++ src/web/src/components/Shared/index.js | 1 + 5 files changed, 303 insertions(+), 42 deletions(-) create mode 100644 src/web/src/components/Shared/Graph.jsx (limited to 'src') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 959df68b..a345f593 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -149,7 +149,6 @@ const Dashboard = ({ server } = {}) => { directories={data.directories} exceptions={data.exceptions} histogram={data.histogram} - historyDays={historyParameters.days} historyEnd={historyParameters.end} historyLabel={historyLabel} historyRanges={HISTORY_RANGES} diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index 91af07ae..b0963082 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -85,72 +85,84 @@ const HISTORY_SERIES = [ format: formatBytes, key: 'uploadBytes', name: 'Upload Size', + unit: 'bytes', }, { color: '#2185d0', format: formatBytes, key: 'downloadBytes', name: 'Download Size', + unit: 'bytes', }, { color: '#6435c9', format: (v) => v.toLocaleString(), key: 'uploadCount', name: 'Upload Count', + unit: 'count', }, { color: '#e03997', format: (v) => v.toLocaleString(), key: 'downloadCount', name: 'Download Count', + unit: 'count', }, { color: '#f2711c', format: formatSpeed, key: 'uploadSpeed', name: 'Upload Speed', + unit: 'speed', }, { color: '#fbbd08', format: formatSpeed, key: 'downloadSpeed', name: 'Download Speed', + unit: 'speed', }, { color: '#db2828', format: (v) => v.toLocaleString(), key: 'uploadErrors', name: 'Upload Errors', + unit: 'count', }, { color: '#a333c8', format: (v) => v.toLocaleString(), key: 'downloadErrors', name: 'Download Errors', + unit: 'count', }, { color: '#d4500a', format: (v) => `${v.toFixed(1)}%`, key: 'uploadErrorRate', name: 'Upload Error Rate', + unit: 'rate', }, { color: '#1aa9b0', format: (v) => `${v.toFixed(1)}%`, key: 'downloadErrorRate', name: 'Download Error Rate', + unit: 'rate', }, { color: '#8e44ad', format: formatWait, key: 'uploadWait', name: 'Upload Queue Wait', + unit: 'seconds', }, { color: '#b5cc18', format: (v) => v.toFixed(2), key: 'shareRatio', name: 'Share Ratio', + unit: 'ratio', }, ]; @@ -161,7 +173,6 @@ const HistoricalStatistics = ({ directories, exceptions, histogram, - historyDays, historyEnd, historyLabel, historyRanges, @@ -186,20 +197,6 @@ const HistoricalStatistics = ({ ? 'yellow' : 'red'; - const histogramTickFormatter = (timestamp) => { - if (historyDays === 1) { - return new Date(timestamp).toLocaleTimeString(undefined, { - hour: '2-digit', - minute: '2-digit', - }); - } - - return new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); - }; - const historyPanes = [ { menuItem: { content: 'Users', icon: 'users', key: 'users' }, @@ -229,7 +226,6 @@ const HistoricalStatistics = ({ @@ -338,8 +334,6 @@ const HistoricalStatistics = ({ data={chartData} defaultSeries={DEFAULT_HISTORY_SERIES} series={HISTORY_SERIES} - xFormatter={histogramTickFormatter} - yFormatter={formatBytes} /> diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index c0b79cf1..d4c9c25c 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -63,23 +63,20 @@ const ERRORS_SERIES = [ format: (v) => v.toLocaleString(), key: 'uploadErrors', name: 'Upload Errors', + unit: 'count', }, { color: '#a333c8', format: (v) => v.toLocaleString(), key: 'downloadErrors', name: 'Download Errors', + unit: 'count', }, ]; const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); -const TransferErrors = ({ - chartData, - download, - historyDays, - upload, -}) => { +const TransferErrors = ({ chartData, download, upload }) => { const isDark = useDarkMode(); const paretoRows = useMemo( @@ -91,20 +88,6 @@ const TransferErrors = ({ [upload.recent, download.recent], ); - const xFormatter = (timestamp) => { - if (historyDays === 1) { - return new Date(timestamp).toLocaleTimeString(undefined, { - hour: '2-digit', - minute: '2-digit', - }); - } - - return new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); - }; - const maxParetoCount = paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; @@ -115,8 +98,6 @@ const TransferErrors = ({ data={chartData ?? []} defaultSeries={DEFAULT_ERRORS_SERIES} series={ERRORS_SERIES} - xFormatter={xFormatter} - yFormatter={(v) => v.toLocaleString()} />
@@ -219,7 +200,9 @@ const TransferErrors = ({ )} {recentRows && recentRows.map((row) => ( - + {formatDateTime(row.endedAt)} diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx new file mode 100644 index 00000000..d383345f --- /dev/null +++ b/src/web/src/components/Shared/Graph.jsx @@ -0,0 +1,284 @@ +import React, { useEffect, useMemo, useState } from 'react'; +import { + Area, + AreaChart, + CartesianGrid, + Legend, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from 'recharts'; + +export const useDarkMode = () => { + const [isDark, setIsDark] = useState(() => + document.documentElement.classList.contains('dark'), + ); + + useEffect(() => { + const observer = new MutationObserver(() => { + setIsDark(document.documentElement.classList.contains('dark')); + }); + observer.observe(document.documentElement, { attributeFilter: ['class'] }); + return () => observer.disconnect(); + }, []); + + 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(), + rate: (v) => `${v.toFixed(1)}%`, + ratio: (v) => v.toFixed(2), + seconds: formatWait, + speed: formatSpeed, +}; + +const mixedFormatter = (v) => { + if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`; + if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`; + if (v >= 1e3) return `${(v / 1e3).toFixed(1)}K`; + return v.toLocaleString(); +}; + +const X_TICK_COUNT = 11; +const ONE_DAY_MS = 86_400_000; + +// series: [{ key, name, color, unit?, format? }] +// key — the data key in each data point +// name — label shown in the legend and tooltip +// color — stroke / fill color +// unit — one of: 'bytes' | 'count' | 'rate' | 'ratio' | 'seconds' | 'speed' +// used to pick the Y axis formatter; omit for unitless/mixed +// format — (value) => string used in the tooltip; defaults to toLocaleString() +const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { + const isDark = useDarkMode(); + + const [visible, setVisible] = useState( + () => defaultSeries ?? new Set(series.map((s) => s.key)), + ); + + const axisStyle = useMemo( + () => ({ + fill: isDark ? '#8b949e' : '#666', + fontSize: '0.8em', + }), + [isDark], + ); + + const xRange = useMemo(() => { + if (data.length < 2) return null; + const min = data[0].timestamp; + const max = data[data.length - 1].timestamp; + return { min, max }; + }, [data]); + + const xTicks = useMemo(() => { + if (!xRange) return []; + const { max, min } = xRange; + const step = (max - min) / (X_TICK_COUNT - 1); + return Array.from({ length: X_TICK_COUNT }, (_, index) => + Math.round(min + index * step), + ); + }, [xRange]); + + const xFormatter = useMemo(() => { + if (!xRange) return String; + const isIntraday = xRange.max - xRange.min <= ONE_DAY_MS; + if (isIntraday) { + return (timestamp) => + new Date(timestamp).toLocaleTimeString(undefined, { + hour: '2-digit', + minute: '2-digit', + }); + } + + return (timestamp) => + new Date(timestamp).toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); + }, [xRange]); + + const yFormatter = useMemo(() => { + const units = series + .filter((s) => visible.has(s.key) && s.unit) + .map((s) => s.unit); + const unique = [...new Set(units)]; + return unique.length === 1 + ? UNIT_FORMATTERS[unique[0]] ?? mixedFormatter + : mixedFormatter; + }, [series, visible]); + + const toggle = (key) => { + setVisible((previous) => { + const next = new Set(previous); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + + return next; + }); + }; + + const renderTooltip = ({ active, label, payload }) => { + if (!active || !payload?.length) return null; + const bg = isDark ? '#161b22' : '#fff'; + const border = isDark ? '#30363d' : '#d0d0d0'; + const labelColor = isDark ? '#c9d1d9' : '#333'; + const valueColor = isDark ? '#8b949e' : '#666'; + return ( +
+
+ {xFormatter(label)} +
+ {payload.map((entry) => { + const s = series.find((item) => item.name === entry.name); + const formatted = s?.format + ? s.format(entry.value) + : entry.value.toLocaleString(); + return ( +
+ ▬ + {entry.name}: + {formatted} +
+ ); + })} +
+ ); + }; + + const renderLegend = ({ payload }) => ( +
+ {payload.map((entry) => ( + toggle(entry.dataKey)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + toggle(entry.dataKey); + } + }} + role="checkbox" + style={{ + alignItems: 'center', + cursor: 'pointer', + display: 'flex', + gap: '0.4em', + opacity: visible.has(entry.dataKey) ? 1 : 0.35, + }} + tabIndex={0} + > + + + + {entry.value} + + ))} +
+ ); + + return ( + + + + + + + + {series.map(({ color, key, name }) => ( + + ))} + + + ); +}; + +export default Graph; diff --git a/src/web/src/components/Shared/index.js b/src/web/src/components/Shared/index.js index 0e36bc48..6fbf167f 100644 --- a/src/web/src/components/Shared/index.js +++ b/src/web/src/components/Shared/index.js @@ -2,6 +2,7 @@ export { default as CodeEditor } from './CodeEditor'; export { default as Div } from './Div'; export { default as ErrorSegment } from './ErrorSegment'; export { default as FileList } from './FileList'; +export { default as Graph, useDarkMode } from './Graph'; export { default as LoaderSegment } from './LoaderSegment'; export { default as Nbsp } from './Nbsp'; export { default as PlaceholderSegment } from './PlaceholderSegment'; -- cgit v1.2.3 From f8537aefc2ca61716305e5f1cfefbbae896b11c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Jun 2026 18:27:40 -0500 Subject: remove unused props --- src/web/src/components/App.jsx | 1 - src/web/src/components/Dashboard/Dashboard.jsx | 1 - 2 files changed, 2 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index fd017dfe..3fbaa468 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -587,7 +587,6 @@ class App extends Component {
, diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index a345f593..8043ab0b 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -45,7 +45,6 @@ const Dashboard = ({ server } = {}) => { HISTORY_RANGES.find((r) => r.label === historyLabel) ?? HISTORY_RANGES[2]; const now = new Date(); return { - days: range.days, end: now.toISOString(), interval: range.interval, start: -- cgit v1.2.3 From b0b1a6514f42b65003ab55d264f4c8c9eb593582 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 30 Jun 2026 13:53:48 +0000 Subject: Bump js-yaml from 3.14.2 to 3.15.0 in /src/web Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 3.14.2 to 3.15.0. - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/3.14.2...3.15.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 3.15.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 191d1cca..ce6c1070 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3427,9 +3427,9 @@ } }, "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", + "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", "dev": true, "license": "MIT", "dependencies": { @@ -14054,10 +14054,20 @@ } }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -19615,9 +19625,9 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", + "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", "dev": true, "license": "MIT", "dependencies": { -- 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') 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') 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') 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 997a3020c795541e8c347ba7c8142c13c415e4c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 16:24:38 -0500 Subject: add transfers.query --- src/slskd/Transfers/TransferService.cs | 92 ++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 6dd852a0..156b63ec 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -32,6 +32,12 @@ namespace slskd.Transfers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore; +using Serilog; using slskd.Transfers.Downloads; using slskd.Transfers.Uploads; @@ -44,9 +50,12 @@ public class TransferService /// Initializes a new instance of the class. /// public TransferService( + IDbContextFactory contextFactory, IUploadService uploadService = null, IDownloadService downloadService = null) { + ContextFactory = contextFactory; + Uploads = uploadService; Downloads = downloadService; } @@ -60,4 +69,87 @@ public class TransferService /// Gets the download service. /// public virtual IDownloadService Downloads { get; init; } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Finds a single transfer matching the specified . + /// + /// + /// Use this only to avoid needing to call this method on both the Upload and Download services. If the expression + /// contains a direction, this method is being used in error. + /// + /// The expression to use to match transfers. + /// The found transfer, or default if not found. + public virtual Transfer Find(Expression> expression) + { + ArgumentNullException.ThrowIfNull(expression); + + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(expression) + .SingleOrDefault(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list transfers: {Message}", ex.Message); + throw; + } + } + + /// + /// Returns a list of all transfers matching the optional . + /// + /// + /// Use this only to avoid needing to call this method on both the Upload and Download services. If the expression + /// contains a direction, this method is being used in error. + /// + /// An optional expression used to match transfers. + /// A value indicating whether to include transfers that have been removed previously. + /// The list of transfers matching the specified expression, or all transfers if no expression is specified. + public virtual List List(Expression> expression, bool includeRemoved) + { + expression ??= t => true; + + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToList(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + throw; + } + } + + /// + /// Query the Transfers database arbitrarily. Only use if there's no better way. + /// + /// The result Type. + /// The query function. + /// The result. + public virtual TResult Query(Func, TResult> query) + { + try + { + using var context = ContextFactory.CreateDbContext(); + return query(context.Transfers.AsNoTracking()); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to query transfers: {Message}", ex.Message); + throw; + } + } } \ No newline at end of file -- 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') 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 0e41af9c1767b29a9a270e055155b338a7b46b4e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 20:35:34 -0500 Subject: remove periods --- src/web/src/components/Dashboard/TopDirectories.jsx | 2 +- src/web/src/components/Dashboard/TransferErrors.jsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Dashboard/TopDirectories.jsx b/src/web/src/components/Dashboard/TopDirectories.jsx index 00eae5d9..e9d4aba5 100644 --- a/src/web/src/components/Dashboard/TopDirectories.jsx +++ b/src/web/src/components/Dashboard/TopDirectories.jsx @@ -40,7 +40,7 @@ const TopDirectories = ({ rows }) => ( colSpan={4} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display )} diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index d4c9c25c..5fa0408c 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -134,7 +134,7 @@ const TransferErrors = ({ chartData, download, upload }) => { colSpan={4} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display )} @@ -194,7 +194,7 @@ const TransferErrors = ({ chartData, download, upload }) => { colSpan={5} style={{ opacity: 0.5, textAlign: 'center' }} > - No data to display. + No data to display )} -- cgit v1.2.3 From aa86e4c3e67a4b9ae591325b3e4d2a6d9c31f77b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:22:38 -0500 Subject: use buckets instead of intervals --- src/web/src/lib/reports.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/web/src/lib/reports.js b/src/web/src/lib/reports.js index 464c37e5..17c6d214 100644 --- a/src/web/src/lib/reports.js +++ b/src/web/src/lib/reports.js @@ -20,7 +20,7 @@ export const getSummary = async ({ export const getHistogram = async ({ start, end, - interval, + buckets, direction, username = null, } = {}) => { @@ -28,7 +28,7 @@ export const getHistogram = async ({ if (start) parameters.append('start', start.toISOString()); if (end) parameters.append('end', end.toISOString()); - if (interval) parameters.append('interval', interval); + if (buckets) parameters.append('buckets', buckets); if (direction) parameters.append('direction', direction); if (username) parameters.append('username', username); -- cgit v1.2.3 From c4d87a3c25a9b1376ed3252f09fbec83303057f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:23:22 -0500 Subject: include year on date labels if the data set spans years --- src/web/src/components/Shared/Graph.jsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index d383345f..386f9a46 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -112,11 +112,14 @@ const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { }); } - return (timestamp) => - new Date(timestamp).toLocaleDateString(undefined, { - day: 'numeric', - month: 'short', - }); + const spansYears = + new Date(xRange.min).getFullYear() !== new Date(xRange.max).getFullYear(); + + return (timestamp) => { + const d = new Date(timestamp); + const date = d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + return spansYears ? `${date} '${String(d.getFullYear()).slice(2)}` : date; + }; }, [xRange]); const yFormatter = useMemo(() => { -- cgit v1.2.3 From 555da1c27697059fa5d96f9d062608772880c720 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 21:23:35 -0500 Subject: use buckets --- src/web/src/components/Dashboard/Dashboard.jsx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 302e0f0a..4554d6d0 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -5,13 +5,13 @@ import SearchBar from './SearchBar'; import React, { useEffect, useMemo, useState } from 'react'; const HISTORY_RANGES = [ - { label: '24h', days: 1, interval: 60 }, - { label: '7d', days: 7, interval: 360 }, - { label: '30d', days: 30, interval: 1_440 }, - { label: '90d', days: 90, interval: 1_440 }, - { label: '180d', days: 180, interval: 2_880 }, - { label: '1y', days: 365, interval: 10_080 }, - { label: 'All', days: null, interval: 43_200 }, + { label: '24h', days: 1, buckets: 24 }, + { label: '7d', days: 7, buckets: 84 }, + { label: '30d', days: 30, buckets: 60 }, + { label: '90d', days: 90, buckets: 90 }, + { label: '180d', days: 180, buckets: 90 }, + { label: '1y', days: 365, buckets: 100 }, + { label: 'All', days: null, buckets: 100 }, ]; const initialState = { @@ -45,8 +45,8 @@ const Dashboard = ({ server } = {}) => { HISTORY_RANGES.find((r) => r.label === historyLabel) ?? HISTORY_RANGES[2]; const now = new Date(); return { + buckets: range.buckets, end: now.toISOString(), - interval: range.interval, start: range.days != null ? new Date(now - range.days * 86_400_000).toISOString() @@ -76,7 +76,7 @@ const Dashboard = ({ server } = {}) => { return {}; }), reports - .getHistogram({ end, interval: parameters.interval, start }) + .getHistogram({ buckets: parameters.buckets, end, start }) .catch((error) => { console.error(error); return {}; -- 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') 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 ffd47b2287f8d8e8dbf47079e5f746f71671805a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Jul 2026 22:15:23 -0500 Subject: linting --- src/web/src/components/Shared/Graph.jsx | 7 +- src/web/src/lib/reports.test.js | 130 +++++++++++++++++++++----------- 2 files changed, 93 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx index 386f9a46..4d672d3d 100644 --- a/src/web/src/components/Shared/Graph.jsx +++ b/src/web/src/components/Shared/Graph.jsx @@ -116,8 +116,11 @@ const Graph = ({ data = [], defaultSeries, height = 200, series = [] }) => { new Date(xRange.min).getFullYear() !== new Date(xRange.max).getFullYear(); return (timestamp) => { - const d = new Date(timestamp); - const date = d.toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + const d = new Date(timestamp); + const date = d.toLocaleDateString(undefined, { + day: 'numeric', + month: 'short', + }); return spansYears ? `${date} '${String(d.getFullYear()).slice(2)}` : date; }; }, [xRange]); diff --git a/src/web/src/lib/reports.test.js b/src/web/src/lib/reports.test.js index 2b73fdca..12bdfd0d 100644 --- a/src/web/src/lib/reports.test.js +++ b/src/web/src/lib/reports.test.js @@ -6,6 +6,9 @@ jest.mock('./api', () => ({ default: { get: jest.fn() }, })); +const urlOf = () => api.get.mock.calls[0][0]; +const parametersOf = () => new URLSearchParams(urlOf().split('?')[1] ?? ''); + describe('reports', () => { beforeEach(() => { api.get.mockResolvedValue({ data: {} }); @@ -15,40 +18,43 @@ describe('reports', () => { jest.clearAllMocks(); }); - const urlOf = () => api.get.mock.calls[0][0]; - const paramsOf = () => new URLSearchParams(urlOf().split('?')[1] ?? ''); - describe('getSummary', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getSummary(); expect(urlOf()).toContain('/telemetry/reports/transfers/summary'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getSummary({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getSummary({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getSummary({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('appends username when provided', async () => { + expect.hasAssertions(); await reports.getSummary({ username: 'testuser' }); - expect(paramsOf().get('username')).toBe('testuser'); + expect(parametersOf().get('username')).toBe('testuser'); }); it('omits optional params when not provided', async () => { + expect.hasAssertions(); await reports.getSummary(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); expect(p.has('direction')).toBe(false); @@ -58,40 +64,47 @@ describe('reports', () => { describe('getHistogram', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getHistogram(); expect(urlOf()).toContain('/telemetry/reports/transfers/histogram'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getHistogram({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getHistogram({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('appends buckets when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ buckets: 50 }); - expect(paramsOf().get('buckets')).toBe('50'); + expect(parametersOf().get('buckets')).toBe('50'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ direction: 'Download' }); - expect(paramsOf().get('direction')).toBe('Download'); + expect(parametersOf().get('direction')).toBe('Download'); }); it('appends username when provided', async () => { + expect.hasAssertions(); await reports.getHistogram({ username: 'testuser' }); - expect(paramsOf().get('username')).toBe('testuser'); + expect(parametersOf().get('username')).toBe('testuser'); }); it('omits optional params when not provided', async () => { + expect.hasAssertions(); await reports.getHistogram(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); expect(p.has('buckets')).toBe(false); @@ -102,50 +115,59 @@ describe('reports', () => { describe('getLeaderboard', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); expect(urlOf()).toContain('/telemetry/reports/transfers/leaderboard'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ limit: 25 }); - expect(paramsOf().get('limit')).toBe('25'); + expect(parametersOf().get('limit')).toBe('25'); }); it('defaults sortBy to Count', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - expect(paramsOf().get('sortBy')).toBe('Count'); + expect(parametersOf().get('sortBy')).toBe('Count'); }); it('appends the specified sortBy', async () => { + expect.hasAssertions(); await reports.getLeaderboard({ sortBy: 'TotalBytes' }); - expect(paramsOf().get('sortBy')).toBe('TotalBytes'); + expect(parametersOf().get('sortBy')).toBe('TotalBytes'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getLeaderboard({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getLeaderboard({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits start and end when not provided', async () => { + expect.hasAssertions(); await reports.getLeaderboard(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); }); @@ -153,35 +175,41 @@ describe('reports', () => { describe('getTopDirectories', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); expect(urlOf()).toContain('/telemetry/reports/transfers/directories'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getTopDirectories({ limit: 20 }); - expect(paramsOf().get('limit')).toBe('20'); + expect(parametersOf().get('limit')).toBe('20'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getTopDirectories({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getTopDirectories({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits start and end when not provided', async () => { + expect.hasAssertions(); await reports.getTopDirectories(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); }); @@ -189,40 +217,49 @@ describe('reports', () => { describe('getExceptionPareto', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - expect(urlOf()).toContain('/telemetry/reports/transfers/exceptions/pareto'); + expect(urlOf()).toContain( + '/telemetry/reports/transfers/exceptions/pareto', + ); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getExceptionPareto({ direction: 'Download' }); - expect(paramsOf().get('direction')).toBe('Download'); + expect(parametersOf().get('direction')).toBe('Download'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getExceptionPareto({ limit: 20 }); - expect(paramsOf().get('limit')).toBe('20'); + expect(parametersOf().get('limit')).toBe('20'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getExceptionPareto({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getExceptionPareto({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); await reports.getExceptionPareto(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('direction')).toBe(false); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); @@ -231,51 +268,60 @@ describe('reports', () => { describe('getExceptions', () => { it('calls the correct endpoint', async () => { + expect.hasAssertions(); await reports.getExceptions(); expect(urlOf()).toContain('/telemetry/reports/transfers/exceptions'); expect(urlOf()).not.toContain('/exceptions/pareto'); }); it('appends direction when provided', async () => { + expect.hasAssertions(); await reports.getExceptions({ direction: 'Upload' }); - expect(paramsOf().get('direction')).toBe('Upload'); + expect(parametersOf().get('direction')).toBe('Upload'); }); it('defaults limit to 10', async () => { + expect.hasAssertions(); await reports.getExceptions(); - expect(paramsOf().get('limit')).toBe('10'); + expect(parametersOf().get('limit')).toBe('10'); }); it('appends the specified limit', async () => { + expect.hasAssertions(); await reports.getExceptions({ limit: 50 }); - expect(paramsOf().get('limit')).toBe('50'); + expect(parametersOf().get('limit')).toBe('50'); }); it('defaults sortOrder to DESC', async () => { + expect.hasAssertions(); await reports.getExceptions(); - expect(paramsOf().get('sortOrder')).toBe('DESC'); + expect(parametersOf().get('sortOrder')).toBe('DESC'); }); it('appends the specified sortOrder', async () => { + expect.hasAssertions(); await reports.getExceptions({ sortOrder: 'ASC' }); - expect(paramsOf().get('sortOrder')).toBe('ASC'); + expect(parametersOf().get('sortOrder')).toBe('ASC'); }); it('appends start as an ISO string', async () => { + expect.hasAssertions(); const start = new Date('2024-01-01T00:00:00.000Z'); await reports.getExceptions({ start }); - expect(paramsOf().get('start')).toBe(start.toISOString()); + expect(parametersOf().get('start')).toBe(start.toISOString()); }); it('appends end as an ISO string', async () => { + expect.hasAssertions(); const end = new Date('2024-12-31T00:00:00.000Z'); await reports.getExceptions({ end }); - expect(paramsOf().get('end')).toBe(end.toISOString()); + expect(parametersOf().get('end')).toBe(end.toISOString()); }); it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); await reports.getExceptions(); - const p = paramsOf(); + const p = parametersOf(); expect(p.has('direction')).toBe(false); expect(p.has('start')).toBe(false); expect(p.has('end')).toBe(false); -- cgit v1.2.3 From 0ff48cabb1464f171b246225c58d15e8ecdb1e57 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 6 Jul 2026 20:53:42 -0500 Subject: move utility functions to util --- .../components/Dashboard/HistoricalStatistics.jsx | 21 +++--------- src/web/src/components/Dashboard/Leaderboard.jsx | 13 +------- .../src/components/Dashboard/TransferErrors.jsx | 38 ++++------------------ src/web/src/lib/util.js | 11 +++++++ 4 files changed, 23 insertions(+), 60 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx index b0963082..c14649c4 100644 --- a/src/web/src/components/Dashboard/HistoricalStatistics.jsx +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -1,3 +1,4 @@ +import { formatBytes, formatSpeed } from '../../lib/util'; import { Graph, LoaderSegment } from '../Shared'; import Leaderboard from './Leaderboard'; import TopDirectories from './TopDirectories'; @@ -6,7 +7,6 @@ import React, { useMemo } from 'react'; import { Button, ButtonGroup, - Divider, Header, Icon, Segment, @@ -14,18 +14,6 @@ import { Tab, } from 'semantic-ui-react'; -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 formatBytesParts = (bytes) => { if (!bytes || bytes === 0) return { unit: 'B', value: '0' }; const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; @@ -82,14 +70,14 @@ const buildChartData = (histogram) => const HISTORY_SERIES = [ { color: '#21ba45', - format: formatBytes, + format: (v) => formatBytes(v, 1), key: 'uploadBytes', name: 'Upload Size', unit: 'bytes', }, { color: '#2185d0', - format: formatBytes, + format: (v) => formatBytes(v, 1), key: 'downloadBytes', name: 'Download Size', unit: 'bytes', @@ -226,6 +214,8 @@ const HistoricalStatistics = ({ @@ -336,7 +326,6 @@ const HistoricalStatistics = ({ series={HISTORY_SERIES} /> - onTabChange(activeIndex)} diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index b983dc5a..a7fa6662 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -1,19 +1,8 @@ import * as reports from '../../lib/reports'; +import { formatBytes, formatSpeed } from '../../lib/util'; import React, { useEffect, useState } from 'react'; import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; -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 SORT_FIELDS = [ { label: 'Count', sort: 'Count' }, { label: 'Total Size', sort: 'TotalBytes' }, diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index 5fa0408c..54dc9a20 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -1,35 +1,9 @@ -import { Graph, useDarkMode } from '../Shared'; -import React, { useMemo } from 'react'; -import { Divider, Header, Table } from 'semantic-ui-react'; - -const truncate = (text, maxLength) => { - if (!text) { - return ''; - } - - if (text.length <= maxLength) { - return text; - } - - return `${text.slice(0, maxLength)}…`; -}; - -const getFilename = (path) => { - if (!path) { - return ''; - } - - const parts = path.replaceAll('\\', '/').split('/'); - return parts[parts.length - 1] || path; -}; - -const formatDateTime = (isoString) => { - if (!isoString) { - return ''; - } - - return new Date(isoString).toLocaleString(); -}; +import * as reports from '../../lib/reports'; +import { Graph } from '../Shared'; +import ExceptionList from './ExceptionList'; +import ExceptionPareto from './ExceptionPareto'; +import React, { useEffect, useMemo, useState } from 'react'; +import { Header, Icon } from 'semantic-ui-react'; const mergePareto = (uploadRows, downloadRows) => { const combined = {}; diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index 091a8207..b499f81e 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -39,10 +39,21 @@ export const formatBytes = ( return padded + ' ' + sizes[index]; }; +export const formatSpeed = (bytesPerSecond, decimals = 1) => { + if (!bytesPerSecond || bytesPerSecond === 0) return '0 B/s'; + return `${formatBytes(bytesPerSecond, decimals)}/s`; +}; + export const formatDate = (date) => { return new Date(date).toLocaleString(); }; +export const truncate = (text, maxLength) => { + if (!text) return ''; + if (text.length <= maxLength) return text; + return `${text.slice(0, maxLength)}...`; +}; + export const getFileName = (fullPath) => { return fullPath.split('\\').pop().split('/').pop(); }; -- cgit v1.2.3 From e86882aa36e403e32f1789ed47dc698a51eba0d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 6 Jul 2026 21:19:52 -0500 Subject: tweak componensts for consistency --- src/web/src/components/Dashboard/ExceptionList.jsx | 96 ++++++++ .../src/components/Dashboard/ExceptionPareto.jsx | 110 +++++++++ src/web/src/components/Dashboard/Leaderboard.jsx | 35 ++- .../src/components/Dashboard/TopDirectories.jsx | 93 ++++---- .../src/components/Dashboard/TransferErrors.jsx | 248 +++++++++------------ 5 files changed, 374 insertions(+), 208 deletions(-) create mode 100644 src/web/src/components/Dashboard/ExceptionList.jsx create mode 100644 src/web/src/components/Dashboard/ExceptionPareto.jsx (limited to 'src') diff --git a/src/web/src/components/Dashboard/ExceptionList.jsx b/src/web/src/components/Dashboard/ExceptionList.jsx new file mode 100644 index 00000000..d0412006 --- /dev/null +++ b/src/web/src/components/Dashboard/ExceptionList.jsx @@ -0,0 +1,96 @@ +import { formatDate, getFileName, truncate } from '../../lib/util'; +import React from 'react'; +import { + Button, + ButtonGroup, + Header, + Icon, + Loader, + Table, +} from 'semantic-ui-react'; + +const DIRECTIONS = ['Upload', 'Download', 'All']; + +const ExceptionList = ({ direction, loading, onDirectionChange, rows }) => ( + <> +
+ + Recent Errors + + {DIRECTIONS.map((d) => ( + + ))} + +
+ + + + Time + Direction + Username + Filename + Exception + + + + {loading && ( + + + + + + )} + {rows.length === 0 && !loading && ( + + + No data to display + + + )} + {!loading && + rows.map((row) => ( + + + {row.endedAt ? formatDate(row.endedAt) : ''} + + {row.direction} + {row.username} + + {row.filename ? getFileName(row.filename) : ''} + + + {truncate(row.exception, 80)} + + + ))} + +
+ +); + +export default ExceptionList; diff --git a/src/web/src/components/Dashboard/ExceptionPareto.jsx b/src/web/src/components/Dashboard/ExceptionPareto.jsx new file mode 100644 index 00000000..13fafb5a --- /dev/null +++ b/src/web/src/components/Dashboard/ExceptionPareto.jsx @@ -0,0 +1,110 @@ +import { truncate } from '../../lib/util'; +import React from 'react'; +import { + Button, + ButtonGroup, + Header, + Icon, + Loader, + Progress, + Table, +} from 'semantic-ui-react'; + +const DIRECTIONS = ['Upload', 'Download', 'All']; + +const ExceptionPareto = ({ direction, loading, onDirectionChange, rows }) => { + const maxCount = rows.length > 0 ? rows[0].count : 1; + + return ( + <> +
+ + Error Count By Type + + {DIRECTIONS.map((d) => ( + + ))} + +
+ + + + Direction + Exception + + Count + + Distinct Users + + + + + {loading && ( + + + + + + )} + {!loading && rows.length === 0 && ( + + + No data to display + + + )} + {!loading && + rows.map((row) => ( + + {row.direction} + + {truncate(row.exception, 80)} + + + + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + +
+ + ); +}; + +export default ExceptionPareto; diff --git a/src/web/src/components/Dashboard/Leaderboard.jsx b/src/web/src/components/Dashboard/Leaderboard.jsx index a7fa6662..4a37870c 100644 --- a/src/web/src/components/Dashboard/Leaderboard.jsx +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -129,30 +129,27 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { const startDate = start ? new Date(start) : undefined; const endDate = end ? new Date(end) : new Date(); - const [newUploads, newDownloads] = await Promise.all([ - reports - .getLeaderboard({ + let newUploads = state.rows.upload; + let newDownloads = state.rows.download; + + try { + [newUploads, newDownloads] = await Promise.all([ + reports.getLeaderboard({ direction: 'Upload', end: endDate, sortBy: sort, start: startDate, - }) - .catch((error) => { - console.error(error); - return state.rows.upload; }), - reports - .getLeaderboard({ + reports.getLeaderboard({ direction: 'Download', end: endDate, sortBy: sort, start: startDate, - }) - .catch((error) => { - console.error(error); - return state.rows.download; }), - ]); + ]); + } catch (error) { + console.error(error); + } setState((previous) => ({ ...previous, @@ -167,10 +164,7 @@ const Leaderboard = ({ downloads, end, start, uploads }) => { stackable > -
+
Downloads
{ -
+
Uploads
{ if (!path) { @@ -16,56 +16,61 @@ const getLastTwoSegments = (path) => { }; const TopDirectories = ({ rows }) => ( - - - - - # - - Directory - Downloads - Distinct Users - - - - {(!rows || rows.length === 0) && ( + <> +
+ Directories +
+
+ - - No data to display - + # + + Directory + Downloads + Distinct Users - )} - {rows && - rows.map((row, index) => ( - + + + {(!rows || rows.length === 0) && ( + - {index + 1} - - - {getLastTwoSegments(row.directory)} - - - {row.count.toLocaleString()} - - - {row.distinctUsers.toLocaleString()} + No data to display - ))} - -
+ )} + {rows && + rows.map((row, index) => ( + + + {index + 1} + + + {getLastTwoSegments(row.directory)} + + + {row.count.toLocaleString()} + + + {row.distinctUsers.toLocaleString()} + + + ))} + + + ); export default TopDirectories; diff --git a/src/web/src/components/Dashboard/TransferErrors.jsx b/src/web/src/components/Dashboard/TransferErrors.jsx index 54dc9a20..7def5ca6 100644 --- a/src/web/src/components/Dashboard/TransferErrors.jsx +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -5,23 +5,13 @@ import ExceptionPareto from './ExceptionPareto'; import React, { useEffect, useMemo, useState } from 'react'; import { Header, Icon } from 'semantic-ui-react'; -const mergePareto = (uploadRows, downloadRows) => { - const combined = {}; - for (const row of [...(uploadRows || []), ...(downloadRows || [])]) { - const key = row.exception ?? ''; - combined[key] = combined[key] - ? { - exception: key, - count: combined[key].count + row.count, - distinctUsers: combined[key].distinctUsers + row.distinctUsers, - } - : { ...row }; - } - - return Object.values(combined) +const buildParetoRows = (uploadRows, downloadRows) => + [ + ...(uploadRows || []).map((r) => ({ ...r, direction: 'Upload' })), + ...(downloadRows || []).map((r) => ({ ...r, direction: 'Download' })), + ] .sort((a, b) => b.count - a.count) .slice(0, 10); -}; const mergeRecent = (uploadRows, downloadRows) => [ @@ -50,148 +40,122 @@ const ERRORS_SERIES = [ const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); -const TransferErrors = ({ chartData, download, upload }) => { - const isDark = useDarkMode(); +const RECENT_PAGE_SIZE = 10; + +const TransferErrors = ({ chartData, download, end, start, upload }) => { + const [paretoDirection, setParetoDirection] = useState('All'); + const [paretoRows, setParetoRows] = useState(null); + const [paretoLoading, setParetoLoading] = useState(false); - const paretoRows = useMemo( - () => mergePareto(upload.pareto, download.pareto), + const [recentDirection, setRecentDirection] = useState('All'); + const [recentRows, setRecentRows] = useState(null); + const [recentLoading, setRecentLoading] = useState(false); + + useEffect(() => { + setParetoDirection('All'); + setParetoRows(null); + setRecentDirection('All'); + setRecentRows(null); + }, [end, start]); + + const initialParetoRows = useMemo( + () => buildParetoRows(upload.pareto, download.pareto), [upload.pareto, download.pareto], ); - const recentRows = useMemo( + + const initialRecentRows = useMemo( () => mergeRecent(upload.recent, download.recent), [upload.recent, download.recent], ); - const maxParetoCount = - paretoRows && paretoRows.length > 0 ? paretoRows[0].count : 1; + const displayedParetoRows = paretoRows ?? initialParetoRows; + const displayedRecentRows = recentRows ?? initialRecentRows; + + const fetchPareto = async (direction) => { + try { + return await reports.getExceptionPareto({ + direction, + end: new Date(end), + start: start ? new Date(start) : undefined, + }); + } catch (error) { + console.error(error); + return []; + } + }; + + const fetchRecent = async (direction) => { + try { + return await reports.getExceptions({ + direction, + end: new Date(end), + limit: RECENT_PAGE_SIZE, + start: start ? new Date(start) : undefined, + }); + } catch (error) { + console.error(error); + return []; + } + }; + + const onParetoDirectionChange = async (d) => { + 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 }))); + } + + 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 }))); + } + + setRecentLoading(false); + }; return (
-
Error Count Over Time
+
+ Errors +
- -
- Top Fault Types - - pareto - -
- - - - Exception - - Count - - Distinct Users - - - - - {(!paretoRows || paretoRows.length === 0) && ( - - - No data to display - - - )} - {paretoRows && - paretoRows.map((row) => ( - - - {truncate(row.exception, 80)} - - -
-
-
- - - {row.count.toLocaleString()} - - - {row.distinctUsers.toLocaleString()} - - - ))} - -
- -
Recent Errors
- - - - Time - Direction - Username - Filename - Exception - - - - {(!recentRows || recentRows.length === 0) && ( - - - No data to display - - - )} - {recentRows && - recentRows.map((row) => ( - - - {formatDateTime(row.endedAt)} - - {row.direction} - {row.username} - - {getFilename(row.filename)} - - - {truncate(row.exception, 80)} - - - ))} - -
+ +
); }; -- 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') 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') 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') 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 From 1abc6ec12de826240cd0edfa478705241b2dabed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 14:21:49 -0500 Subject: fix bug preventing a user from initiating a chat --- src/web/src/components/Chat/Chat.jsx | 2 +- src/web/src/components/Chat/SendMessageModal.jsx | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 39dd1a44..9224fb30 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -217,7 +217,7 @@ class Chat extends Component { }; initiateConversation = async (username, message) => { - await this.sendMessage(username, message); + await chat.send({ username, message }); await this.fetchConversations(); this.selectConversation(username); }; diff --git a/src/web/src/components/Chat/SendMessageModal.jsx b/src/web/src/components/Chat/SendMessageModal.jsx index 203b2d06..309f1759 100644 --- a/src/web/src/components/Chat/SendMessageModal.jsx +++ b/src/web/src/components/Chat/SendMessageModal.jsx @@ -1,10 +1,9 @@ import './Chat.css'; -import React, { useEffect } from 'react'; +import React, { useEffect, useRef } from 'react'; import { Button, Form, Header, Icon, Input, Modal } from 'semantic-ui-react'; -const usernameRef = React.createRef(); - const SendMessageModal = ({ initiateConversation, ...rest }) => { + const usernameRef = useRef(); const [open, setOpen] = React.useState(false); const [username, setUsername] = React.useState(''); const [message, setMessage] = React.useState(''); -- cgit v1.2.3 From b781709d850ba5e0264ca5b7740f1a2a2d0ee8de Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 7 Jul 2026 15:47:09 -0500 Subject: bump dependencies, including Soulseek.NET to 10.0.2 --- src/slskd/slskd.csproj | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cb6a7d83..03fc4af4 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -47,15 +47,15 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + @@ -67,17 +67,17 @@ - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + -- cgit v1.2.3 From a306f157a05da6fcb8798018d7be67c59a129be5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Jul 2026 13:10:57 -0500 Subject: quiet noise --- src/web/.eslintrc.js | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 0b0f9fb6..a39caf8e 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -8,6 +8,7 @@ const overrides = { 'react/prop-types': 'off', // noisy 'canonical/sort-keys': 'off', // noisy 'unicorn/no-array-reduce': 'off', // noisy + 'unicorn/prevent-abbreviations': 'off', }; /** @type {import('eslint').Linter.Config} */ -- cgit v1.2.3 From 1d50173499209d7f70822e7177b48d4216993794 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Jul 2026 20:21:44 -0500 Subject: rename some types --- .../API/Controllers/TransfersController.cs | 12 +-- .../API/DTO/EnqueueDownloadBatchRequest.cs | 118 +++++++++++++++++++++ .../API/DTO/EnqueueDownloadBatchResponse.cs | 47 ++++++++ .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 118 --------------------- .../API/DTO/QueueDownloadBatchResponse.cs | 47 -------- 5 files changed, 171 insertions(+), 171 deletions(-) create mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs create mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs delete mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs delete mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 147921ef..83eb04ef 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -303,15 +303,15 @@ namespace slskd.Transfers.API /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)] - [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] + [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status201Created)] + [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)] [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)] [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] - public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) + public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) { if (Program.IsRelayAgent) { @@ -393,10 +393,10 @@ namespace slskd.Transfers.API // properly finalized and marked as a failure var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); - var response = new QueueDownloadBatchResponse + var response = new EnqueueDownloadBatchResponse { Batch = batch, - Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(), + Failures = failed.Select(f => new EnqueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(), }; // basically a no-op, but we did create the batch record (and it's useless, but it's there) diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs new file mode 100644 index 00000000..7af36fcb --- /dev/null +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -0,0 +1,118 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using slskd.Validation; + +namespace slskd.Transfers.API; + +/// +/// Enqueue a batch of downloads. +/// +public record EnqueueDownloadBatchRequest +{ + /// + /// The ID of the Batch. + /// + /// + /// If not supplied, one will be randomly generated. + /// + [Guid] + public string Id { get; init; } + + /// + /// The ID of the associated Search, if applicable. + /// + [Guid] + public string SearchId { get; init; } + + /// + /// The username of the user from which to download. + /// + [Required] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] + public string Username { get; init; } + + /// + /// The list of files to download. + /// + [Required] + [MinLength(1)] + public IReadOnlyCollection Files { get; init; } = []; + + /// + /// Options for the Batch. + /// + public EnqueueDownloadBatchOptions Options { get; init; } = new(); +} + +/// +/// An item in a download batch. +/// +public record EnqueueDownloadBatchItem +{ + /// + /// The name of the file. + /// + [Required] + [NotNullOrWhiteSpace] + [NonTraversingPath] + public string Filename { get; init; } + + /// + /// The file size. + /// + [Required] + [Range(0, long.MaxValue)] + public long? Size { get; init; } +} + +/// +/// Download batch options. +/// +public record EnqueueDownloadBatchOptions +{ + /// + /// The destination directory for the files, relative to the configured download directory. + /// + [RelativePath(OperatingSystem.All)] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Destination { get; init; } + + /// + /// An optional external ID for the batch. + /// + public string ExternalId { get; init; } +} \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs new file mode 100644 index 00000000..3d066fe9 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs @@ -0,0 +1,47 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System.Collections.Generic; + +namespace slskd.Transfers.API; + +public record EnqueueDownloadBatchResponse +{ + public Batch Batch { get; init; } + public IReadOnlyCollection Failures { get; init; } = []; +} + +public record EnqueueDownloadBatchResponseFailure +{ + public string Filename { get; init; } + public string Message { get; init; } +} diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs deleted file mode 100644 index fe34bfec..00000000 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ /dev/null @@ -1,118 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ 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, version 3. -// │ -// │ 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/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using slskd.Validation; - -namespace slskd.Transfers.API; - -/// -/// Enqueue a batch of downloads. -/// -public record QueueDownloadBatchRequest -{ - /// - /// The ID of the Batch. - /// - /// - /// If not supplied, one will be randomly generated. - /// - [Guid] - public string Id { get; init; } - - /// - /// The ID of the associated Search, if applicable. - /// - [Guid] - public string SearchId { get; init; } - - /// - /// The username of the user from which to download. - /// - [Required] - [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] - public string Username { get; init; } - - /// - /// The list of files to download. - /// - [Required] - [MinLength(1)] - public IReadOnlyCollection Files { get; init; } = []; - - /// - /// Options for the Batch. - /// - public EnqueueDownloadBatchOptions Options { get; init; } = new(); -} - -/// -/// An item in a download batch. -/// -public record EnqueueDownloadBatchItem -{ - /// - /// The name of the file. - /// - [Required] - [NotNullOrWhiteSpace] - [NonTraversingPath] - public string Filename { get; init; } - - /// - /// The file size. - /// - [Required] - [Range(0, long.MaxValue)] - public long? Size { get; init; } -} - -/// -/// Download batch options. -/// -public record EnqueueDownloadBatchOptions -{ - /// - /// The destination directory for the files, relative to the configured download directory. - /// - [RelativePath(OperatingSystem.All)] - [NonTraversingPath] - [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] - public string Destination { get; init; } - - /// - /// An optional external ID for the batch. - /// - public string ExternalId { get; init; } -} \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs deleted file mode 100644 index 84b570bc..00000000 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs +++ /dev/null @@ -1,47 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ 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, version 3. -// │ -// │ 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/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -using System.Collections.Generic; - -namespace slskd.Transfers.API; - -public record QueueDownloadBatchResponse -{ - public Batch Batch { get; init; } - public IReadOnlyCollection Failures { get; init; } = []; -} - -public record QueueDownloadBatchResponseFailure -{ - public string Filename { get; init; } - public string Message { get; init; } -} -- cgit v1.2.3 From 9584bc07cdc4ce5e94ec29273d07a1c67904fdda Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Jul 2026 20:22:20 -0500 Subject: add enqueueBatch() --- src/web/src/lib/transfers.js | 61 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js index 7fa58fc3..361926ae 100644 --- a/src/web/src/lib/transfers.js +++ b/src/web/src/lib/transfers.js @@ -20,6 +20,42 @@ export const download = ({ username, files = [] }) => { ); }; +/** + * Enqueues a batch of downloads. + * @param {object} params + * @param {string} params.username - The user to download from. + * @param {{ filename: string, size: number }[]} [params.files] - Files to enqueue. + * @param {string} [params.id] - Optional batch GUID. Generated server-side if omitted. + * @param {string} [params.searchId] - Optional GUID of an associated search. + * @param {{ destination?: string, externalId?: string }} [params.options] - `destination`: path relative to the configured download directory; `externalId`: optional external identifier for the batch. + * @returns {Promise} Resolves with the axios response. + * - 201: all files enqueued successfully + * - 200: batch created, but every file failed to enqueue — check `response.data.failures` + * - 207: partial — some enqueued, some failed — check `response.data.failures` + * @throws On error responses: + * - 400: validation failure (username/files required; duplicate filenames; id or searchId not a valid GUID) + * - 403: forbidden — running as relay agent + * - 404: user is offline + * - 409: a batch with the supplied id already exists + * - 429: a concurrent enqueue request is already in progress + * - 500: unexpected server error + */ +export const enqueueBatch = ({ + username, + files = [], + id, + searchId, + options = { destination: undefined, externalId: undefined }, +}) => { + return api.post('/transfers/downloads/batches', { + files, + id, + options, + searchId, + username, + }); +}; + export const cancel = ({ direction, username, id, remove = false }) => { return api.delete( `/transfers/${direction}s/${encodeURIComponent(username)}/${encodeURIComponent(id)}?remove=${remove}`, @@ -30,23 +66,26 @@ export const clearCompleted = ({ direction }) => { return api.delete(`/transfers/${direction}s/all/completed`); }; -// 'Requested' -// 'Queued, Remotely' -// 'Queued, Locally' -// 'Initializing' -// 'InProgress' -// 'Completed, Succeeded' -// 'Completed, Cancelled' -// 'Completed, TimedOut' -// 'Completed, Errored' -// 'Completed, Rejected' - export const getPlaceInQueue = ({ username, id }) => { return api.get( `/transfers/downloads/${encodeURIComponent(username)}/${encodeURIComponent(id)}/position`, ); }; +/* + states: + + 'Requested' + 'Queued, Remotely' + 'Queued, Locally' + 'Initializing' + 'InProgress' + 'Completed, Succeeded' + 'Completed, Cancelled' + 'Completed, TimedOut' + 'Completed, Errored' + 'Completed, Rejected' +*/ export const isStateRetryable = (state) => state.includes('Completed') && state !== 'Completed, Succeeded'; -- cgit v1.2.3 From 0f5fc71a0f956b4984c42d8d830f130bd32bf814 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Jul 2026 13:30:09 -0500 Subject: replace Directory with Selection --- src/web/src/components/Browse/Directory.jsx | 136 ----------------- src/web/src/components/Browse/Selection.jsx | 221 ++++++++++++++++++++++++++++ 2 files changed, 221 insertions(+), 136 deletions(-) delete mode 100644 src/web/src/components/Browse/Directory.jsx create mode 100644 src/web/src/components/Browse/Selection.jsx (limited to 'src') diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx deleted file mode 100644 index ed88f131..00000000 --- a/src/web/src/components/Browse/Directory.jsx +++ /dev/null @@ -1,136 +0,0 @@ -import * as transfers from '../../lib/transfers'; -import { formatBytes } from '../../lib/util'; -import FileList from '../Shared/FileList'; -import React, { Component } from 'react'; -import { Button, Card, Icon, Label } from 'semantic-ui-react'; - -const initialState = { - downloadError: '', - downloadRequest: undefined, -}; - -class Directory extends Component { - constructor(props) { - super(props); - - this.state = { - ...initialState, - files: this.props.files.map((f) => ({ selected: false, ...f })), - }; - } - - componentDidUpdate(previousProps) { - if (this.props.name !== previousProps.name) { - this.setState({ - files: this.props.files.map((f) => ({ selected: false, ...f })), - }); - } - } - - handleFileSelectionChange = (file, state) => { - file.selected = state; - this.setState((previousState) => ({ - downloadError: '', - downloadRequest: undefined, - tree: previousState.tree, - })); - }; - - download = (username, files) => { - this.setState({ downloadRequest: 'inProgress' }, async () => { - try { - const requests = (files || []).map(({ filename, size }) => ({ - filename, - size, - })); - await transfers.download({ files: requests, username }); - - this.setState({ downloadRequest: 'complete' }); - } catch (error) { - this.setState({ - downloadError: error.response, - downloadRequest: 'error', - }); - } - }); - }; - - render() { - const { locked, marginTop, name, onClose, username } = this.props; - const { downloadError, downloadRequest, files } = this.state; - - const selectedFiles = files.filter((f) => f.selected); - - const selectedSize = formatBytes( - selectedFiles.reduce((total, f) => total + f.size, 0), - ); - - return ( - - -
- -
-
- {selectedFiles.length > 0 && ( - - -