diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-01-11 16:37:02 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-01-11 16:37:02 -0600 |
| commit | 358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7 (patch) | |
| tree | ae86b9040faf8771c13b50406392dafbe50c506a /src/slskd/Transfers | |
| parent | 8849d78cbe7057dacad9c00c471691af8e367cd9 (diff) | |
| parent | 0f2df52cbfe2b8afd517a598cbaf9fc55c36083c (diff) | |
| download | slskd-358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7.tar.gz | |
Merge branch 'master' into paths
Diffstat (limited to 'src/slskd/Transfers')
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 30 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 95 | ||||
| -rw-r--r-- | src/slskd/Transfers/TransfersDbContext.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Transfers/Types/TransferStateCategories.cs | 116 | ||||
| -rw-r--r-- | src/slskd/Transfers/Types/UserUploadStatistics.cs | 35 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 138 |
6 files changed, 338 insertions, 94 deletions
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 068d1174..443a1b44 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -115,14 +115,16 @@ namespace slskd.Transfers.API return Forbid(); } - var transfers = Transfers.Downloads.List(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); - - foreach (var id in transfers.Select(t => t.Id)) + try { - Transfers.Downloads.Remove(id); + Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State)); + return NoContent(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove completed downloads: {Message}", ex.Message); + return StatusCode(500, ex.Message); } - - return NoContent(); } /// <summary> @@ -182,16 +184,16 @@ namespace slskd.Transfers.API return Forbid(); } - // get all the transfers that aren't removed - var transfers = Transfers.Uploads - .List(t => t.State.HasFlag(Soulseek.TransferStates.Completed), includeRemoved: false); - - foreach (var id in transfers.Select(t => t.Id)) + try { - Transfers.Uploads.Remove(id); + Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State)); + return NoContent(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove completed uploads: {Message}", ex.Message); + return StatusCode(500, ex.Message); } - - return NoContent(); } /// <summary> diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9bc25373..beeab755 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -89,16 +89,25 @@ namespace slskd.Transfers.Downloads /// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>. /// </summary> /// <param name="age">The age after which downloads are eligible for pruning, in hours.</param> - /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param> + /// <param name="states">One or more states by which downloads are filtered for pruning.</param> /// <returns>The number of pruned downloads.</returns> - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params TransferStates[] states); /// <summary> - /// Removes the download matching the specified <paramref name="id"/>. + /// Removes the completed download matching the specified <paramref name="id"/>. /// </summary> /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> /// <param name="id">The unique identifier of the download.</param> - void Remove(Guid id); + /// <returns>A value indicating whether the record was removed.</returns> + bool Remove(Guid id); + + /// <summary> + /// Removes all completed downloads matching the specified <paramref name="expression"/>. + /// </summary> + /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> + /// <param name="expression">The expression used to match downloads.</param> + /// <returns>The number of records removed.</returns> + int Remove(Expression<Func<Transfer, bool>> expression); /// <summary> /// Cancels the download matching the specified <paramref name="id"/>, if it is in progress. @@ -307,17 +316,22 @@ namespace slskd.Transfers.Downloads using var context = ContextFactory.CreateDbContext(); /* - get all past downloads from this user. this list will remain stable throughout this process because + get existing downloads from this user. this list will remain stable throughout this process because we have exclusive access for this user. we'll be adding new records, but we've already deduplicated them so we don't have to worry about duplicate records being created in the critical section + + we are looking for: + 1. anything that's not yet complete (we need to disallow the enqueue) + 2. anything complete, but not yet removed from the UI (we need to supersede it) */ - var existingRecords = context.Transfers + var existingRecordsNotYetRemoved = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Username == username) + .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State)) .AsNoTracking() .ToList(); - var existingInProgressRecords = existingRecords + var existingInProgressRecords = existingRecordsNotYetRemoved .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) .ToDictionary(t => t.Filename, t => t); @@ -401,7 +415,7 @@ namespace slskd.Transfers.Downloads Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed)) + foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !t.Removed)) { record.Removed = true; context.Update(record); @@ -663,13 +677,15 @@ namespace slskd.Transfers.Downloads /// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>. /// </summary> /// <param name="age">The age after which downloads are eligible for pruning, in hours.</param> - /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param> + /// <param name="states">One or more states by which downloads are filtered for pruning.</param> /// <returns>The number of pruned downloads.</returns> - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params TransferStates[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet<int>(states.Select(s => (int)s)); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -678,23 +694,16 @@ namespace slskd.Transfers.Downloads var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - var expired = context.Transfers + var pruned = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == stateHasFlag) - .ToList(); - - foreach (var tx in expired) - { - tx.Removed = true; - } - - var pruned = context.SaveChanges(); + .Where(t => statesSet.Contains((int)t.State)) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); if (pruned > 0) { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet); } return pruned; @@ -707,38 +716,40 @@ namespace slskd.Transfers.Downloads } /// <summary> - /// Removes the download matching the specified <paramref name="id"/>. + /// Removes the completed download matching the specified <paramref name="id"/>. /// </summary> /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> /// <param name="id">The unique identifier of the download.</param> - public void Remove(Guid id) + /// <returns>A value indicating whether the record was removed.</returns> + public bool Remove(Guid id) + { + return Remove(t => t.Id == id) > 0; + } + + /// <summary> + /// Removes all completed downloads matching the specified <paramref name="expression"/>. + /// </summary> + /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> + /// <param name="expression">The expression used to match downloads.</param> + /// <returns>The number of records removed.</returns> + public int Remove(Expression<Func<Transfer, bool>> expression) { try { using var context = ContextFactory.CreateDbContext(); - var transfer = context.Transfers + var count = context.Transfers .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Id == id) - .FirstOrDefault(); - - if (transfer == default) - { - throw new NotFoundException($"No download matching id ${id}"); - } - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); - } - - transfer.Removed = true; + .Where(t => TransferStateCategories.Completed.Contains(t.State)) + .Where(expression) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); - context.SaveChanges(); + Log.Debug("Removed {Count} downloads by expression", count); + return count; } catch (Exception ex) { - Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Failed to remove downloads by expression: {Message}", ex.Message); throw; } } diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index eac4935b..422595e9 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -70,6 +70,24 @@ namespace slskd.Transfers .Entity<Transfer>() .HasIndex(t => t.State) .HasDatabaseName("IDX_Transfers_State"); + + modelBuilder + .Entity<Transfer>() + .HasIndex(t => t.Removed) + .HasDatabaseName("IDX_Transfers_Removed"); + + // covers the check for existing records when enqueueing uploads and downloads + modelBuilder + .Entity<Transfer>() + .HasIndex(t => new { t.Username, t.Filename }) + .HasDatabaseName("IDX_Transfers_UsernameFilename"); + + // covers the GetUserStatistics method that backs limit checks + // check every so often with EXPLAIN to make sure it's being shown as a covering index + modelBuilder + .Entity<Transfer>() + .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) + .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); } } } diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs new file mode 100644 index 00000000..5ccbe572 --- /dev/null +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -0,0 +1,116 @@ +// <copyright file="TransferStateCategories.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfers; + +using System.Collections.Generic; +using Soulseek; + +/// <summary> +/// A collection of transfer state integers, grouped into sets that represent common states. +/// </summary> +/// <remarks> +/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Framework +/// turns HasFlag() expressions into. These hash sets allow us to use IN expressions instead of bitwise. +/// </remarks> +public static class TransferStateCategories +{ + /// <summary> + /// All states representing a successful transfer: + /// + /// <list type="bullet"> + /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item> + /// </list> + /// </summary> + public static readonly HashSet<TransferStates> Successful = [ + TransferStates.Completed | TransferStates.Succeeded // 16 | 32 = 48 + ]; + + /// <summary> + /// All states representing a failed transfer: + /// + /// <list type="bullet"> + /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item> + /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item> + /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item> + /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item> + /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item> + /// </list> + /// </summary> + public static readonly HashSet<TransferStates> Failed = [ + TransferStates.Completed | TransferStates.Cancelled, // 16 | 64 = 80 + TransferStates.Completed | TransferStates.TimedOut, // 16 | 128 = 144 + TransferStates.Completed | TransferStates.Errored, // 16 | 256 = 272 + TransferStates.Completed | TransferStates.Rejected, // 16 | 512 = 528 + TransferStates.Completed | TransferStates.Aborted, // 16 | 1024 = 1040 + ]; + + /// <summary> + /// All states containing the <see cref="TransferStates.Completed"/> flag. + /// + /// <list type="bullet"> + /// <item><see cref="TransferStates.Completed"/> (16)</item> + /// </list> + /// + /// Successful: + /// <list type="bullet"> + /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item> + /// </list> + /// + /// Failed: + /// <list type="bullet"> + /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item> + /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item> + /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item> + /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item> + /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item> + /// </list> + /// </summary> + public static readonly HashSet<TransferStates> Completed = [ + TransferStates.Completed, // 16, in case of some sort of a malfunction or regression + .. Successful, + .. Failed + ]; + + /// <summary> + /// All states representing a queued transfer: + /// + /// <list type="bullet"> + /// <item><see cref="TransferStates.Queued"/> (2)</item> + /// <item><see cref="TransferStates.Locally"/> (2 | 2048 = 2050)</item> + /// <item><see cref="TransferStates.Remotely"/> (2 | 4096 = 4098)</item> + /// </list> + /// </summary> + public static readonly HashSet<TransferStates> Queued = [ + TransferStates.Queued, // 2, in case of some sort of a malfunction or regression + TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050 + TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098 + ]; + + /// <summary> + /// All states representing a transfer that is in progress: + /// + /// <list type="bullet"> + /// <item><see cref="TransferStates.Initializing"/> (4)</item> + /// <item><see cref="TransferStates.InProgress"/> (8)</item> + /// </list> + /// </summary> + public static readonly HashSet<TransferStates> InProgress = [ + TransferStates.Initializing, // 4 + TransferStates.InProgress, // 8 + ]; +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/UserUploadStatistics.cs b/src/slskd/Transfers/Types/UserUploadStatistics.cs new file mode 100644 index 00000000..945964f5 --- /dev/null +++ b/src/slskd/Transfers/Types/UserUploadStatistics.cs @@ -0,0 +1,35 @@ +// <copyright file="UserUploadStatistics.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Upload statistics, for use when evaluating incoming enqueue requests against configured limits. +/// </summary> +public record UserUploadStatistics +{ + public int QueuedFiles { get; set; } + public long QueuedBytes { get; set; } + + public int WeeklyFailedFiles { get; set; } + public int WeeklySucceededFiles { get; set; } + public long WeeklySucceededBytes { get; set; } + + public int DailyFailedFiles { get; set; } + public int DailySucceededFiles { get; set; } + public long DailySucceededBytes { get; set; } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c96d1131..bcc1dd90 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -96,6 +96,14 @@ namespace slskd.Transfers.Uploads (int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression); /// <summary> + /// Gets upload statistics for the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param> + /// <returns>The gathered statistics.</returns> + UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null); + + /// <summary> /// Returns a list of all uploads matching the optional <paramref name="expression"/>. /// </summary> /// <param name="expression">An optional expression used to match uploads.</param> @@ -107,16 +115,25 @@ namespace slskd.Transfers.Uploads /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>. /// </summary> /// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param> - /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param> + /// <param name="states">One or more states by which uploads are filtered for pruning.</param> /// <returns>The number of pruned uploads.</returns> - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params TransferStates[] states); /// <summary> - /// Removes the upload matching the specified <paramref name="id"/>. + /// Removes the completed upload matching the specified <paramref name="id"/>. /// </summary> /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> /// <param name="id">The unique identifier of the upload.</param> - void Remove(Guid id); + /// <returns>A value indicating whether the record was removed.</returns> + bool Remove(Guid id); + + /// <summary> + /// Removes all completed uploads matching the specified <paramref name="expression"/>. + /// </summary> + /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> + /// <param name="expression">The expression used to match uploads.</param> + /// <returns>The number of records removed.</returns> + int Remove(Expression<Func<Transfer, bool>> expression); /// <summary> /// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress. @@ -780,13 +797,15 @@ namespace slskd.Transfers.Uploads /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>. /// </summary> /// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param> - /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param> + /// <param name="states">One or more states by which uploads are filtered for pruning.</param> /// <returns>The number of pruned uploads.</returns> - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params TransferStates[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet<int>(states.Select(s => (int)s)); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -795,23 +814,16 @@ namespace slskd.Transfers.Uploads var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - var expired = context.Transfers + var pruned = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State.HasFlag(stateHasFlag)) - .ToList(); - - foreach (var tx in expired) - { - tx.Removed = true; - } - - var pruned = context.SaveChanges(); + .Where(t => statesSet.Contains((int)t.State)) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); if (pruned > 0) { - Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet); } return pruned; @@ -824,38 +836,40 @@ namespace slskd.Transfers.Uploads } /// <summary> - /// Removes the upload matching the specified <paramref name="id"/>. + /// Removes the completed upload matching the specified <paramref name="id"/>. /// </summary> /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> /// <param name="id">The unique identifier of the upload.</param> - public void Remove(Guid id) + /// <returns>A value indicating whether the record was removed.</returns> + public bool Remove(Guid id) + { + return Remove(t => t.Id == id) > 0; + } + + /// <summary> + /// Removes all completed uploads matching the specified <paramref name="expression"/>. + /// </summary> + /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> + /// <param name="expression">The expression used to match uploads.</param> + /// <returns>The number of records removed.</returns> + public int Remove(Expression<Func<Transfer, bool>> expression) { try { using var context = ContextFactory.CreateDbContext(); - var transfer = context.Transfers + var count = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) - .Where(t => t.Id == id) - .FirstOrDefault(); - - if (transfer == default) - { - throw new NotFoundException($"No upload matching id ${id}"); - } - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete"); - } - - transfer.Removed = true; + .Where(t => TransferStateCategories.Completed.Contains(t.State)) + .Where(expression) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); - context.SaveChanges(); + Log.Debug("Removed {Count} uploads by expression", count); + return count; } catch (Exception ex) { - Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message); throw; } } @@ -913,6 +927,54 @@ namespace slskd.Transfers.Uploads context.SaveChanges(); } + /// <summary> + /// Gets upload statistics for the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the user.</param> + /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param> + /// <returns>The gathered statistics.</returns> + public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null) + { + utcNow ??= DateTime.UtcNow; + var dailyCutoff = utcNow.Value.AddDays(-1); + var weeklyCutoff = utcNow.Value.AddDays(-7); + + using var context = ContextFactory.CreateDbContext(); + + var failedStates = TransferStateCategories.Failed.ToList(); + var successState = TransferStates.Completed | TransferStates.Succeeded; + + var stats = context.Transfers + .AsNoTracking() + .Where(t => t.Username == username) + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => t.EndedAt == null || t.StartedAt >= weeklyCutoff) + .GroupBy(t => 1) // aggregate everything into one row + .Select(g => new UserUploadStatistics + { + QueuedFiles = g.Count(t => t.EndedAt == null), + QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0, + + // note: this generates some funky json_each() expression under the hood; it's an EF optimization + // that helps with optimization of query plans. i've tried expanding this out to force an IN + // and there's either no difference, or there's a slight improvement with the json_each method. + WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStates.Contains(t.State)), + + WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && t.State == successState), + WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && t.State == successState) + .Sum(t => (long?)t.Size) ?? 0, + + DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStates.Contains(t.State)), + + DailySucceededFiles = g.Count(t => t.StartedAt >= dailyCutoff && t.State == successState), + DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState) + .Sum(t => (long?)t.Size) ?? 0, + }) + .FirstOrDefault(); + + return stats ?? new UserUploadStatistics(); + } + private bool TryFail(Guid id, string exception, TransferStates state) { var t = Find(t => t.Id == id); |
