diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-07-07 12:56:13 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-07-07 12:56:13 -0500 |
| commit | ee5586754eb10b5df1c50f6cea53726369c087e7 (patch) | |
| tree | b79ce38202b213e60b3616215af8a06d75c209cf | |
| parent | 8aee7959f1daa96b40a8f742a0ec955096c9f527 (diff) | |
| parent | ada8c819946892bf680fc59202f2620f1aba4368 (diff) | |
| download | slskd-ee5586754eb10b5df1c50f6cea53726369c087e7.tar.gz | |
Merge pull request #1778 from slskd/dashboard
Add a Dashboard view, make it the default landing page
27 files changed, 3750 insertions, 44 deletions
diff --git a/bin/seed b/bin/seed new file mode 100755 index 00000000..91047762 --- /dev/null +++ b/bin/seed @@ -0,0 +1,344 @@ +#!/usr/bin/env bash +set -e + +database="" +from_date="" +db_path="$HOME/.local/share/slskd/data" +dry_run=false +clear_db=false +backup=false + +while test $# -gt 0; do + case "$1" in + -h|--help) + echo '' + echo 'usage: seed --database <name> --from <date> [options]' + echo '' + echo 'options:' + echo '-h, --help show help' + echo '--database NAME database to seed; supported: transfers' + echo '--from DATE seed records starting from this date (YYYY-MM-DD)' + echo '--db-path PATH path to database directory' + echo " default: \$HOME/.local/share/slskd/data" + echo '--backup back up the database before making any changes' + echo '--clear delete all existing records before seeding' + echo '--dry-run show what would be seeded without writing' + echo '' + exit 0 + ;; + --database) + shift + database=$1 + shift + ;; + --from) + shift + from_date=$1 + shift + ;; + --db-path) + shift + db_path=$1 + shift + ;; + --backup) + backup=true + shift + ;; + --clear) + clear_db=true + shift + ;; + --dry-run) + dry_run=true + shift + ;; + *) + break + ;; + esac +done + +if [ -z "$database" ]; then + echo 'error: --database is required' + exit 1 +fi + +if [ -z "$from_date" ]; then + echo 'error: --from is required' + exit 1 +fi + +case "$database" in + transfers) + echo $'\n\t🌱 seeding transfers database\n' + + if [ "$backup" == true ] && [ "$dry_run" == false ]; then + ts=$(date -u '+%m%d%y_%H%M%S') + backup_file="$db_path/backups/transfers.pre-seed-backup.$ts.db" + cp "$db_path/transfers.db" "$backup_file" + echo $'\t💾 backed up to '$(basename "$backup_file")$'\n' + fi + + FROM_DATE="$from_date" DB_PATH="$db_path" DRY_RUN="$dry_run" CLEAR_DB="$clear_db" node --no-warnings << 'JS' +'use strict'; +const { DatabaseSync } = require('node:sqlite'); +const { randomUUID } = require('node:crypto'); +const path = require('node:path'); + +const fromDate = new Date(process.env.FROM_DATE); +const dbPath = process.env.DB_PATH; +const dryRun = process.env.DRY_RUN === 'true'; +const clearDb = process.env.CLEAR_DB === 'true'; +const dbFile = path.join(dbPath, 'transfers.db'); + +// ── random helpers ──────────────────────────────────────────────────────────── + +const rand = (lo, hi) => Math.random() * (hi - lo) + lo; +const randInt = (lo, hi) => Math.floor(rand(lo, hi + 1)); +const choice = (arr) => arr[randInt(0, arr.length - 1)]; +const sample = (arr, n) => [...arr].sort(() => Math.random() - 0.5).slice(0, n); + +const weightedChoice = (choices, weights) => { + let r = Math.random() * weights.reduce((a, b) => a + b, 0); + for (let i = 0; i < choices.length; i++) { r -= weights[i]; if (r <= 0) return choices[i]; } + return choices[choices.length - 1]; +}; + +// ── name generation ─────────────────────────────────────────────────────────── + +const SYLLABLES = [ + 'al','an','ar','ax','az','ber','bor','cal','cor','dal','dar','dex', + 'dor','dral','ech','el','en','er','eth','ex','fal','fen','fer','fir', + 'for','gal','gar','gel','gen','gor','hal','har','hel','hor','il','in', + 'ir','ix','kel','ker','kor','kral','lan','lar','lel','len','ler','lir', + 'lor','mal','mar','mel','mir','mor','nal','nar','nel','ner','nir','nor', + 'ol','on','or','pal','par','pel','per','pir','por','qal','ral','ran', + 'rel','ren','rer','rir','ror','sal','sar','sel','ser','sir','sor','tal', + 'tar','tel','ter','tir','tor','ul','un','ur','val','var','vel','ver', + 'vir','vor','wal','war','wel','wer','xal','xar','xel','yer','yor','zel', + 'zen','zer','zir','zor', +]; + +const ADJECTIVES = [ + 'amber','ancient','ashen','black','blank','blind','broken','burnt', + 'calm','cold','coral','dark','dead','deep','dim','distant','dull', + 'dust','empty','errant','fallen','false','far','feral','flat','fold', + 'grey','grim','hollow','idle','inner','inverted','iron','jade','last', + 'late','lean','light','lone','lost','low','muted','narrow','near', + 'neon','numb','obscure','old','pale','phantom','quiet','raw','remote', + 'rigid','rusted','salt','shallow','sharp','sheer','silent','slow', + 'soft','still','strange','thin','tired','twin','twilight','void', + 'wandering','warm','weathered','white','wide','winter','worn', +]; + +const NOUNS = [ + 'arc','ash','beacon','bone','breach','cable','canal','carbon','carrier', + 'cell','chamber','chord','circuit','coast','code','coil','core','crest', + 'current','curve','decay','delta','depth','desert','digit','dome','door', + 'drift','echo','edge','epoch','field','filament','floor','flow','fold', + 'form','frame','gap','gate','glass','gradient','grain','grid','haze', + 'helix','hollow','horizon','hull','index','inlet','iris','junction', + 'kelp','layer','ledge','lens','light','line','loop','margin','membrane', + 'mesh','mirror','mode','motion','mount','node','null','orbit','origin', + 'oxide','peak','phase','pillar','plane','plate','point','pool','portal', + 'prism','pulse','radius','rail','range','reef','relay','ridge','ring', + 'root','route','ruin','shelf','shell','shore','signal','sink','slope', + 'span','sphere','spiral','stack','static','stem','stone','strand','stratum', + 'stream','surface','surge','terminal','terrain','tide','tower','trace', + 'tract','transit','trench','tunnel','valley','vector','vertex','void', + 'voltage','wave','wire','zone', +]; + +const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1); +const sylWord = (n = 2) => Array.from({ length: n }, () => choice(SYLLABLES)).join(''); + +const makeUsername = () => { + const sep = choice(['-', '_']); + switch (randInt(0, 3)) { + case 0: return `${choice(ADJECTIVES)}${sep}${choice(NOUNS)}`; + case 1: return `${choice(ADJECTIVES)}${sep}${choice(NOUNS)}${randInt(2, 99)}`; + case 2: return `${sylWord(2)}${randInt(10, 999)}`; + default: return `${sylWord(2)}${choice(['-', '_', ''])}${sylWord(2)}`; + } +}; + +const makeArtist = () => { + switch (randInt(0, 3)) { + case 0: return `${cap(sylWord(2))} ${cap(sylWord(2))}`; + case 1: return `The ${cap(sylWord(2))}s`; + case 2: return cap(sylWord(randInt(3, 5))); + default: return `${cap(sylWord(2))} & ${cap(sylWord(2))}`; + } +}; + +const makeAlbumName = () => { + switch (randInt(0, 4)) { + case 0: return `${cap(choice(ADJECTIVES))} ${cap(choice(NOUNS))}`; + case 1: return cap(choice(NOUNS)); + case 2: return `${cap(choice(ADJECTIVES))} ${cap(choice(ADJECTIVES))}`; + case 3: return cap(sylWord(3)); + default: return `${cap(choice(NOUNS))} ${randInt(1, 9)}`; + } +}; + +const makeTrackName = (n) => { + const num = String(n).padStart(2, '0'); + switch (randInt(0, 3)) { + case 0: return `${num} - ${cap(choice(ADJECTIVES))} ${cap(choice(NOUNS))}.flac`; + case 1: return `${num} - ${cap(sylWord(randInt(2, 4)))}.flac`; + case 2: return `${num} - ${cap(choice(NOUNS))} ${randInt(1, 9)}.flac`; + default: return `${num} - ${cap(choice(ADJECTIVES))}.flac`; + } +}; + +const makeAlbum = (artist) => { + const nTracks = randInt(5, 16); + const tracks = Array.from({ length: nTracks }, (_, i) => [makeTrackName(i + 1), randInt(8_000_000, 55_000_000)]); + if (Math.random() < 0.85) tracks.push(['folder.jpg', randInt(28_000, 90_000)]); + return { artist, album: makeAlbumName(), tracks }; +}; + +// ── constants ───────────────────────────────────────────────────────────────── + +const EXCEPTIONS = [ + 'A validation error has occurred.', + 'Transfer timed out.', + "The remote user's connection was reset.", + 'The remote user disconnected.', + "The remote user's queue is full.", +]; + +const STATE_SUCCEEDED = 48; // Completed | Succeeded (16 | 32) +const STATE_ERRORED = 272; // Completed | Errored (16 | 256) + +const HOUR_WEIGHTS = [ + 3, 4, 4, 3, 2, 1, // 00-05 late night + 1, 1, 1, 1, 1, 2, // 06-11 morning + 2, 2, 2, 2, 2, 3, // 12-17 afternoon + 4, 5, 5, 5, 4, 3, // 18-23 evening +]; + +// ── helpers ─────────────────────────────────────────────────────────────────── + +const uid = () => randomUUID().toUpperCase(); + +const ts = (ms) => { + const d = new Date(ms); + const pad = (n, len = 2) => String(n).padStart(len, '0'); + return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ` + + `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}.` + + `${pad(d.getUTCMilliseconds(), 3)}0000`; +}; + +// ── seed ────────────────────────────────────────────────────────────────────── + +const artistPool = Array.from({ length: randInt(12, 20) }, makeArtist); +const albumPool = Array.from({ length: randInt(30, 60) }, () => makeAlbum(choice(artistPool))); +const userPool = Array.from({ length: randInt(10, 20) }, makeUsername); + +const now = Date.now(); +const records = []; + +const addSession = (direction, album, peer, sessionStart) => { + let cursor = sessionStart + rand(8_000, 60_000); + + for (const [trackName, size] of album.tracks) { + const filename = `${album.artist}\\${album.album}\\${trackName}`; + const requestedAt = sessionStart + rand(0, 2_500); + const enqueuedAt = requestedAt + rand(100, 500); + + if (Math.random() < 0.05) { + const endedAt = requestedAt + rand(40, 300); + if (endedAt >= now) return; + records.push([ + uid(), peer, direction, filename, size, + STATE_ERRORED, 'Completed, Errored', + ts(requestedAt), null, null, ts(endedAt), + 0, 0.0, null, choice(EXCEPTIONS), + 0, null, 0, null, + ]); + } else { + const isCover = trackName.endsWith('.jpg') || trackName.endsWith('.png'); + const speed = isCover ? rand(200_000, 600_000) : rand(3_500_000, 9_500_000); + const startedAt = cursor + rand(50, 300); + const endedAt = startedAt + (size / speed) * 1_000; + if (endedAt >= now) return; + records.push([ + uid(), peer, direction, filename, size, + STATE_SUCCEEDED, 'Completed, Succeeded', + ts(requestedAt), ts(enqueuedAt), ts(startedAt), ts(endedAt), + size, speed, null, null, + 0, null, 1, null, + ]); + cursor = endedAt; + } + } +}; + +let current = new Date(fromDate); +current.setUTCHours(0, 0, 0, 0); + +while (current.getTime() < now) { + const nDownloads = weightedChoice([0, 1, 2, 3, 4], [0.10, 0.25, 0.35, 0.20, 0.10]); + const nUploads = weightedChoice([0, 1, 2, 3, 4], [0.15, 0.30, 0.30, 0.20, 0.05]); + + for (const [direction, nSessions] of [['Download', nDownloads], ['Upload', nUploads]]) { + for (let i = 0; i < nSessions; i++) { + const hour = weightedChoice([...Array(24).keys()], HOUR_WEIGHTS); + const sessionStart = current.getTime() + + hour * 3_600_000 + randInt(0, 59) * 60_000 + randInt(0, 59) * 1_000 + randInt(0, 999); + + if (sessionStart >= now) continue; + + const album = choice(albumPool); + const peer = choice(userPool); + + let tracks = album.tracks; + if (direction === 'Upload' && Math.random() < 0.6) { + tracks = sample(tracks, randInt(1, Math.max(1, tracks.length - 1))); + } + + addSession(direction, { ...album, tracks }, peer, sessionStart); + } + } + + current.setUTCDate(current.getUTCDate() + 1); +} + +process.stdout.write(`\n\t📊 ${records.length} records from ${fromDate.toISOString().slice(0, 10)} to ${new Date(now).toISOString().slice(0, 10)}\n`); + +if (dryRun) { + process.stdout.write('\n\t⏩ dry run; nothing written\n\n'); + process.exit(0); +} + +const db = new DatabaseSync(dbFile); +const stmt = db.prepare(` + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, + State, StateDescription, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, + BytesTransferred, AverageSpeed, PlaceInQueue, Exception, + Removed, BatchId, Attempts, NextAttemptAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +`); + +if (clearDb) { + db.exec('DELETE FROM Transfers; DELETE FROM Batches;'); + process.stdout.write('\n\t🗑️ cleared existing records\n'); +} + +db.exec('BEGIN'); +for (const r of records) stmt.run(...r); +db.exec('COMMIT'); +db.close(); + +process.stdout.write(`\n\t🎉 seeded ${records.length} records into ${dbFile}\n\n`); +JS + ;; + *) + echo "error: unknown database '$database'; supported: transfers" + exit 1 + ;; +esac diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index 5ced2def..ccb45daf 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; /// <summary> @@ -55,12 +56,16 @@ public class ReportsController : ControllerBase /// <summary> /// Initializes a new instance of the <see cref="ReportsController"/> class. /// </summary> - 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<ReportsController>(); /// <summary> @@ -128,7 +133,8 @@ public class ReportsController : ControllerBase /// </summary> /// <param name="start">The start time of the window (default: 7 days ago).</param> /// <param name="end">The end time of the window (default: now).</param> - /// <param name="interval">The interval, in minutes (default: 60).</param> + /// <param name="buckets">The number of evenly sized buckets that the data will be divided into (default: 100).</param> + /// <param name="interval">The interval, in minutes (default: null).</param> /// <param name="direction">An optional direction (Upload, Download) by which to filter records.</param> /// <param name="username">An optional username by which to filter records.</param> /// <returns></returns> @@ -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,42 @@ 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 (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"); + } + + 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.Select(t => (DateTime?)t.RequestedAt).Min()) ?? Program.GenesisDateTime; + } TransferDirection? transferDirection = null; @@ -189,6 +218,7 @@ public class ReportsController : ControllerBase return Ok(Telemetry.Reports.GetTransferHistogram( start: start.Value, end: end.Value, + buckets: buckets, interval: intervalTimeSpan, direction: transferDirection, username: username)); diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index ae2d1129..7cd245bf 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -137,32 +137,80 @@ public class ReportsService } /// <summary> - /// 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. /// </summary> /// <param name="start">The start time of the histogram window.</param> /// <param name="end">The end time of the histogram window.</param> - /// <param name="interval">The interval for the histogram.</param> + /// <param name="interval"> + /// The interval for the histogram. Mutually exclusive with <paramref name="buckets"/>; exactly one must + /// be specified. + /// </param> + /// <param name="buckets"> + /// The number of evenly sized buckets into which the histogram window should be divided. Mutually + /// exclusive with <paramref name="interval"/>; exactly one must be specified. + /// </param> /// <param name="direction">The optional direction (Upload or Download) by which to filter results.</param> /// <param name="username">The optional username by which to filter results.</param> /// <returns>A nested dictionary keyed by direction and state and containing summary information.</returns> - /// <exception cref="ArgumentException">Thrown if end time is not later than start time.</exception> + /// <exception cref="ArgumentException"> + /// Thrown if either <paramref name="start"/> or <paramref name="end"/> is default, if both <paramref name="interval"/> + /// and <paramref name="buckets"/> are specified, if neither is specified. + /// </exception> + /// <exception cref="ArgumentOutOfRangeException"> + /// Thrown if <paramref name="end"/> is not later than <paramref name="start"/>, or if <paramref name="buckets"/> + /// is outside of the allowed range. + /// </exception> public Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>> 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 > 1000 || buckets.Value < 1)) + { + throw new ArgumentOutOfRangeException(nameof(buckets), buckets, "Buckets must be between 1 and 1000"); + } + + 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<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>>(); // fill the dictionary with gapless intervals and empty dictionaries - var currentInterval = new DateTime(start.Ticks / interval.Ticks * interval.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) { @@ -171,7 +219,7 @@ public class ReportsService { TransferDirection.Download, new Dictionary<TransferStates, TransferSummary>() }, { TransferDirection.Upload, new Dictionary<TransferStates, TransferSummary>() }, }; - currentInterval = currentInterval.Add(interval); + currentInterval = currentInterval.Add(effectiveInterval); } var sql = @$" @@ -181,8 +229,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, + 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 @@ -203,7 +251,7 @@ public class ReportsService Username = username, Start = start, End = end, - Interval = (int)interval.TotalSeconds, + Interval = (int)effectiveInterval.TotalSeconds, }; var results = connection.Query<TransferSummaryRow>(sql, param); @@ -222,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 / interval.Ticks * interval.Ticks, DateTimeKind.Utc); + var bucketInterval = DateTime.SpecifyKind(result.Interval.Value, DateTimeKind.Utc); if (dict.TryGetValue(bucketInterval, out var intervalDict)) { @@ -361,22 +408,23 @@ public class ReportsService Direction, Filename, Size, - StartOffset, State, - RequestedAt + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, - CASE - WHEN INSTR(Exception, ':') > 0 + CASE + WHEN INSTR(Exception, ':') > 0 THEN SUBSTR(Exception, INSTR(Exception, ':') + 2) ELSE Exception END as Exception - FROM transfers + FROM transfers WHERE state & ~48 AND Direction = @Direction + AND EndedAt IS NOT NULL + AND EndedAt BETWEEN @Start AND @End {(username is not null ? "AND Username = @Username" : string.Empty)} ORDER BY EndedAt {sortOrder} LIMIT @Limit @@ -434,21 +482,23 @@ public class ReportsService } var sql = @$" - SELECT - CASE - WHEN INSTR(Exception, ':') > 0 + SELECT + CASE + WHEN INSTR(Exception, ':') > 0 THEN SUBSTR(Exception, INSTR(Exception, ':') + 2) ELSE Exception END as Exception, COUNT(*) as Count, COUNT(DISTINCT Username) as DistinctUsers - FROM transfers + FROM transfers WHERE state & ~48 AND Direction = @Direction + AND EndedAt IS NOT NULL + AND EndedAt BETWEEN @Start AND @End {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Direction, - CASE - WHEN INSTR(Exception, ':') > 0 + CASE + WHEN INSTR(Exception, ':') > 0 THEN SUBSTR(Exception, INSTR(Exception, ':') + 2) ELSE Exception END 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/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 <see cref="TransferService"/> class. /// </summary> public TransferService( + IDbContextFactory<TransfersDbContext> contextFactory, IUploadService uploadService = null, IDownloadService downloadService = null) { + ContextFactory = contextFactory; + Uploads = uploadService; Downloads = downloadService; } @@ -60,4 +69,87 @@ public class TransferService /// Gets the download service. /// </summary> public virtual IDownloadService Downloads { get; init; } + + private IDbContextFactory<TransfersDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<TransferService>(); + + /// <summary> + /// Finds a single transfer matching the specified <paramref name="expression"/>. + /// </summary> + /// <remarks> + /// 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. + /// </remarks> + /// <param name="expression">The expression to use to match transfers.</param> + /// <returns>The found transfer, or default if not found.</returns> + public virtual Transfer Find(Expression<Func<Transfer, bool>> 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; + } + } + + /// <summary> + /// Returns a list of all transfers matching the optional <paramref name="expression"/>. + /// </summary> + /// <remarks> + /// 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. + /// </remarks> + /// <param name="expression">An optional expression used to match transfers.</param> + /// <param name="includeRemoved">A value indicating whether to include transfers that have been removed previously.</param> + /// <returns>The list of transfers matching the specified expression, or all transfers if no expression is specified.</returns> + public virtual List<Transfer> List(Expression<Func<Transfer, bool>> 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; + } + } + + /// <summary> + /// Query the Transfers database arbitrarily. Only use if there's no better way. + /// </summary> + /// <typeparam name="TResult">The result Type.</typeparam> + /// <param name="query">The query function.</param> + /// <returns>The result.</returns> + public virtual TResult Query<TResult>(Func<IQueryable<Transfer>, 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 diff --git a/src/web/.env.development b/src/web/.env.development new file mode 100644 index 00000000..02269f00 --- /dev/null +++ b/src/web/.env.development @@ -0,0 +1 @@ +DISABLE_ESLINT_PLUGIN=true diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 81d1001c..0b0f9fb6 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -3,6 +3,7 @@ const overrides = { 'id-length': 'off', // noisy 'no-console': 'off', // noisy 'no-eq-null': 'off', // noisy + 'no-negated-condition': 'off', // noisy 'react/forbid-component-props': 'off', // noisy 'react/prop-types': 'off', // noisy 'canonical/sort-keys': 'off', // noisy diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 36e351bf..d5acb711 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -20,6 +20,7 @@ "react-responsive": "^9.0.0-beta.5", "react-router-dom": "^5.0.0", "react-toastify": "^9.0.1", + "recharts": "^2.15.4", "semantic-ui-less": "^2.5.0", "semantic-ui-react": "^2.1.0", "signalr": "^2.4.1", @@ -4654,6 +4655,69 @@ "@types/node": "*" } }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", + "license": "MIT" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", + "license": "MIT" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", + "license": "MIT" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "license": "MIT", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", + "license": "MIT" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "license": "MIT", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz", + "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==", + "license": "MIT", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", + "license": "MIT" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", + "license": "MIT" + }, "node_modules/@types/eslint": { "version": "8.40.1", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz", @@ -7686,6 +7750,133 @@ "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", "dev": true }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "license": "ISC", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz", + "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "license": "ISC", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "license": "ISC", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "license": "ISC", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "license": "ISC", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "license": "ISC", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/damerau-levenshtein": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", @@ -7761,6 +7952,12 @@ "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", "dev": true }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==", + "license": "MIT" + }, "node_modules/dedent": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", @@ -8025,6 +8222,16 @@ "utila": "~0.4" } }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, "node_modules/dom-serializer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", @@ -10389,8 +10596,7 @@ "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", - "dev": true + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==" }, "node_modules/events": { "version": "3.3.0", @@ -10582,6 +10788,15 @@ "integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==", "dev": true }, + "node_modules/fast-equals": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.0.tgz", + "integrity": "sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/fast-glob": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", @@ -12136,6 +12351,15 @@ "node": ">= 0.4" } }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/ipaddr.js": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.1.0.tgz", @@ -17682,6 +17906,21 @@ } } }, + "node_modules/react-smooth": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz", + "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==", + "license": "MIT", + "dependencies": { + "fast-equals": "^5.0.1", + "prop-types": "^15.8.1", + "react-transition-group": "^4.4.5" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/react-toastify": { "version": "9.1.3", "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-9.1.3.tgz", @@ -17694,6 +17933,22 @@ "react-dom": ">=16" } }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "license": "BSD-3-Clause", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, "node_modules/read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", @@ -17856,6 +18111,54 @@ "node": ">= 4" } }, + "node_modules/recharts": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz", + "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==", + "deprecated": "1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide", + "license": "MIT", + "dependencies": { + "clsx": "^2.0.0", + "eventemitter3": "^4.0.1", + "lodash": "^4.17.21", + "react-is": "^18.3.1", + "react-smooth": "^4.0.4", + "recharts-scale": "^0.4.4", + "tiny-invariant": "^1.3.1", + "victory-vendor": "^36.6.8" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/recharts-scale": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz", + "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==", + "license": "MIT", + "dependencies": { + "decimal.js-light": "^2.4.1" + } + }, + "node_modules/recharts/node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/recharts/node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, "node_modules/recursive-readdir": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/recursive-readdir/-/recursive-readdir-2.2.3.tgz", @@ -19945,9 +20248,10 @@ "dev": true }, "node_modules/tiny-invariant": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.1.tgz", - "integrity": "sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==" + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", + "license": "MIT" }, "node_modules/tiny-warning": { "version": "1.0.3", @@ -20643,6 +20947,28 @@ "node": ">= 0.8" } }, + "node_modules/victory-vendor": { + "version": "36.9.2", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz", + "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==", + "license": "MIT AND ISC", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, "node_modules/w3c-hr-time": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.2.tgz", diff --git a/src/web/package.json b/src/web/package.json index 8fe233f4..4c036f75 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -25,6 +25,7 @@ "react-responsive": "^9.0.0-beta.5", "react-router-dom": "^5.0.0", "react-toastify": "^9.0.1", + "recharts": "^2.15.4", "semantic-ui-less": "^2.5.0", "semantic-ui-react": "^2.1.0", "signalr": "^2.4.1", diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 9839bf35..3fbaa468 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -13,6 +13,7 @@ import AppContext from './AppContext'; import AppFooter from './AppFooter'; import Browse from './Browse/Browse'; import Chat from './Chat/Chat'; +import Dashboard from './Dashboard/Dashboard'; import LoginForm from './LoginForm'; import Rooms from './Rooms/Rooms'; import Searches from './Search/Searches'; @@ -398,6 +399,12 @@ class App extends Component { </Menu.Item> ) : ( <> + <Link to={`${urlBase}/dashboard`}> + <Menu.Item> + <Icon name="chart bar" /> + Dashboard + </Menu.Item> + </Link> <Link to={`${urlBase}/searches`}> <Menu.Item> <Icon name="search" /> @@ -574,6 +581,19 @@ class App extends Component { ) : ( <Switch> <Route + path={`${urlBase}/dashboard`} + render={(props) => + this.withTokenCheck( + <div className="view"> + <Dashboard + server={applicationState.server} + {...props} + /> + </div>, + ) + } + /> + <Route path={`${urlBase}/searches/:id?`} render={(props) => this.withTokenCheck( @@ -657,7 +677,7 @@ class App extends Component { /> <Redirect from="*" - to={`${urlBase}/searches`} + to={`${urlBase}/dashboard`} /> </Switch> )} diff --git a/src/web/src/components/AppFooter.jsx b/src/web/src/components/AppFooter.jsx index 261b5c11..9a295eb5 100644 --- a/src/web/src/components/AppFooter.jsx +++ b/src/web/src/components/AppFooter.jsx @@ -51,7 +51,7 @@ const AppFooter = ({ </Menu.Item> <Menu.Item> <Icon - color="orange" + color="green" name="arrow up" /> <span className="footer-upload">{formatSpeed(uploadSpeed)}</span> 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 new file mode 100644 index 00000000..4554d6d0 --- /dev/null +++ b/src/web/src/components/Dashboard/Dashboard.jsx @@ -0,0 +1,165 @@ +import './Dashboard.css'; +import * as reports from '../../lib/reports'; +import HistoricalStatistics from './HistoricalStatistics'; +import SearchBar from './SearchBar'; +import React, { useEffect, useMemo, useState } from 'react'; + +const HISTORY_RANGES = [ + { 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 = { + 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 { + buckets: range.buckets, + end: now.toISOString(), + start: + range.days != null + ? new Date(now - range.days * 86_400_000).toISOString() + : new Date(0).toISOString(), + }; + }, [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({ buckets: parameters.buckets, end, 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 ( + <div className="dashboard"> + <SearchBar server={server} /> + <HistoricalStatistics + activeTab={historyTab} + directories={data.directories} + exceptions={data.exceptions} + histogram={data.histogram} + historyEnd={historyParameters.end} + historyLabel={historyLabel} + historyRanges={HISTORY_RANGES} + historyStart={historyParameters.start} + leaderboard={data.leaderboard} + loading={loading} + onHistoryRangeSelect={(label) => setHistoryLabel(label)} + onTabChange={setHistoryTab} + summary={data.summary} + /> + </div> + ); +}; + +export default Dashboard; 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 }) => ( + <> + <Header + size="small" + style={{ alignItems: 'center', display: 'flex' }} + > + <Icon name="clipboard outline" /> + <Header.Content>Recent Errors</Header.Content> + <ButtonGroup + size="mini" + style={{ marginLeft: 'auto' }} + > + {DIRECTIONS.map((d) => ( + <Button + active={direction === d} + key={d} + onClick={() => onDirectionChange(d)} + > + {d} + </Button> + ))} + </ButtonGroup> + </Header> + <Table + className="unstackable" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell>Time</Table.HeaderCell> + <Table.HeaderCell>Direction</Table.HeaderCell> + <Table.HeaderCell>Username</Table.HeaderCell> + <Table.HeaderCell>Filename</Table.HeaderCell> + <Table.HeaderCell>Exception</Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body> + {loading && ( + <Table.Row> + <Table.Cell + colSpan={5} + textAlign="center" + > + <Loader + active + inline="centered" + size="small" + /> + </Table.Cell> + </Table.Row> + )} + {rows.length === 0 && !loading && ( + <Table.Row> + <Table.Cell + colSpan={5} + style={{ opacity: 0.5, textAlign: 'center' }} + > + No data to display + </Table.Cell> + </Table.Row> + )} + {!loading && + rows.map((row) => ( + <Table.Row key={`${row.direction}-${row.endedAt}-${row.filename}`}> + <Table.Cell style={{ whiteSpace: 'nowrap' }}> + {row.endedAt ? formatDate(row.endedAt) : ''} + </Table.Cell> + <Table.Cell>{row.direction}</Table.Cell> + <Table.Cell>{row.username}</Table.Cell> + <Table.Cell title={row.filename}> + {row.filename ? getFileName(row.filename) : ''} + </Table.Cell> + <Table.Cell title={row.exception}> + {truncate(row.exception, 80)} + </Table.Cell> + </Table.Row> + ))} + </Table.Body> + </Table> + </> +); + +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 ( + <> + <Header + size="small" + style={{ alignItems: 'center', display: 'flex' }} + > + <Icon name="sort amount down" /> + <Header.Content>Error Count By Type</Header.Content> + <ButtonGroup + size="mini" + style={{ marginLeft: 'auto' }} + > + {DIRECTIONS.map((d) => ( + <Button + active={direction === d} + key={d} + onClick={() => onDirectionChange(d)} + > + {d} + </Button> + ))} + </ButtonGroup> + </Header> + <Table + className="unstackable" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell>Direction</Table.HeaderCell> + <Table.HeaderCell>Exception</Table.HeaderCell> + <Table.HeaderCell style={{ width: '120px' }} /> + <Table.HeaderCell textAlign="right">Count</Table.HeaderCell> + <Table.HeaderCell textAlign="right"> + Distinct Users + </Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body> + {loading && ( + <Table.Row> + <Table.Cell + colSpan={5} + textAlign="center" + > + <Loader + active + inline="centered" + size="small" + /> + </Table.Cell> + </Table.Row> + )} + {!loading && rows.length === 0 && ( + <Table.Row> + <Table.Cell + colSpan={5} + style={{ opacity: 0.5, textAlign: 'center' }} + > + No data to display + </Table.Cell> + </Table.Row> + )} + {!loading && + rows.map((row) => ( + <Table.Row key={`${row.direction}-${row.exception ?? ''}`}> + <Table.Cell>{row.direction}</Table.Cell> + <Table.Cell title={row.exception}> + {truncate(row.exception, 80)} + </Table.Cell> + <Table.Cell> + <Progress + color="red" + percent={Math.round((row.count / maxCount) * 100)} + size="tiny" + style={{ margin: 0 }} + /> + </Table.Cell> + <Table.Cell textAlign="right"> + <strong>{row.count.toLocaleString()}</strong> + </Table.Cell> + <Table.Cell textAlign="right"> + {row.distinctUsers.toLocaleString()} + </Table.Cell> + </Table.Row> + ))} + </Table.Body> + </Table> + </> + ); +}; + +export default ExceptionPareto; diff --git a/src/web/src/components/Dashboard/HistoricalStatistics.jsx b/src/web/src/components/Dashboard/HistoricalStatistics.jsx new file mode 100644 index 00000000..a640fc1b --- /dev/null +++ b/src/web/src/components/Dashboard/HistoricalStatistics.jsx @@ -0,0 +1,334 @@ +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; +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, + Header, + Icon, + Segment, + Statistic, + Tab, +} from 'semantic-ui-react'; + +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 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: (v) => formatBytes(v, 1), + key: 'uploadBytes', + name: 'Upload Size', + unit: 'bytes', + }, + { + color: '#2185d0', + format: (v) => formatBytes(v, 1), + 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', + }, +]; + +const DEFAULT_HISTORY_SERIES = new Set(['uploadBytes', 'downloadBytes']); + +const HistoricalStatistics = ({ + activeTab, + directories, + exceptions, + histogram, + 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 historyPanes = [ + { + menuItem: { content: 'Users', icon: 'users', key: 'users' }, + render: () => ( + <Tab.Pane> + <Leaderboard + downloads={leaderboard.download} + end={historyEnd} + start={historyStart} + uploads={leaderboard.upload} + /> + </Tab.Pane> + ), + }, + { + menuItem: { content: 'Content', icon: 'folder open', key: 'content' }, + render: () => ( + <Tab.Pane> + <TopDirectories rows={directories} /> + </Tab.Pane> + ), + }, + { + menuItem: { content: 'Errors', icon: 'warning sign', key: 'errors' }, + render: () => ( + <Tab.Pane> + <TransferErrors + chartData={chartData} + download={exceptions.download} + end={historyEnd} + start={historyStart} + upload={exceptions.upload} + /> + </Tab.Pane> + ), + }, + ]; + + return ( + <Segment> + {loading && <LoaderSegment />} + {!loading && ( + <> + <div + style={{ + alignItems: 'center', + display: 'flex', + justifyContent: 'space-between', + marginBottom: '1em', + }} + > + <Header + as="h4" + style={{ margin: 0 }} + > + <Icon name="history" /> + <Header.Content>History</Header.Content> + </Header> + <ButtonGroup size="mini"> + {historyRanges.map(({ label }) => ( + <Button + active={historyLabel === label} + key={label} + onClick={() => onHistoryRangeSelect(label)} + > + {label} + </Button> + ))} + </ButtonGroup> + </div> + <Statistic.Group + size="small" + widths="four" + > + <Statistic color="blue"> + <Statistic.Value> + <Icon + name="arrow down" + size="tiny" + style={{ marginRight: '5px' }} + /> + {formatBytesParts(sumBytes(summary.Download ?? {})).value} + <span style={{ color: '#999', fontSize: '0.5em' }}> + {formatBytesParts(sumBytes(summary.Download ?? {})).unit} + </span> + </Statistic.Value> + <Statistic.Label> + Downloaded ·{' '} + {sumCounts(summary.Download ?? {}).toLocaleString()} files + </Statistic.Label> + </Statistic> + <Statistic color="green"> + <Statistic.Value> + <Icon + name="arrow up" + size="tiny" + style={{ marginRight: '5px' }} + /> + {formatBytesParts(sumBytes(summary.Upload ?? {})).value} + <span style={{ color: '#999', fontSize: '0.5em' }}> + {formatBytesParts(sumBytes(summary.Upload ?? {})).unit} + </span> + </Statistic.Value> + <Statistic.Label> + Uploaded · {sumCounts(summary.Upload ?? {}).toLocaleString()}{' '} + files + </Statistic.Label> + </Statistic> + <Statistic color={shareRatioColor}> + <Statistic.Value> + <Icon + name="chart pie" + size="mini" + style={{ marginRight: '5px' }} + /> + {shareRatio !== null ? shareRatio.toFixed(2) : '—'} + </Statistic.Value> + <Statistic.Label>Share ratio (↑/↓)</Statistic.Label> + </Statistic> + <Statistic> + <Statistic.Value> + <Icon + name="user" + size="mini" + style={{ marginRight: '5px' }} + /> + {( + (summary.Upload?.Succeeded?.distinctUsers ?? 0) + + (summary.Download?.Succeeded?.distinctUsers ?? 0) + ).toLocaleString()} + </Statistic.Value> + <Statistic.Label>Distinct peers</Statistic.Label> + </Statistic> + </Statistic.Group> + <div style={{ marginTop: '1.5em' }}> + <Graph + data={chartData} + defaultSeries={DEFAULT_HISTORY_SERIES} + series={HISTORY_SERIES} + /> + </div> + <Tab + activeIndex={activeTab} + onTabChange={(_, { activeIndex }) => onTabChange(activeIndex)} + panes={historyPanes} + /> + </> + )} + </Segment> + ); +}; + +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..a3df7d2c --- /dev/null +++ b/src/web/src/components/Dashboard/Leaderboard.jsx @@ -0,0 +1,198 @@ +import * as reports from '../../lib/reports'; +import { formatBytes, formatSpeed } from '../../lib/util'; +import React, { useEffect, useRef, useState } from 'react'; +import { Divider, Grid, Header, Icon, Loader, Table } from 'semantic-ui-react'; + +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 }) => ( + <Table + className="unstackable" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell + style={{ color: '#999', width: '2em' }} + textAlign="right" + > + # + </Table.HeaderCell> + <Table.HeaderCell>Username</Table.HeaderCell> + {SORT_FIELDS.map(({ label, sort }) => ( + <Table.HeaderCell + key={sort} + onClick={() => onSort(sort)} + style={sortHeaderStyle} + textAlign="right" + > + {label} + {sortBy === sort && ( + <Icon + name="chevron down" + style={{ marginLeft: '0.3em' }} + /> + )} + </Table.HeaderCell> + ))} + </Table.Row> + </Table.Header> + <Table.Body> + {loading && ( + <Table.Row> + <Table.Cell + colSpan={5} + textAlign="center" + > + <Loader + active + inline="centered" + size="small" + /> + </Table.Cell> + </Table.Row> + )} + {!loading && (!rows || rows.length === 0) && ( + <Table.Row> + <Table.Cell + colSpan={5} + style={{ opacity: 0.5, textAlign: 'center' }} + > + No data to display + </Table.Cell> + </Table.Row> + )} + {!loading && + rows && + rows.map((row, index) => ( + <Table.Row key={row.username}> + <Table.Cell + style={{ color: '#999' }} + textAlign="right" + > + {index + 1} + </Table.Cell> + <Table.Cell>{row.username}</Table.Cell> + <Table.Cell textAlign="right"> + {row.count.toLocaleString()} + </Table.Cell> + <Table.Cell textAlign="right"> + {formatBytes(row.totalBytes)} + </Table.Cell> + <Table.Cell textAlign="right"> + {formatSpeed(row.averageSpeed)} + </Table.Cell> + </Table.Row> + ))} + </Table.Body> + </Table> +); + +const initialState = { + sortBy: 'Count', + rows: { + upload: [], + download: [], + }, + loading: { + upload: false, + download: false, + }, +}; + +const Leaderboard = ({ downloads, end, start, uploads }) => { + const [state, setState] = useState(initialState); + const sortRef = useRef(null); + + useEffect(() => { + setState((previous) => ({ + ...previous, + sortBy: 'Count', + rows: { upload: uploads, download: downloads }, + })); + }, [downloads, uploads]); + + const onSort = async (sort) => { + if (sort === state.sortBy) return; + + sortRef.current = sort; + + 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(); + + 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, + }), + reports.getLeaderboard({ + direction: 'Download', + end: endDate, + sortBy: sort, + start: startDate, + }), + ]); + } catch (error) { + console.error(error); + } + + if (sortRef.current !== sort) return; + + setState((previous) => ({ + ...previous, + rows: { upload: newUploads, download: newDownloads }, + loading: { upload: false, download: false }, + })); + }; + + return ( + <Grid + columns={2} + stackable + > + <Grid.Column> + <Header size="small"> + <Icon name="download" /> Downloads + </Header> + <LeaderboardTable + loading={state.loading.download} + onSort={onSort} + rows={state.rows.download} + sortBy={state.sortBy} + /> + </Grid.Column> + <Divider vertical /> + <Grid.Column> + <Header size="small"> + <Icon name="upload" /> Uploads + </Header> + <LeaderboardTable + loading={state.loading.upload} + onSort={onSort} + rows={state.rows.upload} + sortBy={state.sortBy} + /> + </Grid.Column> + </Grid> + ); +}; + +export default Leaderboard; diff --git a/src/web/src/components/Dashboard/SearchBar.jsx b/src/web/src/components/Dashboard/SearchBar.jsx new file mode 100644 index 00000000..43e7d18a --- /dev/null +++ b/src/web/src/components/Dashboard/SearchBar.jsx @@ -0,0 +1,104 @@ +import '../Search/Search.css'; +import { urlBase } from '../../config'; +import * as library from '../../lib/searches'; +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'; +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( + <span> + Search for ‘{label}’ started.{' '} + <Link to={`${urlBase}/searches/${id}`}>View results</Link> + </span>, + ); + } + } catch (createError) { + console.error(createError); + toast.error( + createError?.response?.data ?? createError?.message ?? createError, + ); + setCreating(false); + } + }; + + useEffect(() => { + inputRef?.current?.inputRef?.current?.focus(); + }, []); + + return ( + <Segment + className="search-segment" + raised + > + <div className="search-segment-icon"> + <Icon + name="search" + size="big" + /> + </div> + <Input + action={ + <> + <Button + disabled={creating || !server?.isConnected} + icon="plus" + onClick={create} + /> + <Button + disabled={creating || !server?.isConnected} + icon="search" + onClick={() => create({ navigate: true })} + /> + </> + } + className="search-input" + disabled={creating || !server?.isConnected} + input={ + <input + data-lpignore="true" + placeholder={ + server?.isConnected + ? 'Search phrase' + : 'Connect to server to perform a search' + } + type="search" + /> + } + loading={creating} + onKeyUp={(keyUpEvent) => (keyUpEvent.key === 'Enter' ? create() : '')} + placeholder="Search phrase" + ref={inputRef} + size="big" + /> + </Segment> + ); +}; + +export default SearchBar; diff --git a/src/web/src/components/Dashboard/TopDirectories.jsx b/src/web/src/components/Dashboard/TopDirectories.jsx new file mode 100644 index 00000000..cadb3e80 --- /dev/null +++ b/src/web/src/components/Dashboard/TopDirectories.jsx @@ -0,0 +1,76 @@ +import React from 'react'; +import { Header, Icon, 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 }) => ( + <> + <Header size="small"> + <Icon name="folder open" /> Directories + </Header> + <Table + className="unstackable" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell + style={{ color: '#999', width: '2em' }} + textAlign="right" + > + # + </Table.HeaderCell> + <Table.HeaderCell>Directory</Table.HeaderCell> + <Table.HeaderCell textAlign="right">Downloads</Table.HeaderCell> + <Table.HeaderCell textAlign="right">Distinct Users</Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body> + {(!rows || rows.length === 0) && ( + <Table.Row> + <Table.Cell + colSpan={4} + style={{ opacity: 0.5, textAlign: 'center' }} + > + No data to display + </Table.Cell> + </Table.Row> + )} + {rows && + rows.map((row, index) => ( + <Table.Row key={row.directory}> + <Table.Cell + style={{ color: '#999' }} + textAlign="right" + > + {index + 1} + </Table.Cell> + <Table.Cell title={row.directory}> + {getLastTwoSegments(row.directory)} + </Table.Cell> + <Table.Cell textAlign="right"> + {row.count.toLocaleString()} + </Table.Cell> + <Table.Cell textAlign="right"> + {row.distinctUsers.toLocaleString()} + </Table.Cell> + </Table.Row> + ))} + </Table.Body> + </Table> + </> +); + +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..5246abd0 --- /dev/null +++ b/src/web/src/components/Dashboard/TransferErrors.jsx @@ -0,0 +1,167 @@ +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 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) => + [ + ...(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', + unit: 'count', + }, + { + color: '#a333c8', + format: (v) => v.toLocaleString(), + key: 'downloadErrors', + name: 'Download Errors', + unit: 'count', + }, +]; + +const DEFAULT_ERRORS_SERIES = new Set(['uploadErrors', 'downloadErrors']); + +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 [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 initialRecentRows = useMemo( + () => mergeRecent(upload.recent, download.recent), + [upload.recent, download.recent], + ); + + 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); + + 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); + } + }; + + const onRecentDirectionChange = async (d) => { + setRecentDirection(d); + setRecentLoading(true); + + 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); + } + }; + + return ( + <div> + <Header size="small"> + <Icon name="history" /> Errors + </Header> + <Graph + data={chartData ?? []} + defaultSeries={DEFAULT_ERRORS_SERIES} + series={ERRORS_SERIES} + /> + <ExceptionPareto + direction={paretoDirection} + loading={paretoLoading} + onDirectionChange={onParetoDirectionChange} + rows={displayedParetoRows} + /> + <ExceptionList + direction={recentDirection} + loading={recentLoading} + onDirectionChange={onRecentDirectionChange} + rows={displayedRecentRows} + /> + </div> + ); +}; + +export default TransferErrors; diff --git a/src/web/src/components/Shared/Graph.jsx b/src/web/src/components/Shared/Graph.jsx new file mode 100644 index 00000000..0f753b72 --- /dev/null +++ b/src/web/src/components/Shared/Graph.jsx @@ -0,0 +1,273 @@ +import { formatBytes, formatSpeed, formatWait } from '../../lib/util'; +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 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', + }); + } + + 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(() => { + 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 ( + <div + style={{ + background: bg, + border: `1px solid ${border}`, + borderRadius: 4, + fontSize: '0.875em', + padding: '6px 10px', + }} + > + <div + style={{ + color: labelColor, + fontWeight: 'bold', + fontSize: '1.05em', + marginBottom: 4, + }} + > + {xFormatter(label)} + </div> + {payload.map((entry) => { + const s = series.find((item) => item.name === entry.name); + const formatted = s?.format + ? s.format(entry.value) + : entry.value.toLocaleString(); + return ( + <div + key={entry.dataKey} + style={{ color: valueColor, display: 'flex', gap: '0.5em' }} + > + <span style={{ color: entry.color }}>▬</span> + <span>{entry.name}:</span> + <span>{formatted}</span> + </div> + ); + })} + </div> + ); + }; + + const renderLegend = ({ payload }) => ( + <div + style={{ + display: 'flex', + flexWrap: 'wrap', + fontSize: '0.875em', + gap: '1em', + justifyContent: 'center', + }} + > + {payload.map((entry) => ( + <span + aria-checked={visible.has(entry.dataKey)} + key={entry.dataKey} + onClick={() => 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} + > + <svg + height="10" + width="16" + > + <line + stroke={entry.color} + strokeWidth="2" + x1="0" + x2="16" + y1="5" + y2="5" + /> + </svg> + {entry.value} + </span> + ))} + </div> + ); + + return ( + <ResponsiveContainer + height={height} + width="100%" + > + <AreaChart data={data}> + <CartesianGrid + stroke={isDark ? 'rgba(255,255,255,0.20)' : '#d0d0d0'} + strokeDasharray="3 3" + /> + <XAxis + dataKey="timestamp" + domain={['dataMin', 'dataMax']} + style={axisStyle} + tickFormatter={xFormatter} + ticks={xTicks} + type="number" + /> + <YAxis + style={axisStyle} + tickFormatter={yFormatter} + /> + <Tooltip content={renderTooltip} /> + <Legend content={renderLegend} /> + {series.map(({ color, key, name }) => ( + <Area + dataKey={key} + dot={false} + fill={color} + fillOpacity={0.15} + hide={!visible.has(key)} + isAnimationActive={false} + key={key} + name={name} + stroke={color} + strokeOpacity={visible.has(key) ? 1 : 0} + type="monotone" + /> + ))} + </AreaChart> + </ResponsiveContainer> + ); +}; + +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'; diff --git a/src/web/src/lib/reports.js b/src/web/src/lib/reports.js new file mode 100644 index 00000000..9815fa9c --- /dev/null +++ b/src/web/src/lib/reports.js @@ -0,0 +1,133 @@ +import api from './api'; + +export const getSummary = async ({ + start, + end, + direction, + username = null, +} = {}) => { + const parameters = new URLSearchParams(); + + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + if (direction) parameters.append('direction', direction); + if (username) parameters.append('username', username); + + return (await api.get(`/telemetry/reports/transfers/summary?${parameters}`)) + .data; +}; + +export const getHistogram = async ({ + start, + end, + buckets, + direction, + username = null, +} = {}) => { + const parameters = new URLSearchParams(); + + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + if (buckets) parameters.append('buckets', buckets); + if (direction) parameters.append('direction', direction); + if (username) parameters.append('username', username); + + return (await api.get(`/telemetry/reports/transfers/histogram?${parameters}`)) + .data; +}; + +export const getLeaderboard = async ({ + direction, + start, + end, + sortBy = 'Count', + sortOrder = 'DESC', + limit = 10, + offset = 0, +} = {}) => { + const parameters = new URLSearchParams(); + + if (direction) parameters.append('direction', direction); + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + + parameters.append('sortBy', sortBy); + parameters.append('sortOrder', sortOrder); + parameters.append('limit', limit); + parameters.append('offset', offset); + + return ( + await api.get(`/telemetry/reports/transfers/leaderboard?${parameters}`) + ).data; +}; + +export const getTopDirectories = async ({ + start, + end, + username = null, + limit = 10, + offset = 0, +} = {}) => { + const parameters = new URLSearchParams(); + + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + if (username) parameters.append('username', username); + + parameters.append('limit', limit); + parameters.append('offset', offset); + + return ( + await api.get(`/telemetry/reports/transfers/directories?${parameters}`) + ).data; +}; + +export const getExceptions = async ({ + direction, + start, + end, + username, + sortOrder = 'DESC', + limit = 10, + offset = 0, +} = {}) => { + const parameters = new URLSearchParams(); + + if (direction) parameters.append('direction', direction); + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + if (username) parameters.append('username', username); + + parameters.append('sortOrder', sortOrder); + parameters.append('limit', limit); + parameters.append('offset', offset); + + return ( + await api.get(`/telemetry/reports/transfers/exceptions?${parameters}`) + ).data; +}; + +export const getExceptionPareto = async ({ + direction, + start, + end, + username = null, + limit = 10, + offset = 0, +} = {}) => { + const parameters = new URLSearchParams(); + + if (direction) parameters.append('direction', direction); + if (start) parameters.append('start', start.toISOString()); + if (end) parameters.append('end', end.toISOString()); + if (username) parameters.append('username', username); + + parameters.append('limit', limit); + parameters.append('offset', offset); + + return ( + await api.get( + `/telemetry/reports/transfers/exceptions/pareto?${parameters}`, + ) + ).data; +}; diff --git a/src/web/src/lib/reports.test.js b/src/web/src/lib/reports.test.js new file mode 100644 index 00000000..12bdfd0d --- /dev/null +++ b/src/web/src/lib/reports.test.js @@ -0,0 +1,330 @@ +import api from './api'; +import * as reports from './reports'; + +jest.mock('./api', () => ({ + __esModule: true, + 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: {} }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + 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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('appends direction when provided', async () => { + expect.hasAssertions(); + await reports.getSummary({ direction: 'Upload' }); + expect(parametersOf().get('direction')).toBe('Upload'); + }); + + it('appends username when provided', async () => { + expect.hasAssertions(); + await reports.getSummary({ username: 'testuser' }); + expect(parametersOf().get('username')).toBe('testuser'); + }); + + it('omits optional params when not provided', async () => { + expect.hasAssertions(); + await reports.getSummary(); + const p = parametersOf(); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + expect(p.has('direction')).toBe(false); + expect(p.has('username')).toBe(false); + }); + }); + + 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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('appends buckets when provided', async () => { + expect.hasAssertions(); + await reports.getHistogram({ buckets: 50 }); + expect(parametersOf().get('buckets')).toBe('50'); + }); + + it('appends direction when provided', async () => { + expect.hasAssertions(); + await reports.getHistogram({ direction: 'Download' }); + expect(parametersOf().get('direction')).toBe('Download'); + }); + + it('appends username when provided', async () => { + expect.hasAssertions(); + await reports.getHistogram({ username: 'testuser' }); + expect(parametersOf().get('username')).toBe('testuser'); + }); + + it('omits optional params when not provided', async () => { + expect.hasAssertions(); + await reports.getHistogram(); + const p = parametersOf(); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + expect(p.has('buckets')).toBe(false); + expect(p.has('direction')).toBe(false); + expect(p.has('username')).toBe(false); + }); + }); + + 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(parametersOf().get('direction')).toBe('Upload'); + }); + + it('defaults limit to 10', async () => { + expect.hasAssertions(); + await reports.getLeaderboard(); + expect(parametersOf().get('limit')).toBe('10'); + }); + + it('appends the specified limit', async () => { + expect.hasAssertions(); + await reports.getLeaderboard({ limit: 25 }); + expect(parametersOf().get('limit')).toBe('25'); + }); + + it('defaults sortBy to Count', async () => { + expect.hasAssertions(); + await reports.getLeaderboard(); + expect(parametersOf().get('sortBy')).toBe('Count'); + }); + + it('appends the specified sortBy', async () => { + expect.hasAssertions(); + await reports.getLeaderboard({ sortBy: '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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('omits start and end when not provided', async () => { + expect.hasAssertions(); + await reports.getLeaderboard(); + const p = parametersOf(); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + }); + }); + + 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(parametersOf().get('limit')).toBe('10'); + }); + + it('appends the specified limit', async () => { + expect.hasAssertions(); + await reports.getTopDirectories({ limit: 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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('omits start and end when not provided', async () => { + expect.hasAssertions(); + await reports.getTopDirectories(); + const p = parametersOf(); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + }); + }); + + describe('getExceptionPareto', () => { + it('calls the correct endpoint', async () => { + expect.hasAssertions(); + await reports.getExceptionPareto(); + expect(urlOf()).toContain( + '/telemetry/reports/transfers/exceptions/pareto', + ); + }); + + it('appends direction when provided', async () => { + expect.hasAssertions(); + await reports.getExceptionPareto({ direction: 'Download' }); + expect(parametersOf().get('direction')).toBe('Download'); + }); + + it('defaults limit to 10', async () => { + expect.hasAssertions(); + await reports.getExceptionPareto(); + expect(parametersOf().get('limit')).toBe('10'); + }); + + it('appends the specified limit', async () => { + expect.hasAssertions(); + await reports.getExceptionPareto({ limit: 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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); + await reports.getExceptionPareto(); + const p = parametersOf(); + expect(p.has('direction')).toBe(false); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + }); + }); + + 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(parametersOf().get('direction')).toBe('Upload'); + }); + + it('defaults limit to 10', async () => { + expect.hasAssertions(); + await reports.getExceptions(); + expect(parametersOf().get('limit')).toBe('10'); + }); + + it('appends the specified limit', async () => { + expect.hasAssertions(); + await reports.getExceptions({ limit: 50 }); + expect(parametersOf().get('limit')).toBe('50'); + }); + + it('defaults sortOrder to DESC', async () => { + expect.hasAssertions(); + await reports.getExceptions(); + expect(parametersOf().get('sortOrder')).toBe('DESC'); + }); + + it('appends the specified sortOrder', async () => { + expect.hasAssertions(); + await reports.getExceptions({ sortOrder: '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(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(parametersOf().get('end')).toBe(end.toISOString()); + }); + + it('omits direction, start, and end when not provided', async () => { + expect.hasAssertions(); + await reports.getExceptions(); + const p = parametersOf(); + expect(p.has('direction')).toBe(false); + expect(p.has('start')).toBe(false); + expect(p.has('end')).toBe(false); + }); + }); +}); diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index caced7ac..854e625e 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -39,10 +39,27 @@ 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 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(); }; +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(); }; @@ -106,7 +123,6 @@ export const sleep = (milliseconds) => { */ export const downloadFile = (data, filename, mime) => { const blob = new Blob([data], { type: mime || 'application/octet-stream' }); - // eslint-disable-next-line no-negated-condition if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE workaround for "HTML7007: One or more blob URLs were // revoked by closing the blob for which they were created. 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<ArgumentException>(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<ArgumentException>(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<ArgumentOutOfRangeException>(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<ArgumentOutOfRangeException>(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<ArgumentException>(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<ArgumentException>(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<ArgumentOutOfRangeException>(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<ArgumentOutOfRangeException>(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<ArgumentOutOfRangeException>(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<ArgumentOutOfRangeException>(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<ArgumentOutOfRangeException>(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<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>> + histogram(ReportsService sut) => + sut.GetTransferHistogram(Start, End, buckets: 1); + + private static long TotalCount( + Dictionary<DateTime, Dictionary<TransferDirection, Dictionary<TransferStates, TransferSummary>>> 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, ConnectionString> { { Database.Transfers, mocks.ConnectionString } })); + return (mocks, sut); + } + + private class Mocks + { + private readonly SqliteConnection _anchor; + private readonly DbContextOptions<TransfersDbContext> _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<TransfersDbContext>() + .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(); + } + } +} 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, ConnectionString> { { 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); + } +} |
