aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Transfers/Uploads/UploadService.cs
blob: 05251ecfb4caadb3552f009d4246eb297a8534b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
// <copyright file="UploadService.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ Copyright (c) JP Dillingham.
//   │
//   │ This program is free software: you can redistribute it and/or modify
//   │ it under the terms of the GNU Affero General Public License as published
//   │ by the Free Software Foundation, version 3.
//   │
//   │ This program is distributed in the hope that it will be useful,
//   │ but WITHOUT ANY WARRANTY; without even the implied warranty of
//   │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   │ GNU Affero General Public License for more details.
//   │
//   │ You should have received a copy of the GNU Affero General Public License
//   │ along with this program.  If not, see https://www.gnu.org/licenses/.
//   │
//   │ This program is distributed with Additional Terms pursuant to Section 7
//   │ of the AGPLv3.  See the LICENSE file in the root directory of this
//   │ project for the complete terms and conditions.
//   │
//   │ https://slskd.org
//   │
//   ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
//   │ SPDX-FileCopyrightText: JP Dillingham
//   │ SPDX-License-Identifier: AGPL-3.0-only
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

using Microsoft.Extensions.Options;
using slskd.Files;
using Soulseek;

namespace slskd.Transfers.Uploads
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Query;
    using Serilog;
    using slskd.Events;
    using slskd.Relay;
    using slskd.Shares;
    using slskd.Users;

    /// <summary>
    ///     Manages uploads.
    /// </summary>
    public interface IUploadService
    {
        /// <summary>
        ///     Gets the upload governor.
        /// </summary>
        IUploadGovernor Governor { get; }

        /// <summary>
        ///     Gets the upload queue.
        /// </summary>
        IUploadQueue Queue { get; }

        /// <summary>
        ///     Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
        /// </summary>
        /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks>
        /// <param name="transfer"></param>
        void AddOrSupersede(Transfer transfer);

        /// <summary>
        ///     Enqueues the requested file.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="filename">The local filename of the requested file.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default);

        /// <summary>
        ///     Uploads the specified enqueued <paramref name="transfer"/> to the requesting user.
        /// </summary>
        /// <param name="transfer">The Transfer to upload.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
        /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
        /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception>
        /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception>
        Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default);

        /// <summary>
        ///     Finds a single upload matching the specified <paramref name="id"/>.
        /// </summary>
        /// <param name="id">The unique identifier of the upload.</param>
        /// <returns>The found transfer, or default if not found.</returns>
        Transfer Find(Guid id);

        /// <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 specified <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">An expression used to match uploads.</param>
        /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
        /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
        List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved);

        /// <summary>
        ///     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="states">One or more states by which uploads are filtered for pruning.</param>
        /// <returns>The number of pruned uploads.</returns>
        int Prune(int age, params TransferStates[] states);

        /// <summary>
        ///     Returns a list of all uploads matching the specified <paramref name="query"/>, projected to type <typeparamref name="TResult"/>.
        /// </summary>
        /// <typeparam name="TResult">The Type of the returned projection.</typeparam>
        /// <param name="query">The query expression.</param>
        /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
        /// <returns>The list of uploads matching the specified query.</returns>
        List<TResult> Query<TResult>(Func<IQueryable<Transfer>, IQueryable<TResult>> query, bool includeRemoved = false);

        /// <summary>
        ///     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>
        /// <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.
        /// </summary>
        /// <param name="id">The unique identifier for the upload.</param>
        /// <returns>A value indicating whether the upload was successfully cancelled.</returns>
        bool TryCancel(Guid id);

        /// <summary>
        ///     Fails the upload matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
        ///     and sets the final state accordingly.
        /// </summary>
        /// <remarks>
        ///     This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
        ///     the EndedAt or Exception properties if they have already been set. If the transfer State already includes
        ///     the terminal Completed flag, it is unchanged.
        /// </remarks>
        /// <param name="id">The unique identifier for the upload.</param>
        /// <param name="exception">The exception that caused the failure.</param>
        /// <returns>A value indicating whether the upload was successfully failed.</returns>
        bool TryFail(Guid id, Exception exception);

        /// <summary>
        ///     Synchronously updates the specified <paramref name="transfer"/>.
        /// </summary>
        /// <param name="transfer">The transfer to update.</param>
        void Update(Transfer transfer);
    }

    /// <summary>
    ///     Manages uploads.
    /// </summary>
    public class UploadService : IUploadService
    {
        public UploadService(
            FileService fileService,
            IUserService userService,
            ISoulseekClient soulseekClient,
            IOptionsMonitor<Options> optionsMonitor,
            IShareService shareService,
            IRelayService relayService,
            IDbContextFactory<TransfersDbContext> contextFactory,
            EventBus eventBus)
        {
            Files = fileService;
            Users = userService;
            Client = soulseekClient;
            Shares = shareService;
            Relay = relayService;
            ContextFactory = contextFactory;
            OptionsMonitor = optionsMonitor;
            EventBus = eventBus;

            Governor = new UploadGovernor(userService, optionsMonitor);
            Queue = new UploadQueue(userService, optionsMonitor);

            Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics());
        }

        /// <summary>
        ///     Gets the upload governor.
        /// </summary>
        public IUploadGovernor Governor { get; init; }

        /// <summary>
        ///     Gets the upload queue.
        /// </summary>
        public IUploadQueue Queue { get; init; }

        private FileService Files { get; }
        private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>();
        private ISoulseekClient Client { get; set; }
        private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
        private ILogger Log { get; } = Serilog.Log.ForContext<UploadService>();
        private IOptionsMonitor<Options> OptionsMonitor { get; }
        private IRelayService Relay { get; }
        private IShareService Shares { get; set; }
        private IUserService Users { get; set; }
        private EventBus EventBus { get; }
        private ConcurrentDictionary<string, bool> Locks { get; } = new();

        /// <summary>
        ///     Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
        /// </summary>
        /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string, CancellationToken)"/> instead.</remarks>
        /// <param name="transfer"></param>
        public void AddOrSupersede(Transfer transfer)
        {
            using var context = ContextFactory.CreateDbContext();

            var existing = context.Transfers
                .Where(t => t.Direction == TransferDirection.Upload)
                .Where(t => t.Username == transfer.Username)
                .Where(t => t.Filename == transfer.Filename)
                .Where(t => !t.Removed)
                .FirstOrDefault();

            if (existing != default)
            {
                Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username);
                existing.Removed = true;
            }

            context.Add(transfer);
            context.SaveChanges();
        }

        /// <summary>
        ///     Uploads the specified enqueued <paramref name="transfer"/> to the requesting user.
        /// </summary>
        /// <param name="transfer">The Transfer to upload.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
        /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
        /// <exception cref="DuplicateTransferException">Thrown if an upload matching the username and filename is already tracked by Soulseek.NET.</exception>
        /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception>
        public async Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            var syncRoot = new SemaphoreSlim(1, 1);

            string host = default;
            string localFilename = default;
            long localFileLength = default;
            var stateHistory = new List<TransferStates>();
            DateTime lastReportedAverageSpeed = default;

            var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}";

            if (!Locks.TryAdd(lockName, true))
            {
                Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName);
                return null;
            }

            /*
                from this point forward, any exit from this method MUST result in an update to the Transfer record
                in the database that sets EndedAt and ensures that the State property includes the Completed flag

                failure to do so means records will get "stuck" in the database/on the UI

                additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot
            */
            try
            {
                Log.Debug("Acquired lock {LockName}", lockName);

                /*
                    fetch an updated copy of the transfer record from the database; now that we are locked, we *should*
                    have exclusive access to this record

                    we're not using DbContext and tracked changes here because we don't want to hold a connection
                    open for the duration of the upload
                */
                transfer = Find(transfer.Id)
                    ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found");

                if (transfer.State != (TransferStates.Queued | TransferStates.Locally))
                {
                    throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}");
                }

                /*
                    Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic;
                    check that list to see if there's already an instance of this upload in it, just in case we've gotten
                    out of sync somehow
                */
                if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename))
                {
                    throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered");
                }

                // users with uploads must be watched so that we can keep informed of their online status, privileges, and
                // statistics. this is so that we can accurately determine their effective group.
                try
                {
                    if (!Users.IsWatched(transfer.Username))
                    {
                        await Users.WatchAsync(transfer.Username);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Failed to watch user {Username}", transfer.Username);
                }

                Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username);

                // locate the file on disk. we checked this once already when enqueueing, but it may have moved since
                // can throw NotFoundException
                (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename);

                using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true);

                var topts = new TransferOptions(
                    stateChanged: (args) =>
                    {
                        Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, transfer.Username, args.PreviousState, args.Transfer.State);

                        // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions;
                        // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup
                        if (Application.IsShuttingDown)
                        {
                            Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
                            return;
                        }

                        transfer = transfer.WithSoulseekTransfer(args.Transfer);

                        Telemetry.Metrics.Update(() =>
                        {
                            if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State))
                            {
                                Telemetry.Metrics.Transfers.Uploads.Queued.Files.Inc(1);
                                Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Inc(transfer.Size);
                            }

                            if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State))
                            {
                                Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1);
                                Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size);
                                Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1);
                                Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size);
                            }
                        }, cancellationToken);

                        stateHistory.Add(transfer.State);

                        // todo: broadcast
                        SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token);
                    },
                    progressUpdated: (args) => rateLimiter.Invoke(() =>
                    {
                        // don't do anything unless the `transfer` within the outer scope is in the
                        // InProgress state; this will help prevent out-of-band updates that are sometimes
                        // being made after the transfer is completed, causing them to appear 'stuck'
                        if (transfer.State == TransferStates.InProgress)
                        {
                            // don't wait for the semaphore; if a previous progress update is still hanging, don't make
                            // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems
                            // but the alternative is to continue to stack slow writes on top of one another
                            if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token))
                            {
                                try
                                {
                                    // update only the properties that we expect to change between progress updates
                                    // this helps prevent this update from 'stepping' on other updates
                                    transfer.BytesTransferred = args.Transfer.BytesTransferred;
                                    transfer.AverageSpeed = args.Transfer.AverageSpeed;

                                    using var context = ContextFactory.CreateDbContext();

                                    context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter
                                        .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred)
                                        .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed));

                                    // progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms)
                                    // the transfer's speed is also zero until it has enough data to compute the EMA, so throw both
                                    // repeated and zero values out
                                    var now = DateTime.UtcNow;

                                    if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000))
                                    {
                                        Telemetry.Metrics.Update(() =>
                                        {
                                            Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed);
                                        }, cancellationToken);

                                        lastReportedAverageSpeed = now;
                                    }
                                }
                                finally
                                {
                                    syncRoot.Release();
                                }
                            }
                            else
                            {
                                Log.Debug("Skipped progress update of {Filename} to {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size);
                            }
                        }
                    }),
                    seekInputStreamAutomatically: false,
                    disposeInputStreamOnCompletion: true, // note: don't set this to false!
                    governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct),
                    reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act),
                    slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(transfer, ct),
                    slotReleased: (tx) => Queue.Complete(transfer));

                // register the cancellation token
                CancellationTokens.TryAdd(transfer.Id, cts);

                // add the transfer to the UploadQueue so that it can become eligible for selection
                Queue.Enqueue(transfer);
                transfer.EnqueuedAt = DateTime.UtcNow;
                SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token);

                Soulseek.Transfer completedTransfer;

                if (host == Program.LocalHostName)
                {
                    completedTransfer = await Client.UploadAsync(
                        username: transfer.Username,
                        remoteFilename: transfer.Filename,
                        size: localFileLength,
                        inputStreamFactory: (startOffset) =>
                        {
#pragma warning disable S2930 // "IDisposables" should be disposed
                            // disposeInputStreamOnCompletion takes care of this
                            var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read);
#pragma warning restore S2930 // "IDisposables" should be disposed

                            stream.Seek(startOffset, SeekOrigin.Begin);
                            return Task.FromResult((Stream)stream);
                        },
                        options: topts,
                        cancellationToken: cts.Token);
                }
                else
                {
                    completedTransfer = await Client.UploadAsync(
                        username: transfer.Username,
                        remoteFilename: transfer.Filename,
                        size: localFileLength,
                        inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id),
                        options: topts,
                        cancellationToken: cts.Token);

                    Relay.TryCloseFileStream(host, id: transfer.Id);
                }

                // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we
                // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress
                rateLimiter.Dispose();

                // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state
                // over the top of the transfer record, then persist it
                transfer = transfer.WithSoulseekTransfer(completedTransfer);

                // todo: broadcast
                SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);

                Telemetry.Metrics.Update(() =>
                {
                    Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1);
                    Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred);
                    Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed);
                }, cancellationToken);

                EventBus.Raise(new UploadFileCompleteEvent
                {
                    Timestamp = transfer.EndedAt.Value,
                    LocalFilename = localFilename,
                    RemoteFilename = transfer.Filename,
                    Transfer = transfer,
                });

                return transfer;
            }
            catch (NotFoundException ex)
            {
                Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);

                SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
                TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted);

                // todo: broadcast transfer state to a hub
                Telemetry.Metrics.Update(() =>
                {
                    Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1);
                }, cancellationToken);

                throw;
            }
            catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
            {
                Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);

                SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
                TryFail(transfer.Id, exception: ex);

                // todo: broadcast transfer state to a hub
                Telemetry.Metrics.Update(() =>
                {
                    Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1);
                }, cancellationToken);

                throw;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);

                SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None);
                TryFail(transfer.Id, exception: ex);

                // todo: broadcast transfer state to a hub
                Telemetry.Metrics.Update(() =>
                {
                    Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1);
                }, cancellationToken);

                throw;
            }
            finally
            {
                Log.Debug("Upload of {Filename} to user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory);

                // figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes
                // for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something)
                // state will almost certainly transition to errored or completed before we get here, so we can't just take the last state
                var mostRecentQueuedOrInProgressState = stateHistory
                    .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s));

                Telemetry.Metrics.Update(() =>
                {
                    if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Value > 0)
                    {
                        Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1);
                        Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size);
                    }
                    else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.Queued.Files.Value > 0)
                    {
                        Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1);
                        Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size);
                    }
                }, cancellationToken);

                if (host != Program.LocalHostName)
                {
                    try
                    {
                        Relay.TryCloseFileStream(host, id: transfer.Id);
                    }
                    catch
                    {
                        // noop
                    }
                }

                try
                {
                    Locks.TryRemove(lockName, out _);
                    Log.Debug("Released lock {LockName}", lockName);

                    CancellationTokens.TryRemove(transfer.Id, out var registeredCts);
                    registeredCts?.TryDispose();
                    cts?.TryDispose();

                    // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked,
                    // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious
                    // and ensure it gets removed
                    Queue.TryComplete(transfer);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
                }
            }
        }

        /// <summary>
        ///     Enqueues the requested file.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="filename">The local filename of the requested file.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        public async Task<Transfer> EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username), "Username is required");
            }

            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(nameof(filename), "Filename is required");
            }

            var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}";

            if (!Locks.TryAdd(lockName, true))
            {
                Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName);
                return null;
            }

            Guid id = Guid.NewGuid();

            try
            {
                Log.Debug("Acquired lock {LockName}", lockName);

                Log.Information("Upload of {Filename} to {Username} requested", filename, username);

                using var context = ContextFactory.CreateDbContext();

                /*
                    first, get all past uploads to this user for this filename
                */
                var existingRecords = context.Transfers
                    .Where(t => t.Direction == TransferDirection.Upload)
                    .Where(t => t.Username == username)
                    .Where(t => t.Filename == filename)
                    .AsNoTracking()
                    .ToList();

                var existingInProgressRecords = existingRecords
                    .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
                    .ToList();

                /*
                    if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
                    an existing transfer record covering this file, and we're already enqueued. nothing more to do!
                */
                if (existingInProgressRecords.Count != 0)
                {
                    Log.Information("Upload of {Filename} to {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id)));
                    return null;
                }

                /*
                    check the tracked upload dictionary in Soulseek.NET to see if it knows about this already
                    it shouldn't, if the slskd database doesn't. but things could get desynced
                */
                if (Client.Uploads.Any(u => u.Username == username && u.Filename == filename))
                {
                    throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered");
                }

                /*
                    no existing transfers. next, check to see if they are requesting a file we are sharing

                    we do this after checking the database because database I/O is "cheaper" than disk and potentially
                    network (if we check a relay)
                */
                string host = default;
                string localFilename = default;
                long localFileLength = default;

                try
                {
                    (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: filename);
                }
                catch (NotFoundException)
                {
                    Log.Information("Upload of {Filename} to {Username} {Rejected}: {Message}", filename, username, "REJECTED", "File not shared.");
                    throw new DownloadEnqueueException($"File not shared.");
                }

                Log.Debug("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host);

                /*
                    we're cleared to enqueue! create a new transfer record, and automatically mark any existing records
                    we found as 'removed' to clean up the UI
                */
                var transfer = new Transfer()
                {
                    Id = id,
                    Username = username,
                    Direction = TransferDirection.Upload,
                    Filename = filename, // important! use the remote filename
                    Size = localFileLength,
                    RequestedAt = DateTime.UtcNow,
                    State = TransferStates.Queued | TransferStates.Locally,
                };

                context.Add(transfer);

                foreach (var record in existingRecords.Where(t => !t.Removed))
                {
                    record.Removed = true;
                    context.Update(record);
                    Log.Debug("Marked existing upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id);
                }

                context.SaveChanges();

                Log.Information("Successfully enqueued upload of {Filename} to {Username} (id: {Id})", filename, username, id);

                // users with uploads must be watched so that we can keep informed of their online status, privileges, and
                // statistics. this is so that we can accurately determine their effective group.
                try
                {
                    if (!Users.IsWatched(username))
                    {
                        await Users.WatchAsync(username);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Failed to watch user {Username}", username);
                }

                /*
                    schedule the upload immediately

                    Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and
                    fail the enqueue request
                */
                _ = Task.Run(() => UploadAsync(transfer)).ContinueWith(task =>
                {
                    if (task.IsCompletedSuccessfully)
                    {
                        Log.Information("Task for upload of {Filename} to {Username} completed successfully", filename, username);
                        return;
                    }

                    /*
                        things that can cause us to arrive here:

                        * file not found (moved, deleted somehow)
                        * transfer record deleted somehow
                        * transfer record updated so that it's no longer in Queued | Locally
                        * Soulseek.NET already tracking an identical upload (slskd <> Soulseek.NET desync)
                    */
                    Log.Error(task.Exception, "Task for upload of {Filename} to {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message);

                    if (!TryFail(id, task.Exception))
                    {
                        Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", id, task.Exception.Message);
                    }
                }, cancellationToken);

                return transfer;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to enqueue upload of {Filename} to {Username}: {Message}", filename, username, ex.Message);

                if (!TryFail(id, exception: ex))
                {
                    Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, ex.Message);
                    throw;
                }

                throw;
            }
            finally
            {
                if (Locks.TryRemove(lockName, out _))
                {
                    Log.Debug("Released lock {LockName}", lockName);
                }
            }
        }

        /// <summary>
        ///     Finds a single upload matching the specified <paramref name="id"/>.
        /// </summary>
        /// <param name="id">The unique identifier of the upload.</param>
        /// <returns>The found transfer, or default if not found.</returns>
        public Transfer Find(Guid id)
        {
            try
            {
                return Query(q => q.Where(t => t.Id == id), includeRemoved: true).SingleOrDefault();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to find upload: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     Returns a list of all uploads matching the specified <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">An expression used to match uploads.</param>
        /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
        /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
        public List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved)
        {
            expression ??= t => true;

            try
            {
                return Query(q => q.Where(expression), includeRemoved);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to list uploads: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     Returns a list of all uploads matching the specified <paramref name="query"/>, projected to type <typeparamref name="TResult"/>.
        /// </summary>
        /// <typeparam name="TResult">The Type of the returned projection.</typeparam>
        /// <param name="query">The query expression.</param>
        /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param>
        /// <returns>The list of uploads matching the specified query.</returns>
        public List<TResult> Query<TResult>(Func<IQueryable<Transfer>, IQueryable<TResult>> query, bool includeRemoved = false)
        {
            ArgumentNullException.ThrowIfNull(query);

            try
            {
                using var context = ContextFactory.CreateDbContext();

                var transfers = context.Transfers
                    .AsNoTracking()
                    .Where(t => t.Direction == TransferDirection.Upload);

                if (!includeRemoved)
                {
                    transfers = transfers.Where(t => !t.Removed);
                }

                var result = query(transfers);

                if (result.Provider is not IAsyncQueryProvider)
                {
                    throw new InvalidOperationException("Query must be fully translatable to SQL; in-memory evaluation is not allowed (remove any AsEnumerable() present in the query)");
                }

                return result.ToList();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to execute upload queury: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     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="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, params TransferStates[] states)
        {
            var statesSet = new HashSet<int>(states.Select(s => (int)s));

            if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
            {
                throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
            }

            try
            {
                using var context = ContextFactory.CreateDbContext();

                var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);

                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 => statesSet.Contains((int)t.State))
                    .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));

                if (pruned > 0)
                {
                    Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet);
                }

                return pruned;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to prune uploads: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     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>
        /// <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 count = context.Transfers
                    .Where(t => t.Direction == TransferDirection.Upload)
                    .Where(t => TransferStateCategories.Completed.Contains(t.State))
                    .Where(expression)
                    .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));

                Log.Debug("Removed {Count} uploads by expression", count);
                return count;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     Cancels the upload matching the specified <paramref name="id"/>, if it is in progress.
        /// </summary>
        /// <param name="id">The unique identifier for the upload.</param>
        /// <returns>A value indicating whether the upload was successfully cancelled.</returns>
        public bool TryCancel(Guid id)
        {
            if (CancellationTokens.TryRemove(id, out var cts))
            {
                cts.Cancel();
                return true;
            }

            return false;
        }

        /// <summary>
        ///     Fails the upload matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>,
        ///     and sets the final state accordingly.
        /// </summary>
        /// <remarks>
        ///     This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
        ///     the EndedAt or Exception properties if they have already been set. If the transfer State already includes
        ///     the terminal Completed flag, it is unchanged.
        /// </remarks>
        /// <param name="id">The unique identifier for the upload.</param>
        /// <param name="exception">The exception that caused the failure.</param>
        /// <returns>A value indicating whether the upload was successfully failed.</returns>
        public bool TryFail(Guid id, Exception exception)
        {
            var state = exception switch
            {
                NotFoundException => TransferStates.Aborted,
                OperationCanceledException => TransferStates.Cancelled,
                TimeoutException => TransferStates.TimedOut,
                _ => TransferStates.Errored,
            };

            return TryFail(id, exception.Message, state);
        }

        /// <summary>
        ///     Synchronously updates the specified <paramref name="transfer"/>.
        /// </summary>
        /// <param name="transfer">The transfer to update.</param>
        public void Update(Transfer transfer)
        {
            using var context = ContextFactory.CreateDbContext();

            context.Update(transfer);
            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();
        }

        protected virtual void EmitMetrics()
        {
            void EmitQueuedMetrics()
            {
                var queued = Client.Uploads.Where(u => u.State.HasFlag(TransferStates.Queued));

                Telemetry.Metrics.Transfers.Uploads.Queued.Users
                    .Set(queued.Select(u => u.Username).Distinct().Count());

                Telemetry.Metrics.Transfers.Uploads.Queued.Files
                    .Set(queued.Count());

                Telemetry.Metrics.Transfers.Uploads.Queued.Bytes
                    .Set(queued.Sum(q => q.Size));
            }

            void EmitInProgressMetrics()
            {
                var inProgress = Client.Uploads.Where(u => u.State == TransferStates.InProgress);

                Telemetry.Metrics.Transfers.Uploads.InProgress.Users
                    .Set(inProgress.Select(u => u.Username).Distinct().Count());

                Telemetry.Metrics.Transfers.Uploads.InProgress.Files
                    .Set(inProgress.Count());

                Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes
                    .Set(inProgress.Sum(u => u.Size));

                if (inProgress.Any())
                {
                    Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed
                        .Update(inProgress.Sum(u => u.AverageSpeed));

                    Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed
                        .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0);
                }
                else
                {
                    Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Reset();
                    Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Reset();
                }
            }

            Telemetry.Metrics.Update(() =>
            {
                EmitQueuedMetrics();
                EmitInProgressMetrics();
            });
        }

        private bool TryFail(Guid id, string exception, TransferStates state)
        {
            var t = Find(id);

            if (t is null)
            {
                return false;
            }

            t.EndedAt ??= DateTime.UtcNow;

            // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
            // exceptions in a database. when we encounter one of these, drop the first segment.
            var m = exception;
            t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;

            if (!t.State.HasFlag(TransferStates.Completed))
            {
                t.State = TransferStates.Completed | state;
            }

            try
            {
                Update(t);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to update database: {Message}", ex.Message);
                return false;
            }
        }

        /// <summary>
        ///     Resolves a remote file's location and size from shares and potentially disk.
        /// </summary>
        /// <param name="remoteFilename">The file to resolve.</param>
        /// <returns>The resolved host, filename (on disk), and length.</returns>
        /// <exception cref="NotFoundException">Thrown if the file can't be located, either in a share or on disk.</exception>
        private async Task<(string Host, string Filename, long Length)> ResolveFileInfoAsync(string remoteFilename)
        {
            string host;
            string filename;
            long length;

            /*
                locate the file and the stored details from shares.
                the size returned here will be the size the remote client is expecting.

                throws NotFoundException
            */
            (host, filename, length) = await Shares.ResolveFileAsync(remoteFilename);

            Log.Debug("Resolved shared file {RemoteFilename} to host {Host} and file {ShareFilename} (length: {ShareLength})", remoteFilename, host, filename, length);

            /*
                if the file is hosted locally, do some quick I/O to check to see if the file still exists at the location
                and of the size stored in the scan. the cost is negligible and this will keep transfers that are doomed
                to fail out of our queue.
            */
            if (host == Program.LocalHostName)
            {
                var info = Files.ResolveFileInfo(filename);

                // if the file doesn't exist we can't continue; shares have diverged from disk
                if (!info.Exists)
                {
                    Shares.RequestScan();
                    Log.Warning("The shared file '{File}' could not be located on disk. A share scan should be performed", filename);
                    throw new NotFoundException($"The file '{filename}' could not be located on disk. A share scan should be performed.");
                }

                // shares have diverged from disk, but we *MIGHT* be able to upload this file, if the remote client
                // doesn't care that the size is exact.  we definitely need to re-scan though.
                if (info.Length != length)
                {
                    Log.Warning("The length of shared file '{File}' differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, length, info.Length);
                    Shares.RequestScan();
                }

                length = info.Length;
            }
            else if (!OptionsMonitor.CurrentValue.Flags.OptimisticRelayFileInfo)
            {
                /*
                    if the file is hosted on a relay agent and the user has set the pessimistic flag to true,
                    get the file info from the agent.

                    this was, at one time, the default behavior, but users complained that it caused a lot of timeouts
                    so now it is opt-in.
                */
                var (exists, relayLength) = await Relay.GetFileInfoAsync(agentName: host, remoteFilename);

                if (!exists || relayLength <= 0)
                {
                    // todo: force a remote scan
                    throw new NotFoundException($"The file '{remoteFilename}' could not be located on Agent {host}. A share scan should be performed.");
                }

                if (relayLength != length)
                {
                    // todo: force a remote scan
                    Log.Warning("The length of shared file '{File}' on host {Host} differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, host, length, relayLength);
                }

                length = relayLength;
            }

            return (host, filename, length);
        }

        private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
        {
            semaphore.Wait(cancellationToken);

            try
            {
                Update(transfer);
            }
            finally
            {
                semaphore.Release();
            }
        }
    }
}