aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Transfers/Downloads/DownloadService.cs
blob: 707221accccdadfc0d5f7afabaa51cc6ad8b6ece (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
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
// <copyright file="DownloadService.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 Soulseek;

namespace slskd.Transfers.Downloads
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Net;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    using Serilog;
    using slskd.Events;
    using slskd.Files;
    using slskd.Integrations.FTP;
    using slskd.Relay;
    using slskd.Search;

    /// <summary>
    ///     Manages downloads.
    /// </summary>
    public interface IDownloadService
    {
        /// <summary>
        ///     Gets download batch service.
        /// </summary>
        IBatchService Batches { 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 EnqueueAsync() instead.</remarks>
        /// <param name="transfer"></param>
        void AddOrSupersede(Transfer transfer);

        /// <summary>
        ///     Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and batch
        ///     configuration.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
        ///         Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
        ///     </para>
        ///     <para>
        ///         Empty segments may be present in the output, which more closely aligns with user intent. The
        ///         <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
        ///     </para>
        /// </remarks>
        /// <param name="transfer">The transfer.</param>
        /// <returns>The derived destination directory.</returns>
        /// <exception cref="NotFoundException">Thrown if the specified download doesn't exist.</exception>
        /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
        Task<string> DeriveDestination(Transfer transfer);

        /// <summary>
        ///     Enqueues the requested list of <paramref name="files"/>.
        /// </summary>
        /// <remarks>
        ///     If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
        ///     thrown after all files are dispositioned if any throws.
        /// </remarks>
        /// <param name="username">The username of remote user.</param>
        /// <param name="files">The list of files to enqueue.</param>
        /// <param name="batchId">The optional batch id for the transfers.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
        /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
        /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
        Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default);

        /// <summary>
        ///     Finds a single download matching the specified <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">The expression to use to match downloads.</param>
        /// <returns>The found transfer, or default if not found.</returns>
        Transfer Find(Expression<Func<Transfer, bool>> expression);

        /// <summary>
        ///     Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
        /// </summary>
        /// <param name="id">The unique identifier for the download.</param>
        /// <returns>The retrieved place in queue.</returns>
        Task<int> GetPlaceInQueueAsync(Guid id);

        /// <summary>
        ///     Returns a list of all downloads matching the optional <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">An optional expression used to match downloads.</param>
        /// <param name="includeRemoved">Optionally include downloads that have been removed previously.</param>
        /// <returns>The list of downloads matching the specified expression, or all downloads if no expression is specified.</returns>
        List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);

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

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

        /// <summary>
        ///     Fails the download 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 download.</param>
        /// <param name="exception">The exception that caused the failure.</param>
        /// <returns>A value indicating whether the download was successfully failed.</returns>
        bool TryFail(Guid id, Exception exception);

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

    /// <summary>
    ///     Manages downloads.
    /// </summary>
    public class DownloadService : IDownloadService
    {
        public DownloadService(
            IBatchService batchService,
            ISearchService searchService,
            IOptionsMonitor<Options> optionsMonitor,
            ISoulseekClient soulseekClient,
            IDbContextFactory<TransfersDbContext> contextFactory,
            FileService fileService,
            IRelayService relayService,
            IFTPService ftpClient,
            EventBus eventBus,
            TimeProvider timeProvider = null)
        {
            Batches = batchService;
            Searches = searchService;
            Client = soulseekClient;
            OptionsMonitor = optionsMonitor;
            ContextFactory = contextFactory;
            Files = fileService;
            FTP = ftpClient;
            Relay = relayService;
            EventBus = eventBus;

            TimeProvider = timeProvider ?? TimeProvider.System;

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

        /// <summary>
        ///     Gets download batch service.
        /// </summary>
        public IBatchService Batches { get; }

        /// <summary>
        ///     These tokens give users the ability to cancel transfers via the UI (or API).
        ///
        ///     The lifecycle is:
        ///
        ///     1. in EnqueueAsync(), just before transfer records are added to the database, these CTS are created and
        ///        added to the dictionary
        ///     2. in EnqueueAsync(), if there was an error or any condition which caused the transfer to not proceed was met,
        ///        the CTS is removed from the dictionary and disposed
        ///     3. in DownloadAsync(), in the finally block after all post-download logic has been executed, the CTS
        ///        is removed and disposed.
        ///
        ///     The CTS should be in the dictionary the entire time the transfer is "in flight", from the first moment it
        ///     comes into being (via database insert) until the eventual download process has completed or failed.
        ///
        ///     Every cancellable operation in this flow needs to use this CTS token either directly or by linking it with another,
        ///     or we risk transfers getting stuck with no way for users to get rid of them.
        /// </summary>
        private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>();
        private ISoulseekClient Client { get; }
        private IDbContextFactory<TransfersDbContext> ContextFactory { get; }
        private IFTPService FTP { get; }
        private FileService Files { get; }
        private ISearchService Searches { get; }
        private IRelayService Relay { get; }
        private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>();
        private IOptionsMonitor<Options> OptionsMonitor { get; }
        private EventBus EventBus { get; }
        private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        private TimeProvider TimeProvider { get; }

        /// <summary>
        ///     Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they
        ///     don't already exist, and a timer asynchronously cleans the dictionary up.
        /// </summary>
        private ConcurrentDictionary<string, SemaphoreSlim> EnqueueSemaphores { get; } = [];

        /// <summary>
        ///     Synchronizes the cleanup process; after gaining exclusive access over the dictionary, checks each entry
        ///     to see if the containing semaphore can be obtained immediately.  If so, it's not in use and is therefore
        ///     removed from the dictionary and discarded.
        /// </summary>
        private SemaphoreSlim EnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(initialCount: 1, maxCount: 1);

        /// <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 EnqueueAsync() 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.Download)
                .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>
        ///     Enqueues the requested list of <paramref name="files"/>.
        /// </summary>
        /// <param name="username">The username of the remote user.</param>
        /// <param name="files">The list of files to enqueue.</param>
        /// <param name="batchId">The optional batch id for the transfers.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation.</param>
        /// <returns>The operation context.</returns>
        /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
        /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
        /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
        public async Task<(List<Transfer> Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Username is required", nameof(username));
            }

            var fileList = files?.ToList() ?? [];

            if (fileList.Count == 0)
            {
                throw new ArgumentException("At least one file is required", nameof(files));
            }

            if (fileList.Any(f => string.IsNullOrEmpty(f.Filename)))
            {
                throw new ArgumentException("At least one filename is null or empty", nameof(files));
            }

            if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename)))
            {
                throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files));
            }

            if (fileList.Count != fileList.Select(f => f.Filename).Distinct().Count())
            {
                throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
            }

            IPEndPoint endpoint;

            Log.Information("Requested enqueue of {Count} files from user {Username}", fileList.Count, username);

            // get the user's ip and port. this will throw if they are offline.
            try
            {
                endpoint = await Client.GetUserEndPointAsync(username, cancellationToken);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
                throw;
            }

            // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop
            try
            {
                Log.Debug("Priming message connection to {Username}", username);
                await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message);
                throw;
            }

            List<Transfer> enqueued = [];
            List<(string Filename, string Message)> failed = [];

            SemaphoreSlim userSemaphore;
            Task userSemaphoreWaitTask;

            Log.Debug("Awaiting enqueue semaphore sync root");
            await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken);

            try
            {
                Log.Debug("Acquired enqueue semaphore sync root");
                userSemaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1));
                userSemaphoreWaitTask = userSemaphore.WaitAsync(cancellationToken);
            }
            finally
            {
                EnqueueSemaphoreSyncRoot.Release();
                Log.Debug("Released enqueue semaphore sync root");
            }

            Log.Debug("Awaiting enqueue semaphore for user {Username}", username);
            await userSemaphoreWaitTask;

            try
            {
                Log.Debug("Acquired enqueue semaphore for user {Username}", username);

                using var context = ContextFactory.CreateDbContext();

                /*
                    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 existingRecordsNotYetRemoved = context.Transfers
                    .Where(t => t.Direction == TransferDirection.Download)
                    .Where(t => t.Username == username)
                    .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State))
                    .AsNoTracking() // note: AI wants to remove this, dont.
                    .ToList();

                var existingInProgressRecords = existingRecordsNotYetRemoved
                    .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
                    .ToDictionary(t => t.Filename, t => t);

                /*
                    determine how many concurrent enqueue requests we want to send to the remote client.

                    sending a ton of them can bog the client down and fail transfers due to resource contention on both sides,
                    but both clients should be able to handle momentary 'bursts'.

                    if the request contains 30 files or fewer, send all of the requests at the same time. the average number
                    of tracks in a single album is 15, so this is 2x as many as most enqueue requests will need.

                    if that number is more than 30, send only 5 at a time; transfers will be starting as we are still
                    enqueueing files, and this raises the risk of errors considerably.
                */
                var concurrentEnqueueRequests = 5;

                if (fileList.Count <= 30)
                {
                    concurrentEnqueueRequests = fileList.Count;
                }

                var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3);
                var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests);

                /*
                    iterate over each of the files in the request.  each file must be dispositioned as one of the following:

                    1. enqueued: passed duplicate checks and successfully kicked off a Task to enqueue the download
                    2. failed: download is already in progress, or something went wrong kicking off the Task

                    if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is
                    given a final disposition that will keep it from getting 'stuck'
                */
                foreach (var file in fileList)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    Guid transferId = Guid.NewGuid();

                    try
                    {
                        Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username);

                        /*
                            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!
                        */
                        existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord);

                        if (existingInProgressRecord is not null)
                        {
                            Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
                            failed.Add((file.Filename, "Skipped: Already in progress"));
                            continue;
                        }

                        /*
                            check the tracked download 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, which is likely a bug
                            and we'd like to know about it
                        */
                        if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false)
                        {
                            Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username);
                            failed.Add((file.Filename, "Skipped: Already in progress"));
                            continue;
                        }

                        /*
                            add the transfer record to the database in the Queued | Locally state, and set the 'Removed'
                            property of any existing transfer to 'true', allowing the new record to supersede any old record(s)
                            on the UI

                            we have to persist these changes to the database at this time so the record shows up on the UI,
                            otherwise the transfers only show up as they are enqueued.
                        */
                        var transfer = new Transfer()
                        {
                            Id = transferId,
                            BatchId = batchId,
                            Username = username,
                            Direction = TransferDirection.Download,
                            Filename = file.Filename, // important! use the remote filename
                            Size = file.Size,
                            RequestedAt = DateTime.UtcNow,
                            State = TransferStates.Queued | TransferStates.Locally,
                        };

                        context.Add(transfer);

                        Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id);

                        foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !t.Removed))
                        {
                            record.Removed = true;
                            context.Update(record);
                            Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id);
                        }

                        /*
                            create a TaskCompletionSource that we can await for one of the following:

                            1. the transfer enters the Queued | Remotely state
                            2. the transfer enters a state containing Completed
                            3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
                            4. the 'max wait time' CancellationTokenSource is cancelled
                            5. the DownloadAsync() method throws

                            add this to the dictionary before inserting the record, so we are guaranteed to have it
                            in the right place once the transfer hits the UI
                        */
                        var enqueuedTcs = new TaskCompletionSource<Transfer>(TaskCreationOptions.RunContinuationsAsynchronously);

                        // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call)
                        var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                        CancellationTokens.TryAdd(transfer.Id, cts);
                        cts.Token.Register(() => enqueuedTcs.TrySetCanceled());

                        /*
                            DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up
                            with a State that includes the Completed flag, else it remain "stuck" on the UI
                        */
                        context.SaveChanges();

                        Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username);

                        /*
                            rip off one task for each file in the batch, leaving each to internally wait their turn
                            to proceed with the actual enqueue request and subsequent download, orchestrated by the
                            concurrent enqueue request semaphore

                            we don't wait for any of them; as long as the Task is successfully scheduled (Task.Run doesn't throw),
                            we consider it a success.
                        */
                        var downloadEnqueueTask = Task.Run(async () =>
                        {
                            Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
                            await enqueueSemaphore.WaitAsync(cts.Token);

                            try
                            {
                                Log.Debug("Acquired download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);

                                List<string> transitions = [];
                                TransferStates state = TransferStates.None;

                                // satisfies condition #4; remote user doesn't respond after a really long time
                                using var timeoutCts = new CancellationTokenSource(delay: maxTimeToWaitForEnqueueRequestAck, timeProvider: TimeProvider);
                                timeoutCts.Token.Register(() =>
                                {
                                    // note: disposed once we leave the try block, so registration doesn't fire unless it actually times out
                                    Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions));
                                    enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs"));

                                    // cancel the download attempt so that it doesn't keep running (within Soulseek.NET) and cause the internal
                                    // state of slskd to diverge from the internal state of Soulseek.NET.
                                    cts.Cancel(swallowObjectDisposedException: true);
                                });

                                // satisfies conditions #1 and #2
                                void stateChanged(Transfer transfer)
                                {
                                    state = transfer.State;
                                    transitions.Add(transfer.State.ToString());

                                    if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely))
                                    {
                                        // satisfies condition #1; transfer is now remotely queued
                                        enqueuedTcs.TrySetResult(transfer);
                                    }

                                    // satisfies condition #2; transfer advanced to a terminal state before being enqueued remotely (probably failed)
                                    if (transfer.State.HasFlag(TransferStates.Completed))
                                    {
                                        if (transfer.State.HasFlag(TransferStates.Succeeded))
                                        {
                                            enqueuedTcs.TrySetResult(transfer);
                                        }
                                        else
                                        {
                                            enqueuedTcs.TrySetException(new TransferException(transfer.Exception));
                                        }
                                    }
                                }

                                Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username);

                                var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task =>
                                {
                                    if (task.IsCompletedSuccessfully)
                                    {
                                        Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username);
                                        return;
                                    }

                                    Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
                                    ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");

                                    Log.Error(ex, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);

                                    // trip the TCS if DownloadAsync() throws before any of the other conditions trip it
                                    // this is harmless if it has already been tripped
                                    enqueuedTcs.TrySetException(ex);

                                    if (!TryFail(transferId, exception: ex))
                                    {
                                        Log.Error(ex, "Failed to clean up transfer {Id} after failed download", transferId);
                                    }
                                }, cancellationToken: CancellationToken.None); // end downloadTask.Run();

                                Log.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status);

                                Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely);

                                /*
                                    wait for one of the four conditions to be true:

                                    1. the transfer enters the Queued | Remotely state
                                    2. the transfer enters a state containing Completed
                                    3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
                                    4. the 'max wait time' CancellationTokenSource is cancelled
                                    5. the DownloadAsync() method throws
                                */
                                await enqueuedTcs.Task;

                                Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex, "Download of {File} from {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
                                if (!TryFail(transferId, exception: ex))
                                {
                                    Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message);
                                }
                            }
                            finally
                            {
                                enqueueSemaphore.Release();
                            }
                        }, cancellationToken: cts.Token).ContinueWith(task =>
                        {
                            if (task.IsCompletedSuccessfully)
                            {
                                Log.Information("Task for enqueue of {Filename} from {Username} completed successfully", file.Filename, username);
                                return;
                            }

                            Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
                            ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");

                            Log.Error(ex, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);

                            if (!TryFail(transferId, exception: ex))
                            {
                                Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue", transferId);
                            }
                        }, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run();

                        Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status);
                        Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transferId);
                        enqueued.Add(transfer);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
                        TryFail(transferId, exception: ex);
                        failed.Add((file.Filename, $"Error: {ex.Message}"));

                        if (CancellationTokens.TryRemove(transferId, out var cts))
                        {
                            cts.Dispose();
                        }

                        continue;
                    }
                } // end foreach()

                Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username);
                return (enqueued, failed);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
                throw;
            }
            finally
            {
                userSemaphore.Release();
                Log.Debug("Released enqueue semaphore for user {Username}", username);
            }
        }

        /// <summary>
        ///     Finds a single download matching the specified <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">The expression to use to match downloads.</param>
        /// <returns>The found transfer, or default if not found.</returns>
        public Transfer Find(Expression<Func<Transfer, bool>> expression)
        {
            try
            {
                using var context = ContextFactory.CreateDbContext();

                return context.Transfers
                    .AsNoTracking()
                    .Where(t => t.Direction == TransferDirection.Download)
                    .Where(expression).FirstOrDefault();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to find download: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
        /// </summary>
        /// <param name="id">The unique identifier for the download.</param>
        /// <returns>The retrieved place in queue.</returns>
        public async Task<int> GetPlaceInQueueAsync(Guid id)
        {
            try
            {
                using var context = ContextFactory.CreateDbContext();

                var transfer = context.Transfers.Find(id);

                if (transfer == default || transfer.Direction != TransferDirection.Download)
                {
                    throw new NotFoundException($"No download matching id {id}");
                }

                var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename);

                transfer.PlaceInQueue = place;
                context.SaveChanges();

                return place;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and
        ///     batch configuration.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
        ///         Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop.
        ///     </para>
        ///     <para>
        ///         Empty segments may be present in the output, which more closely aligns with user intent. The
        ///         <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact.
        ///     </para>
        /// </remarks>
        /// <param name="transfer">The transfer.</param>
        /// <returns>The derived destination directory.</returns>
        /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception>
        public async Task<string> DeriveDestination(Transfer transfer)
        {
            // validation should ensure this is a relative path and that it contains no traversal segments
            // we accept any type of slash in the pattern and convert it to the correct variant for the local OS
            var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory;

            // users can enter '{}' if they want the files to go directly into the root of the downloads directory
            if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase))
            {
                return string.Empty;
            }

            string source_username;
            string source_path;
            string source_directory;
            string batch_id;
            string batch_external_id;
            string search_id;
            string search_text;

            /*
                fetch/extract/derive and sanitize each of the values we're going to replace

                when flow leaves this block we can expect that all of the string values
                defined above have a value that can be safely substituted for its placeholder
            */
            try
            {
                Batch batch = null;

                if (transfer.BatchId is not null)
                {
                    batch = await Batches.FindAsync(b => b.Id == transfer.BatchId);
                }

                // destination supplied with the batch enqueue request takes precedence over all; return early
                if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination))
                {
                    var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_');

                    // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
                    // properly sanitizing user input both via the API and in the logic above
                    if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination))
                    {
                        throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed.  Please report this on GitHub.");
                    }

                    return explicitDestination;
                }

                Search search = null;

                if (batch?.SearchId is not null)
                {
                    search = await Searches.FindAsync(s => s.Id == batch.SearchId);
                }

                source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_');

                var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_');

                // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz'
                // retains the path root, if there is one (Soulseek NS does this), which may not be what
                // people want, so possibly revisit and add StripPathRoot()
                source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\');

                // name of the remote parent directory, so using the example above, 'Baz'
                source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\');

                batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString();

                // the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination,
                // except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended
                batch_external_id = FileSafety.SanitizeFilename(
                    filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId,
                    replacement: '_');

                search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString();
                search_text = FileSafety.SanitizeFilename(
                    filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText,
                    replacement: '_');
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message);
                throw;
            }

            var args = new Dictionary<string, string>(
                StringComparer.OrdinalIgnoreCase) // important!
            {
                ["SOURCE_USERNAME"] = source_username,
                ["SOURCE_PATH"] = source_path,
                ["SOURCE_DIRECTORY"] = source_directory,
                ["BATCH_ID"] = batch_id,
                ["BATCH_EXTERNAL_ID"] = batch_external_id,
                ["SEARCH_ID"] = search_id,
                ["SEARCH_TEXT"] = search_text,
            };

            // use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could
            // cascade into others and produce unintended results
            var destination = SubdirectoryPatternTokenRegex.Replace(
                input: pattern,
                evaluator: match =>
                {
                    if (args.TryGetValue(match.Groups[1].Value, out var value))
                    {
                        return value;
                    }

                    return match.Value;
                });

            destination = FileSafety.SanitizePath(destination, replacement: '_');

            Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });

            // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
            // properly sanitizing the final output to strip leading slashes and replace traversal segments
            if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination))
            {
                Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });
                throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed.  Please report this on GitHub.");
            }

            return destination;
        }

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

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

                return context.Transfers
                    .AsNoTracking()
                    .Where(t => t.Direction == TransferDirection.Download)
                    .Where(t => !t.Removed || includeRemoved)
                    .Where(expression)
                    .ToList();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to list downloads: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        ///     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="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, 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.Download)
                    .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 downloads with states {States}", pruned, statesSet);
                }

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

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

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

        /// <summary>
        ///     Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
        /// </summary>
        /// <param name="id">The unique identifier for the download.</param>
        /// <returns>A value indicating whether the download was successfully cancelled.</returns>
        public bool TryCancel(Guid id)
        {
            // if the cancellation token is still in the dictionary, calling Cancel() on it _should_
            // cause the transfer operation to fail with an OperationCancelled exception and set the state
            // of the transfer to Cancelled.  _should_!
            if (CancellationTokens.TryRemove(id, out var cts))
            {
                cts.Cancel(swallowObjectDisposedException: true);
                return true;
            }

            /*
                if the cancellation token couldn't be found in the dictionary, either:

                1. the transfer completed already
                2. something went wrong and the record is 'stuck'

                see if we can find the record, and if it's *NOT* completed, cancel it. otherwise,
                leave it alone.
            */
            var t = Find(t => t.Id == id);

            if (t is not null && !t.State.HasFlag(TransferStates.Completed))
            {
                t.EndedAt = DateTime.UtcNow;
                t.State = TransferStates.Completed | TransferStates.Cancelled;
                t.Exception = new OperationCanceledException().Message;
                Update(t);
                return true;
            }

            // this transfer id didn't have a cancellation token registered, and we couldn't find it in the dictionary
            return false;
        }

        /// <summary>
        ///     Fails the download 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 download.</param>
        /// <param name="exception">The exception that caused the failure.</param>
        /// <returns>A value indicating whether the download was successfully failed.</returns>
        public bool TryFail(Guid id, Exception exception)
        {
            var t = Find(t => t.Id == id);

            if (t is null)
            {
                return false;
            }

            t.EndedAt ??= DateTime.UtcNow;

            // Retry.Do() wraps failures in an AggregateException; use the most recent so that the state reflects what happened
            if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count > 0)
            {
                exception = aggregate.InnerExceptions.Last();
            }

            // 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.Message;
            t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;

            if (!t.State.HasFlag(TransferStates.Completed))
            {
                t.State = TransferStates.Completed | exception switch
                {
                    OperationCanceledException => TransferStates.Cancelled,
                    TimeoutException => TransferStates.TimedOut,
                    TransferRejectedException => TransferStates.Rejected,
                    _ => TransferStates.Errored,
                };
            }

            try
            {
                Update(t);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to update database: {Message}", ex.Message);
                return false;
            }
            finally
            {
                CancellationTokens.TryRemove(id, out var cts);
                cts?.TryDispose();
            }
        }

        /// <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();
        }

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

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

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

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

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

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

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

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

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

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

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

        /// <summary>
        ///     Downloads the specified enqueued <paramref name="transfer"/> from the remote user.
        /// </summary>
        /// <param name="transfer">The Transfer to download.</param>
        /// <param name="stateChanged">An optional delegate to invoke the transfer state changes.</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 a download matching the username and filename is already tracked by Soulseek.NET.</exception>
        private async Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default)
        {
            if (transfer is null)
            {
                throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required");
            }

            // grab the latest from the database; this may have been sitting behind a semaphore or something
            transfer = Find(t => t.Id == 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 download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}");
            }

            if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename))
            {
                throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered");
            }

            // there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given
            // (which is probably the same one, harmless if so) to make sure we don't get any wires crossed
            CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource);
            using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None);
            cancellationToken = cts.Token;

            var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry;
            var updateSyncRoot = new SemaphoreSlim(1, 1);

            var stateHistory = new List<TransferStates>();
            DateTime lastReportedAverageSpeed = default;

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

                var topts = new TransferOptions(
                    stateChanged: (args) =>
                    {
                        try
                        {
                            Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, 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("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
                                return;
                            }

                            transfer = transfer.WithSoulseekTransfer(args.Transfer);

                            // we don't know when the download is actually enqueued (remotely) until it switches into that state
                            // when it is enqueued locally is irrelevant, due to internal throttling etc
                            if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
                            {
                                transfer.EnqueuedAt ??= DateTime.UtcNow;
                            }

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

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

                            stateHistory.Add(transfer.State);

                            // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer
                            // *might* still have remaining retry attempts. leave this non-committal for now, and allow
                            // the final update after all retry attempts have been exhausted to add it.
                            // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all
                            // retries is to look for this flag
                            if (args.Transfer.State.HasFlag(TransferStates.Completed)
                                && !args.Transfer.State.HasFlag(TransferStates.Succeeded)
                                && transfer.Attempts < retryOptions.Attempts)
                            {
                                transfer.State = TransferStates.Queued | TransferStates.Locally;
                            }

                            // todo: broadcast
                            SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken);
                        }
                        finally
                        {
                            stateChanged?.Invoke(transfer);
                        }
                    },
                    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 (updateSyncRoot.Wait(millisecondsTimeout: 0, cancellationToken: cancellationToken))
                            {
                                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.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed);
                                        }, cancellationToken);

                                        lastReportedAverageSpeed = now;
                                    }
                                }
                                finally
                                {
                                    updateSyncRoot.Release();
                                }
                            }
                            else
                            {
                                Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size);
                            }
                        }
                    }),
                    disposeOutputStreamOnCompletion: true);

                UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode)
                    ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode()
                    : null;

                /*
                    store incomplete files under a username subdirectory to prevent collisions between users and to make
                    it safe to resume partial downloads without risking picking up an unrelated file.

                    we're going to store the file as:

                        <incomplete directory>/<username>/<full path to file on remote client>/<filename>

                    so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes:

                        linux:   incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext
                        windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext

                    slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _.
                    this mitigates the risk of an improper partial resume to a great extent.

                    if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because
                    the size we send originates from the original file, and there will be a mismatch.

                    the only remaining risk is in a case where the file contents have changed but the size remains the same.
                    the resulting file will be corrupted in that case, and there's nothing we can really do about it. users
                    that are concerned about this (extremely unlikely) case should configure slskd to always overwrite
                    partial files.
                */
                var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete;
                var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username);
                var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true);
                var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty;

                var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename);

                Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename);

                Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username);
                transfer.Attempts = 1;
                SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);

                var completedTransfer = await Retry.Do(() =>
                    {
                        var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename);
                        var incompleteStrategy = retryOptions.Partial.ToEnum<RetryPartialStrategy>();

                        var shouldResume = false;
                        var startOffset = 0L;

                        if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0)
                        {
                            if (incompleteStrategy == RetryPartialStrategy.Resume)
                            {
                                shouldResume = true;
                                startOffset = incompleteFileInfo.Length;
                                Log.Information("Resuming download of {Filename} from user {Username} at offset {Offet}", transfer.Filename, transfer.Username, incompleteFileInfo.Length);
                            }
                            else
                            {
                                Log.Information("Overwriting partial download of {Length} bytes for download of {Filename} from user {Username} at offset {Offet}", incompleteFileInfo.Length, transfer.Filename, transfer.Username);
                            }
                        }

                        return Client.DownloadAsync(
                            username: transfer.Username,
                            remoteFilename: transfer.Filename,
                            outputStreamFactory: () => Task.FromResult(
                                Files.CreateFile(
                                    filename: incompleteFilename,
                                    options: new CreateFileOptions
                                    {
                                        Access = System.IO.FileAccess.Write,
                                        Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create,
                                        Share = System.IO.FileShare.None, // exclusive access for the duration of the download
                                        UnixCreateMode = unixFileMode,
                                    })),
                            size: transfer.Size,
                            startOffset: startOffset,
                            token: null,
                            cancellationToken: cancellationToken,
                            options: topts);
                    },
                    isRetryable: (attempts, ex) =>
                        ex is not OperationCanceledException
                        && ex is not TransferRejectedException
                        && ex is not DuplicateTransferException
                        && ex is not TransferSizeMismatchException,
                    onRetry: (attempts, delay) =>
                    {
                        // an attempt failed and we have decided that we're going to retry instead of letting it throw
                        // we *MAY* have incremented queued/in progress metrics as part of the previous attempt
                        var mostRecentQueuedOrInProgressState = stateHistory
                            .LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s));

                        Telemetry.Metrics.Update(() =>
                        {
                            if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState))
                            {
                                Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1);
                                Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size);
                            }
                            else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState))
                            {
                                Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1);
                                Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size);
                            }
                        });

                        // reset the history to make detection logic above easier and more accurate
                        Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory);
                        stateHistory = [];

                        Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username);

                        transfer.Attempts = attempts;
                        transfer.State = TransferStates.Queued | TransferStates.Locally;
                        SynchronizedUpdate(transfer, updateSyncRoot);
                    },
                    onFailure: (attempts, ex) =>
                    {
                        Log.Warning("Failed attempt #{Attempts} to download {Filename} from user {Username}: {Message}", attempts, transfer.Filename, transfer.Username, ex.Message);
                    },
                    maxAttempts: retryOptions.Attempts,
                    baseDelayInMilliseconds: retryOptions.Delay,
                    maxDelayInMilliseconds: retryOptions.MaxDelay,
                    cancellationToken: cancellationToken);

                Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);

                // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we
                // flush 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 to signalr hub
                SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);

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

                Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete);

                /*
                    move the file from incomplete to complete

                    users have a lot of strong opinions about this!

                    the destination is always rooted in the configured download directory. we derive the subdirectory
                    for this file based on either the Destination property defined for the Batch that contains this transfer,
                    or by applying replacements to the user's configured Destination.Subdirectory string.

                    what we get back will be a relative path (or perhaps an empty string if that's what the user wanted)
                    that has sanitized and checked for safety against traversal
                */
                var subdirectory = await DeriveDestination(transfer);
                var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory);

                var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>();

                Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);

                var finalFilename = Files.MoveFile(
                    sourceFilename: incompleteFilename,
                    destinationDirectory: destinationDirectory,
                    unixFileMode: unixFileMode,
                    overwrite: existsStrategy == DestinationExistsStrategy.Overwrite,
                    deleteSourceDirectoryIfEmptyAfterMove: true);

                Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename);

                if (OptionsMonitor.CurrentValue.Relay.Enabled)
                {
                    _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename);
                }

                try
                {
                    // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary,
                    // and the file has been moved from the incomplete directory to the downloads directory
                    Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username);

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

                    // try to figure out if this file is the last of a directory, and if so, raise the associated
                    // event. this can be tricky because we want to be sure that this is the last file in this specific
                    // directory, excluding any pending downloads in a subdirectory.
                    var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator();
                    var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator);
                    var pendingDownloadsInDirectory = Client.Downloads
                        .Where(t => t.Username == transfer.Username)
                        .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName);

                    if (!pendingDownloadsInDirectory.Any())
                    {
                        EventBus.Raise(new DownloadDirectoryCompleteEvent
                        {
                            Timestamp = transfer.EndedAt.Value,
                            Username = transfer.Username,
                            LocalDirectoryName = destinationDirectory,
                            RemoteDirectoryName = remoteDirectoryName,
                        });
                    }

                    if (OptionsMonitor.CurrentValue.Integrations.Ftp.Enabled)
                    {
                        _ = FTP.UploadAsync(finalFilename);
                    }

                    Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username);
                }
                catch (Exception ex)
                {
                    // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete
                    // todo: add a visual indicator/new state for Transfers that indicate this state.  or move all of this logic out and handle it via events
                    Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
                }

                Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);

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

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

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

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

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

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

                throw;
            }
            finally
            {
                Log.Debug("Download of {Filename} from 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.Downloads.InProgress.Files.Value > 0)
                    {
                        // if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition
                        Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1);
                        Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size);
                    }
                    else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.Queued.Files.Value > 0)
                    {
                        // if the transfer never transitioned to in progress but it was queued at any point, decrement queued
                        Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1);
                        Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size);
                    }
                }, cancellationToken);

                if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource))
                {
                    storedCancellationTokenSource?.Dispose();
                }
            }
        }

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

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

        private async Task CleanupEnqueueSemaphoresAsync()
        {
            if (await EnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false))
            {
                try
                {
                    foreach (var kvp in EnqueueSemaphores)
                    {
                        if (await kvp.Value.WaitAsync(0).ConfigureAwait(false))
                        {
                            EnqueueSemaphores.TryRemove(kvp.Key, out var removed);
                            removed.Dispose();
                            Log.Debug("Cleaned up enqueue semaphore for {Key}", kvp.Key);
                        }
                    }
                }
                finally
                {
                    EnqueueSemaphoreSyncRoot.Release();
                }
            }
        }
    }
}