From 4daf1f166b03bc27d723c915a680ca649d6829e5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Jun 2026 18:37:24 -0500 Subject: add dashboard --- src/web/src/components/Dashboard/Dashboard.css | 11 + src/web/src/components/Dashboard/Dashboard.jsx | 157 ++++++++- .../components/Dashboard/HistoricalStatistics.jsx | 357 +++++++++++++++++++++ src/web/src/components/Dashboard/Leaderboard.jsx | 213 ++++++++++++ .../src/components/Dashboard/TopDirectories.jsx | 71 ++++ .../src/components/Dashboard/TransferErrors.jsx | 242 ++++++++++++++ 6 files changed, 1050 insertions(+), 1 deletion(-) create mode 100644 src/web/src/components/Dashboard/Dashboard.css create mode 100644 src/web/src/components/Dashboard/HistoricalStatistics.jsx create mode 100644 src/web/src/components/Dashboard/Leaderboard.jsx create mode 100644 src/web/src/components/Dashboard/TopDirectories.jsx create mode 100644 src/web/src/components/Dashboard/TransferErrors.jsx (limited to 'src') diff --git a/src/web/src/components/Dashboard/Dashboard.css b/src/web/src/components/Dashboard/Dashboard.css new file mode 100644 index 00000000..b67483e6 --- /dev/null +++ b/src/web/src/components/Dashboard/Dashboard.css @@ -0,0 +1,11 @@ +.dark .dashboard .ui.statistics .statistic .label { + color: var(--slskd-color); +} + +.dark .dashboard .ui.statistics .statistic:not(.blue):not(.green):not(.red):not(.yellow) > .value { + color: var(--slskd-color); +} + +.dashboard .ui.small.statistics .statistic > .value { + height: 50px; +} \ No newline at end of file diff --git a/src/web/src/components/Dashboard/Dashboard.jsx b/src/web/src/components/Dashboard/Dashboard.jsx index 01dd1aa0..959df68b 100644 --- a/src/web/src/components/Dashboard/Dashboard.jsx +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -1,10 +1,165 @@ +import './Dashboard.css'; +import * as reports from '../../lib/reports'; +import HistoricalStatistics from './HistoricalStatistics'; import SearchBar from './SearchBar'; -import React from 'react'; +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 }, +]; + +const initialState = { + summary: {}, + histogram: {}, + leaderboard: { + upload: [], + download: [], + }, + directories: [], + exceptions: { + upload: { + pareto: [], + recent: [], + }, + download: { + pareto: [], + recent: [], + }, + }, +}; const Dashboard = ({ server } = {}) => { + const [loading, setLoading] = useState(true); + const [historyLabel, setHistoryLabel] = useState('30d'); + const [historyTab, setHistoryTab] = useState(0); + const [data, setData] = useState(initialState); + + const historyParameters = useMemo(() => { + const range = + 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: + range.days != null + ? new Date(now - range.days * 86_400_000).toISOString() + : null, + }; + }, [historyLabel]); + + const fetchAll = async (parameters) => { + const start = parameters.start ? new Date(parameters.start) : undefined; + const end = new Date(parameters.end); + + setLoading(true); + + const [ + summary, + histogram, + uploadLeaderboard, + downloadLeaderboard, + directories, + uploadPareto, + downloadPareto, + uploadRecent, + downloadRecent, + ] = await Promise.all([ + reports.getSummary({ end, start }).catch((error) => { + console.error(error); + return {}; + }), + reports + .getHistogram({ end, interval: parameters.interval, start }) + .catch((error) => { + console.error(error); + return {}; + }), + reports + .getLeaderboard({ direction: 'Upload', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + reports + .getLeaderboard({ direction: 'Download', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + reports.getTopDirectories({ end, start }).catch((error) => { + console.error(error); + return []; + }), + reports + .getExceptionPareto({ direction: 'Upload', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + reports + .getExceptionPareto({ direction: 'Download', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + reports + .getExceptions({ direction: 'Upload', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + reports + .getExceptions({ direction: 'Download', end, start }) + .catch((error) => { + console.error(error); + return []; + }), + ]); + + setData({ + summary, + histogram, + leaderboard: { upload: uploadLeaderboard, download: downloadLeaderboard }, + directories, + exceptions: { + upload: { pareto: uploadPareto, recent: uploadRecent }, + download: { pareto: downloadPareto, recent: downloadRecent }, + }, + }); + setLoading(false); + }; + + useEffect(() => { + fetchAll(historyParameters); + }, [historyParameters]); // eslint-disable-line react-hooks/exhaustive-deps + return (
+ setHistoryLabel(label)} + onTabChange={setHistoryTab} + summary={data.summary} + />
); }; diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx new file mode 100644 index 00000000..91af07ae --- /dev/null +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -0,0 +1,357 @@ +import { Graph, LoaderSegment } from '../Shared'; +import Leaderboard from './Leaderboard'; +import TopDirectories from './TopDirectories'; +import TransferErrors from './TransferErrors'; +import React, { useMemo } from 'react'; +import { + Button, + ButtonGroup, + Divider, + Header, + Icon, + Segment, + Statistic, + 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']; + const index = Math.floor(Math.log(bytes) / Math.log(1_024)); + return { unit: units[index], value: (bytes / 1_024 ** index).toFixed(1) }; +}; + +const sumCounts = (directionData = {}) => + Object.values(directionData).reduce((sum, s) => sum + (s.count ?? 0), 0); + +const sumBytes = (directionData = {}) => + Object.values(directionData).reduce((sum, s) => sum + (s.totalBytes ?? 0), 0); + +const errorCount = (directionData = {}) => + (directionData.Errored?.count ?? 0) + + (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)) + .map(([timestamp, directions]) => { + const uploadBytes = sumBytes(directions.Upload ?? {}); + const downloadBytes = sumBytes(directions.Download ?? {}); + const uploadCount = sumCounts(directions.Upload ?? {}); + const downloadCount = sumCounts(directions.Download ?? {}); + const uploadErrors = errorCount(directions.Upload ?? {}); + const downloadErrors = errorCount(directions.Download ?? {}); + return { + downloadBytes, + downloadCount, + downloadErrorRate: + downloadCount > 0 ? (downloadErrors / downloadCount) * 100 : 0, + downloadErrors, + downloadSpeed: directions.Download?.Succeeded?.averageSpeed ?? 0, + shareRatio: downloadBytes > 0 ? uploadBytes / downloadBytes : 0, + timestamp: new Date(timestamp).getTime(), + uploadBytes, + uploadCount, + uploadErrorRate: + uploadCount > 0 ? (uploadErrors / uploadCount) * 100 : 0, + uploadErrors, + uploadSpeed: directions.Upload?.Succeeded?.averageSpeed ?? 0, + uploadWait: directions.Upload?.Succeeded?.averageWait ?? 0, + }; + }); + +const HISTORY_SERIES = [ + { + color: '#21ba45', + format: formatBytes, + key: 'uploadBytes', + name: 'Upload Size', + }, + { + color: '#2185d0', + format: formatBytes, + key: 'downloadBytes', + name: 'Download Size', + }, + { + color: '#6435c9', + format: (v) => v.toLocaleString(), + key: 'uploadCount', + name: 'Upload Count', + }, + { + color: '#e03997', + format: (v) => v.toLocaleString(), + key: 'downloadCount', + name: 'Download Count', + }, + { + color: '#f2711c', + format: formatSpeed, + key: 'uploadSpeed', + name: 'Upload Speed', + }, + { + color: '#fbbd08', + format: formatSpeed, + key: 'downloadSpeed', + name: 'Download Speed', + }, + { + color: '#db2828', + format: (v) => v.toLocaleString(), + key: 'uploadErrors', + name: 'Upload Errors', + }, + { + color: '#a333c8', + format: (v) => v.toLocaleString(), + key: 'downloadErrors', + name: 'Download Errors', + }, + { + color: '#d4500a', + format: (v) => `${v.toFixed(1)}%`, + key: 'uploadErrorRate', + name: 'Upload Error Rate', + }, + { + color: '#1aa9b0', + format: (v) => `${v.toFixed(1)}%`, + key: 'downloadErrorRate', + name: 'Download Error Rate', + }, + { + color: '#8e44ad', + format: formatWait, + key: 'uploadWait', + name: 'Upload Queue Wait', + }, + { + color: '#b5cc18', + format: (v) => v.toFixed(2), + key: 'shareRatio', + name: 'Share Ratio', + }, +]; + +const DEFAULT_HISTORY_SERIES = new Set(['uploadBytes', 'downloadBytes']); + +const HistoricalStatistics = ({ + activeTab, + directories, + exceptions, + histogram, + historyDays, + historyEnd, + historyLabel, + historyRanges, + historyStart, + leaderboard, + loading, + onHistoryRangeSelect, + onTabChange, + summary, +}) => { + const chartData = useMemo(() => buildChartData(histogram), [histogram]); + + const dlBytes = sumBytes(summary.Download ?? {}); + const ulBytes = sumBytes(summary.Upload ?? {}); + const shareRatio = dlBytes > 0 ? ulBytes / dlBytes : null; + const shareRatioColor = + shareRatio === null + ? 'grey' + : shareRatio > 0.66 + ? 'green' + : shareRatio >= 0.33 + ? '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' }, + render: () => ( + + + + ), + }, + { + menuItem: { content: 'Content', icon: 'folder open', key: 'content' }, + render: () => ( + + + + ), + }, + { + menuItem: { content: 'Errors', icon: 'warning sign', key: 'errors' }, + render: () => ( + + + + ), + }, + ]; + + return ( + + {loading && } + {!loading && ( + <> +
+
+ + History +
+ + {historyRanges.map(({ label }) => ( + + ))} + +
+ + + + + {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