aria2-core 0.3.12

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
Documentation
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
//! Download lifecycle event hooks.
//!
//! Mirrors C++ `util::executeHookByOptName()` and the
//! `PREF_ON_DOWNLOAD_START / COMPLETE / ERROR / PAUSE / STOP /
//! BT_DOWNLOAD_COMPLETE` hook infrastructure.
//!
//! In the original C++ aria2, each lifecycle transition fires a user-configured
//! shell command with arguments: `<command> <GID_hex> <numFiles> <firstFilePath>`.
//! The Rust implementation replicates this via async `tokio::process::Command`
//! spawning, which works on both Unix and Windows.
//!
//! # Events
//!
//! | Event              | C++ Preference              | Fired when                     |
//! |--------------------|-----------------------------|--------------------------------|
//! | `Start`            | `PREF_ON_DOWNLOAD_START`   | Group promoted to active       |
//! | `Complete`         | `PREF_ON_DOWNLOAD_COMPLETE`| Download finished successfully |
//! | `Error`            | `PREF_ON_DOWNLOAD_ERROR`   | Download finished with error   |
//! | `Pause`            | `PREF_ON_DOWNLOAD_PAUSE`   | Download paused by user        |
//! | `Stop`             | `PREF_ON_DOWNLOAD_STOP`    | Download stopped (not complete)|
//! | `BtComplete`       | `PREF_ON_BT_DOWNLOAD_COMPLETE` | BT download fully complete |
//!
//! # Architecture
//!
//! The bus has **two independent sinks**. A single `fire_*` call feeds both;
//! neither sink may gate the other.
//!
//! ```text
//! Group state transition / engine loop / demotion path
//!   │
//!   ├─ on promotion  → fire DownloadEvent::Start
//!   ├─ on demotion   → fire DownloadEvent::Complete / Error / Pause / Stop
//!   └─ on BT done    → fire DownloadEvent::BtComplete
//!         │
//!         â–¼
//!   DownloadEventHooks::fire_event()
//!     ├─ sink 1: shell hook (OPTIONAL — only when --on-download-* is set)
//!     │    ├─ resolve hook command from DownloadOptions / global hooks
//!     │    ├─ spawn tokio::process::Command with (gid, numFiles, firstFilePath)
//!     │    └─ log result (fire-and-forget, non-blocking)
//!     │
//!     └─ sink 2: observers (ALWAYS — never gated on sink 1)
//!          └─ DownloadEventListener::on_download_event(event, gid)
//! ```
//!
//! # Observers (`DownloadEventListener`)
//!
//! Sink 2 mirrors C++ `Notifier::addDownloadEventListener()` /
//! `Notifier::notifyDownloadEvent()`. It exists so layers *above* `aria2-core`
//! (notably the JSON-RPC WebSocket notifier, which emits
//! `aria2.onDownloadComplete` / `aria2.onDownloadError` /
//! `aria2.onBtDownloadComplete`) can observe download lifecycle transitions
//! **without `aria2-core` ever depending on `aria2-rpc`**. The binary crate
//! `aria2` owns both crates and installs the adapter, keeping the dependency
//! direction `aria2 → {aria2-core, aria2-rpc}` intact.
//!
//! Observer notification is deliberately synchronous and cheap: implementors
//! must not block (the recommended pattern is an `mpsc` send consumed by a
//! dedicated task).

use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, OnceLock, atomic::AtomicU64};

use tokio::sync::broadcast;

use tracing::{debug, info, warn};

use crate::request::request_group::{GroupId, RequestGroup};
use crate::util::rwlock_ext::RwLockRecover;

// ============================================================================
// Download event types
// ============================================================================

/// Download lifecycle events that can trigger user-configured shell hooks.
///
/// Each variant maps to a C++ `PREF_ON_DOWNLOAD_*` preference and is fired
/// at a specific point in the download lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DownloadEvent {
    /// Fired when a download is promoted from reserved to active.
    /// C++: `PREF_ON_DOWNLOAD_START`
    Start,
    /// Fired when a download completes successfully.
    /// C++: `PREF_ON_DOWNLOAD_COMPLETE`
    Complete,
    /// Fired when a download finishes with an error.
    /// C++: `PREF_ON_DOWNLOAD_ERROR`
    Error,
    /// Fired when a download is paused by user request.
    /// C++: `PREF_ON_DOWNLOAD_PAUSE`
    Pause,
    /// Fired when a download is stopped (not complete, not error).
    /// C++: `PREF_ON_DOWNLOAD_STOP`
    Stop,
    /// Fired when a BitTorrent payload download completes. Seeding may
    /// continue after this event.
    /// C++: `PREF_ON_BT_DOWNLOAD_COMPLETE`
    BtComplete,
}

/// Describes the transition from a completed metadata task to download groups
/// that can consume its resolved metadata.
///
/// This is deliberately separate from [`DownloadEvent`]. The latter mirrors
/// aria2's lifecycle hooks and the standard RPC notifications, while metadata
/// resolution is a Rust-library observation that has no corresponding
/// standard aria2 status or notification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetadataResolvedEvent {
    /// GID of the task that produced the metadata.
    pub metadata_gid: GroupId,
    /// GIDs ready to consume the resolved metadata. For an in-place magnet
    /// download this contains the same GID as `metadata_gid`; for a
    /// metadata-only request it is empty. For a post-download metadata task,
    /// these are the values exposed as `followedBy` for `metadata_gid`.
    pub download_gids: Vec<GroupId>,
}

/// Event stream item for Rust-library consumers.
///
/// The lifecycle variant keeps the canonical hex GID used by aria2's RPC
/// surface. Metadata resolution is represented separately because it is a
/// transient library event rather than a standard aria2 download status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DownloadNotification {
    Lifecycle { event: DownloadEvent, gid: String },
    MetadataResolved(MetadataResolvedEvent),
}

/// A loss-aware stream of lifecycle and metadata notifications.
///
/// This is backed by a bounded broadcast channel. A slow consumer must handle
/// [`broadcast::error::RecvError::Lagged`] by taking a fresh snapshot from its
/// [`DownloadHandle`](super::download_manager::DownloadHandle), rather than
/// assuming every intermediate progress event was retained.
pub struct DownloadEventStream {
    receiver: broadcast::Receiver<DownloadNotification>,
}

impl DownloadEventStream {
    pub async fn recv(&mut self) -> Result<DownloadNotification, broadcast::error::RecvError> {
        self.receiver.recv().await
    }

    /// Wait for a terminal lifecycle event for `gid`.
    ///
    /// This consumes unrelated notifications from this receiver while
    /// waiting. `Stop` is included because aria2 uses it for a download that
    /// was stopped without completing or failing. The helper is deliberately
    /// event-driven; callers that need the final snapshot can use the matching
    /// [`DownloadHandle`](super::download_manager::DownloadHandle) after it
    /// returns.
    pub async fn recv_terminal_for(
        &mut self,
        gid: GroupId,
    ) -> Result<DownloadEvent, broadcast::error::RecvError> {
        let gid = gid.to_hex_string();
        loop {
            match self.recv().await? {
                DownloadNotification::Lifecycle {
                    event,
                    gid: event_gid,
                } if event_gid == gid && event.is_terminal() => {
                    return Ok(event);
                }
                DownloadNotification::Lifecycle { .. }
                | DownloadNotification::MetadataResolved(_) => {}
            }
        }
    }

    /// Wait for metadata resolution involving `gid`.
    ///
    /// A metadata task may resolve into the same GID (for a magnet download)
    /// or into one or more child download GIDs (for a metadata-backed graph).
    /// This helper filters both forms while preserving the broadcast channel's
    /// lag error so callers can resubscribe and refresh their snapshots.
    pub async fn recv_metadata_for(
        &mut self,
        gid: GroupId,
    ) -> Result<MetadataResolvedEvent, broadcast::error::RecvError> {
        loop {
            match self.recv().await? {
                DownloadNotification::MetadataResolved(event)
                    if event.metadata_gid == gid || event.download_gids.contains(&gid) =>
                {
                    return Ok(event);
                }
                DownloadNotification::Lifecycle { .. }
                | DownloadNotification::MetadataResolved(_) => {}
            }
        }
    }
}

impl MetadataResolvedEvent {
    /// Create a metadata-resolution event from a parent GID and its children.
    pub fn new(metadata_gid: GroupId, download_gids: Vec<GroupId>) -> Self {
        Self {
            metadata_gid,
            download_gids,
        }
    }
}

impl DownloadEvent {
    /// Returns the human-readable name of this event.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Start => "on-download-start",
            Self::Complete => "on-download-complete",
            Self::Error => "on-download-error",
            Self::Pause => "on-download-pause",
            Self::Stop => "on-download-stop",
            Self::BtComplete => "on-bt-download-complete",
        }
    }

    /// Whether this event can legitimately fire at most **once** for a given
    /// download.
    ///
    /// `Complete`, `Error` and `BtComplete` are one-shot transitions: a
    /// download completes once, fails once, and finishes its BT payload once.
    /// They are emitted from more than one place (the group state transition
    /// itself *and* the engine-loop demotion path), so observer notification is
    /// de-duplicated on `(gid, event)` for these variants.
    ///
    /// `Start` and `Pause` may repeat across pause/unpause cycles and `Stop`
    /// is re-emitted by the RPC layer on explicit removal, so those are never
    /// de-duplicated.
    pub fn is_once_per_download(&self) -> bool {
        matches!(self, Self::Complete | Self::Error | Self::BtComplete)
    }

    /// Whether this notification marks the task as stopped for lifecycle
    /// observers. `BtComplete` only marks payload completion; seeding may
    /// continue until a later terminal event.
    ///
    /// `Stop` is terminal for the current task run even though aria2 may emit
    /// it again when a caller explicitly removes the task. It is therefore
    /// terminal for waiters but not a one-shot event for de-duplication.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Stop | Self::Complete | Self::Error)
    }
}

// ============================================================================
// DownloadEventListener — observer interface for out-of-crate subscribers
// ============================================================================

/// Observer notified of every download lifecycle transition.
///
/// Mirrors C++ `aria2::DownloadEventListener` (see `src/Notifier.h`), whose
/// `onEvent(DownloadEvent, const RequestGroup*)` is invoked by
/// `Notifier::notifyDownloadEvent()`.
///
/// # Contract
///
/// * Implementations **must not block**. Notification happens inline on the
///   thread that performed the state transition, which may be holding
///   unrelated locks. Forward the event to a channel and do the real work on
///   a dedicated task.
/// * Implementations **must not panic**. A panicking listener would unwind
///   through the download engine.
/// * `gid` is the canonical 16-digit lowercase hex GID (`GroupId::to_hex_string`),
///   i.e. exactly the identifier the JSON-RPC layer exposes to clients.
pub trait DownloadEventListener: Send + Sync {
    /// Called for every fired download event.
    fn on_download_event(&self, event: DownloadEvent, gid: &str);

    /// Called for lifecycle events emitted by a request manager.
    ///
    /// The default keeps existing process-wide observers compatible. A
    /// manager-scoped observer can override this method to distinguish equal
    /// GIDs owned by different managers.
    fn on_download_event_scoped(&self, event: DownloadEvent, gid: &str, _scope_id: u64) {
        self.on_download_event(event, gid);
    }

    /// Called after a metadata task has produced and queued its download
    /// groups.
    ///
    /// This callback is intentionally not mapped to a standard aria2 RPC
    /// notification. Implementors that only need lifecycle events can keep
    /// the default no-op implementation.
    fn on_metadata_resolved(&self, _event: &MetadataResolvedEvent) {}

    /// Whether the observer still has a live destination.
    ///
    /// Process-wide buses can outlive a server instance. Implementations that
    /// hold a weak destination should return false after that destination is
    /// dropped so the bus can release the stale observer.
    fn is_alive(&self) -> bool {
        true
    }
}

/// Stable identifier for one registered lifecycle listener.
pub type DownloadEventListenerId = u64;

// ============================================================================
// DownloadEventHooks — manages hook registration and execution
// ============================================================================

/// Maximum number of `(gid, event)` pairs retained for one-shot event
/// de-duplication before the bookkeeping is rotated.
///
/// A long-running daemon must not accumulate one entry per download forever,
/// so the set is kept in two generations: once `current` reaches this cap it
/// is demoted to `previous` and a fresh `current` is started. Lookups consult
/// both generations, so recently-seen events are never forgotten prematurely.
const DEDUP_GENERATION_CAPACITY: usize = 4096;

/// Number of metadata-resolution events retained for late library observers.
///
/// Metadata resolution is a one-shot transition, so a bounded replay history
/// is enough to bridge the small gap between task submission and a caller
/// starting its await. The event stream remains loss-aware for older entries.
const METADATA_HISTORY_CAPACITY: usize = 1024;

/// Two-generation bounded de-duplication ledger for one-shot events.
#[derive(Default)]
struct OneShotLedger {
    current: HashSet<(Option<u64>, String, DownloadEvent)>,
    previous: HashSet<(Option<u64>, String, DownloadEvent)>,
}

impl OneShotLedger {
    /// Record `key` and report whether this is the first time it was seen.
    ///
    /// Returns `true` when the caller should proceed with the notification,
    /// `false` when the event was already delivered.
    fn claim(&mut self, key: (Option<u64>, String, DownloadEvent)) -> bool {
        if self.current.contains(&key) || self.previous.contains(&key) {
            return false;
        }
        if self.current.len() >= DEDUP_GENERATION_CAPACITY {
            self.previous = std::mem::take(&mut self.current);
        }
        self.current.insert(key);
        true
    }
}

/// Manages download event hooks and provides fire-and-forget execution.
///
/// The hook system mirrors C++ aria2's `--on-download-start`,
/// `--on-download-complete`, etc. CLI options. Each option holds a shell
/// command to execute when the corresponding event fires.
///
/// Hook commands are resolved from `DownloadOptions` fields at fire time,
/// allowing per-group hook customization. If no command is configured for
/// an event, nothing is executed.
///
/// # Thread Safety
///
/// `DownloadEventHooks` is `Send + Sync` — it holds no mutable state.
/// Hook execution is fire-and-forget via `tokio::spawn`, so the caller
/// never blocks.
pub struct DownloadEventHooks {
    /// Global hooks applied to all downloads unless overridden per-group.
    /// Maps event type → shell command string.
    global_hooks: Arc<std::sync::RwLock<GlobalHookMap>>,
    /// Registered observers (sink 2). Notified for **every** fired event,
    /// regardless of whether a shell hook command is configured.
    listeners: std::sync::RwLock<Vec<(DownloadEventListenerId, Arc<dyn DownloadEventListener>)>>,
    next_listener_id: AtomicU64,
    /// De-duplication ledger for one-shot events
    /// ([`DownloadEvent::is_once_per_download`]).
    one_shot: std::sync::RwLock<OneShotLedger>,
    /// Bounded event stream for library consumers that do not need to
    /// implement the synchronous listener trait.
    notifications: broadcast::Sender<DownloadNotification>,
    /// Recent structured metadata transitions for late high-level waiters.
    metadata_history: std::sync::RwLock<VecDeque<MetadataResolvedEvent>>,
}

/// Type alias for the global hook map.
type GlobalHookMap = Vec<(DownloadEvent, String)>;

/// Process-wide hook bus, lazily created on first use.
static SHARED_HOOKS: OnceLock<Arc<DownloadEventHooks>> = OnceLock::new();

impl DownloadEventHooks {
    /// Create a new hook manager with no global hooks and no listeners.
    pub fn new() -> Self {
        let (notifications, _) = broadcast::channel(256);
        Self {
            global_hooks: Arc::new(std::sync::RwLock::new(Vec::new())),
            listeners: std::sync::RwLock::new(Vec::new()),
            next_listener_id: AtomicU64::new(1),
            one_shot: std::sync::RwLock::new(OneShotLedger::default()),
            notifications,
            metadata_history: std::sync::RwLock::new(VecDeque::new()),
        }
    }

    /// Return the process-wide hook bus.
    ///
    /// Download lifecycle transitions happen deep inside individual
    /// `Command` implementations that have no reference to the engine, while
    /// the engine loop remains the central group-management path. A process-wide
    /// bus is what lets a single listener registration
    /// observe *all* of them, and mirrors C++ where `Notifier` is a
    /// `SingletonHolder`. The same pattern is already used in this crate for
    /// `filesystem::file_allocation_man::shared()` and
    /// `checksum::check_integrity::man::shared()`.
    pub fn shared() -> &'static Arc<DownloadEventHooks> {
        SHARED_HOOKS.get_or_init(|| Arc::new(DownloadEventHooks::new()))
    }

    /// Register an observer that is notified of every fired download event.
    ///
    /// Registration is additive. Call [`Self::add_listener_with_id`] when the
    /// caller owns a bounded-lifetime adapter and needs explicit cleanup.
    pub fn add_listener(&self, listener: Arc<dyn DownloadEventListener>) {
        let _ = self.add_listener_with_id(listener);
    }

    /// Register an observer and return its removal identifier.
    ///
    /// The identifier is local to this hook bus and remains valid until the
    /// listener is removed or the bus is dropped. Registration still prunes
    /// listeners whose [`DownloadEventListener::is_alive`] method is false.
    pub fn add_listener_with_id(
        &self,
        listener: Arc<dyn DownloadEventListener>,
    ) -> DownloadEventListenerId {
        let id = self
            .next_listener_id
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut listeners = self.listeners.recover_mut();
        listeners.retain(|(_, listener)| listener.is_alive());
        listeners.push((id, listener));
        debug!(
            listener_id = id,
            count = listeners.len(),
            "Registered download event listener"
        );
        id
    }

    /// Remove a listener previously returned by [`Self::add_listener_with_id`].
    ///
    /// Returns `true` only when the requested identifier was registered. Any
    /// other listeners that are already dead are pruned as part of the same
    /// operation.
    pub fn remove_listener(&self, id: DownloadEventListenerId) -> bool {
        let mut listeners = self.listeners.recover_mut();
        let removed = listeners.iter().any(|(listener_id, _)| *listener_id == id);
        listeners.retain(|(listener_id, listener)| *listener_id != id && listener.is_alive());
        removed
    }

    /// Number of currently registered observers (primarily for tests).
    pub fn listener_count(&self) -> usize {
        self.listeners.recover().len()
    }

    /// Subscribe to lifecycle and metadata notifications without installing a
    /// callback object. Events are delivered in publication order for this
    /// receiver, subject to the bounded channel's lag semantics.
    pub fn subscribe(&self) -> DownloadEventStream {
        DownloadEventStream {
            receiver: self.notifications.subscribe(),
        }
    }

    /// Return the most recent metadata transition involving `gid`.
    ///
    /// This is used by high-level handles to close the race between creating
    /// an event receiver and checking whether metadata was already resolved.
    pub(crate) fn metadata_event_for(&self, gid: GroupId) -> Option<MetadataResolvedEvent> {
        self.metadata_history
            .recover()
            .iter()
            .rev()
            .find(|event| event.metadata_gid == gid || event.download_gids.contains(&gid))
            .cloned()
    }

    /// Notify every registered observer of `event` for `gid`.
    ///
    /// `gid` must be the canonical 16-digit hex GID
    /// ([`GroupId::to_hex_string`](crate::request::request_group::GroupId::to_hex_string)).
    ///
    /// This is the *unconditional* sink: it is deliberately independent of
    /// whether the user configured an `--on-download-*` shell command, because
    /// RPC clients (AriaNg, webui-aria2, ...) rely on the corresponding
    /// WebSocket notifications to ever mark a download as finished.
    ///
    /// One-shot events are de-duplicated so that a transition observed both at
    /// the `RequestGroup` state change and again at engine-loop demotion is
    /// only delivered once.
    pub fn notify_listeners(&self, event: DownloadEvent, gid: &str) {
        self.notify_listeners_in_scope(event, gid, None);
    }

    /// Notify observers with the owning request manager's identity.
    pub(crate) fn notify_listeners_scoped(&self, event: DownloadEvent, gid: &str, scope_id: u64) {
        self.notify_listeners_in_scope(event, gid, Some(scope_id));
    }

    fn notify_listeners_in_scope(&self, event: DownloadEvent, gid: &str, scope_id: Option<u64>) {
        // Snapshot under a short read lock so a listener callback can never
        // deadlock against `add_listener`.
        let listeners: Vec<Arc<dyn DownloadEventListener>> = {
            let mut guard = self.listeners.recover_mut();
            guard.retain(|(_, listener)| listener.is_alive());
            if guard.is_empty() && self.notifications.receiver_count() == 0 {
                // Nothing to do — and importantly, do not pollute the
                // de-duplication ledger when no one is listening.
                return;
            }
            guard
                .iter()
                .map(|(_, listener)| Arc::clone(listener))
                .collect()
        };

        if event.is_once_per_download()
            && !self
                .one_shot
                .recover_mut()
                .claim((scope_id, gid.to_string(), event))
        {
            debug!(
                event = event.name(),
                gid, "Suppressed duplicate one-shot download event"
            );
            return;
        }

        let _ = self.notifications.send(DownloadNotification::Lifecycle {
            event,
            gid: gid.to_string(),
        });

        debug!(
            event = event.name(),
            gid,
            listeners = listeners.len(),
            "Notifying download event listeners"
        );
        for listener in listeners {
            if let Some(scope_id) = scope_id {
                listener.on_download_event_scoped(event, gid, scope_id);
            } else {
                listener.on_download_event(event, gid);
            }
        }
    }

    /// Notify observers that a metadata task produced its download groups.
    ///
    /// The caller must invoke this after the child groups have been inserted
    /// into the request manager. The event is synchronous and follows the
    /// same non-blocking, non-panicking listener contract as lifecycle events.
    pub fn notify_metadata_resolved(&self, event: MetadataResolvedEvent) {
        {
            let mut history = self.metadata_history.recover_mut();
            history.retain(|previous| previous.metadata_gid != event.metadata_gid);
            history.push_back(event.clone());
            while history.len() > METADATA_HISTORY_CAPACITY {
                history.pop_front();
            }
        }

        let listeners: Vec<Arc<dyn DownloadEventListener>> = {
            let mut guard = self.listeners.recover_mut();
            guard.retain(|(_, listener)| listener.is_alive());
            if guard.is_empty() && self.notifications.receiver_count() == 0 {
                return;
            }
            guard
                .iter()
                .map(|(_, listener)| Arc::clone(listener))
                .collect()
        };

        let _ = self
            .notifications
            .send(DownloadNotification::MetadataResolved(event.clone()));

        debug!(
            metadata_gid = event.metadata_gid.value(),
            download_gids = event.download_gids.len(),
            listeners = listeners.len(),
            "Notifying metadata-resolved listeners"
        );
        for listener in listeners {
            listener.on_metadata_resolved(&event);
        }
    }

    /// Register a global hook for the given event.
    ///
    /// Global hooks are used when no per-group hook is configured.
    /// If a global hook is already registered for this event, it is replaced.
    pub fn set_global_hook(&self, event: DownloadEvent, command: String) {
        let mut hooks = self.global_hooks.recover_mut();
        if let Some(entry) = hooks.iter_mut().find(|(e, _)| *e == event) {
            entry.1 = command;
        } else {
            hooks.push((event, command));
        }
        debug!(
            event = event.name(),
            "Registered global download event hook"
        );
    }

    /// Remove a global hook for the given event.
    pub fn remove_global_hook(&self, event: DownloadEvent) {
        let mut hooks = self.global_hooks.recover_mut();
        hooks.retain(|(e, _)| *e != event);
    }

    /// Fire a download event hook for the given group.
    ///
    /// This method resolves the hook command from (in priority order):
    /// 1. Per-group `DownloadOptions` fields (e.g. `on_download_start`)
    /// 2. Global hooks registered via `set_global_hook()`
    ///
    /// If a command is found, it is spawned as an async child process
    /// with arguments: `<command> <GID_hex> <numFiles> <firstFilePath>`
    ///
    /// This is fire-and-forget — the caller is not blocked.
    /// Errors are logged but do not propagate.
    ///
    /// Mirrors C++ `util::executeHookByOptName(group, option, pref)` followed
    /// by `Notifier::notifyDownloadEvent()` — C++ performs both, in that
    /// order, at every hook site.
    pub fn fire_event(&self, event: DownloadEvent, group: &RequestGroup) {
        // C++ `util::executeHook()` formats the GID with `GroupId::toHex()`,
        // i.e. a zero-padded 16-digit lowercase hex string. Use the same
        // canonical form here so hook arguments match the original *and* so
        // observers receive exactly the GID the JSON-RPC layer publishes.
        let gid_hex = group.gid().to_hex_string();

        // ── Sink 1: user-configured shell hook (optional) ──────────────────
        match self.resolve_hook_command(event, group) {
            Some(command) if !command.is_empty() => {
                let (num_files, first_file_path) = Self::extract_file_info(group);
                self.spawn_hook(&command, &gid_hex, num_files, &first_file_path, event);
            }
            _ => {
                debug!(
                    event = event.name(),
                    gid = %gid_hex,
                    "No hook command configured, skipping shell hook"
                );
            }
        }

        // ── Sink 2: observers (unconditional) ─────────────────────────────
        // MUST run even when no shell hook is configured: the RPC WebSocket
        // notifications (aria2.onDownloadComplete / onDownloadError /
        // onBtDownloadComplete) are delivered through this path, and gating
        // them on an unrelated `--on-download-*` CLI option would leave every
        // default deployment without completion notifications.
        self.notify_listeners_scoped(event, &gid_hex, group.event_scope_id());
    }

    /// Fire a download event hook using direct parameters instead of a group.
    ///
    /// Useful when the RequestGroup is no longer available (e.g. after demotion)
    /// but the relevant data has already been extracted.
    ///
    /// `gid_hex` must be the canonical 16-digit hex GID (as produced by
    /// [`DownloadEventContext::from_group`]).
    pub fn fire_event_with_params(
        &self,
        event: DownloadEvent,
        gid_hex: &str,
        num_files: usize,
        first_file_path: &str,
        command: &str,
    ) {
        self.fire_event_with_params_in_scope(
            event,
            gid_hex,
            num_files,
            first_file_path,
            command,
            None,
        );
    }

    pub(crate) fn fire_event_with_params_scoped(
        &self,
        event: DownloadEvent,
        gid_hex: &str,
        num_files: usize,
        first_file_path: &str,
        command: &str,
        scope_id: u64,
    ) {
        self.fire_event_with_params_in_scope(
            event,
            gid_hex,
            num_files,
            first_file_path,
            command,
            Some(scope_id),
        );
    }

    fn fire_event_with_params_in_scope(
        &self,
        event: DownloadEvent,
        gid_hex: &str,
        num_files: usize,
        first_file_path: &str,
        command: &str,
        scope_id: Option<u64>,
    ) {
        // Sink 1 — only when a shell command was actually configured.
        if !command.is_empty() {
            self.spawn_hook(command, gid_hex, num_files, first_file_path, event);
        }
        // Sink 2 — always. See `fire_event` for why this must not be gated.
        self.notify_listeners_in_scope(event, gid_hex, scope_id);
    }

    /// Extract `(numFiles, firstFilePath)` hook arguments from a group.
    ///
    /// Mirrors the C++ `executeHookByOptName` body, which reads
    /// `group->getDownloadContext()->getNumFileEntries()` and the first
    /// requested file entry's path.
    fn extract_file_info(group: &RequestGroup) -> (usize, String) {
        if let Some(dctx) = group.download_context.recover().as_ref() {
            let num = dctx.count_requested_file_entry();
            let path = dctx.first_file_path().unwrap_or_default().to_string();
            (num, path)
        } else {
            (0, String::new())
        }
    }

    /// Resolve the hook command for an event from per-group or global config.
    fn resolve_hook_command(&self, event: DownloadEvent, group: &RequestGroup) -> Option<String> {
        // Priority 1: per-group options
        let opts = group.options_arc();
        let per_group = match event {
            DownloadEvent::Start => opts.on_download_start.as_ref(),
            DownloadEvent::Complete => opts.on_download_complete.as_ref(),
            DownloadEvent::Error => opts.on_download_error.as_ref(),
            DownloadEvent::Pause => opts.on_download_pause.as_ref(),
            DownloadEvent::Stop => opts.on_download_stop.as_ref(),
            DownloadEvent::BtComplete => opts.on_bt_download_complete.as_ref(),
        };

        if let Some(cmd) = per_group
            && !cmd.is_empty()
        {
            return Some(cmd.clone());
        }

        // Priority 2: global hooks
        let hooks = self.global_hooks.recover();
        for (e, cmd) in hooks.iter() {
            if *e == event && !cmd.is_empty() {
                return Some(cmd.clone());
            }
        }

        None
    }

    /// Spawn the hook command as an async child process.
    ///
    /// Mirrors C++ `util::executeHook()` which forks on Unix or
    /// `CreateProcessW` on Windows. The Rust version uses
    /// `tokio::process::Command` which handles both platforms.
    fn spawn_hook(
        &self,
        command: &str,
        gid_hex: &str,
        num_files: usize,
        first_file_path: &str,
        event: DownloadEvent,
    ) {
        info!(
            event = event.name(),
            command,
            gid = gid_hex,
            num_files,
            path = first_file_path,
            "Executing download event hook"
        );

        // Split command into program + args for proper process spawning.
        // C++ uses execlp(command, command, gidStr, numFilesStr, firstFilename, NULL)
        // which searches PATH and passes the arguments directly.
        let num_files_str = num_files.to_string();

        // On Windows, handle .bat/.cmd files specially (like C++ does).
        #[cfg(target_os = "windows")]
        let result = {
            let is_batch = command.to_lowercase().ends_with(".bat")
                || command.to_lowercase().ends_with(".cmd");

            if is_batch {
                let cmd_exe = std::env::var("windir")
                    .map(|w| format!("{}\\system32\\cmd.exe", w))
                    .unwrap_or_else(|_| "cmd.exe".to_string());

                let mut cmd = tokio::process::Command::new(&cmd_exe);
                cmd.args(["/c", command, gid_hex, &num_files_str, first_file_path])
                    .creation_flags(0x08000000); // CREATE_NO_WINDOW
                cmd.spawn()
            } else {
                tokio::process::Command::new(command)
                    .args([gid_hex, &num_files_str, first_file_path])
                    .spawn()
            }
        };

        #[cfg(not(target_os = "windows"))]
        let result = {
            tokio::process::Command::new(command)
                .args([gid_hex, &num_files_str, first_file_path])
                .spawn()
        };

        match result {
            Ok(mut child) => {
                if let Some(id) = child.id() {
                    debug!(event = event.name(), pid = id, "Hook process spawned");
                }
                // Fire-and-forget: await the child in a detached task
                // to reap zombies on Unix.
                let event_name = event.name().to_string();
                tokio::spawn(async move {
                    match child.wait().await {
                        Ok(status) => {
                            if !status.success() {
                                warn!(
                                    event = %event_name,
                                    exit = ?status.code(),
                                    "Hook process exited with non-zero status"
                                );
                            }
                        }
                        Err(e) => {
                            warn!(
                                event = %event_name,
                                error = %e,
                                "Failed to wait for hook process"
                            );
                        }
                    }
                });
            }
            Err(e) => {
                warn!(
                    event = event.name(),
                    command,
                    error = %e,
                    "Failed to spawn hook process"
                );
            }
        }
    }
}

impl Default for DownloadEventHooks {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Helper: extract hook context from a RequestGroup for demotion-time events
// ============================================================================

/// Pre-extracted context needed to fire stop/complete/error hooks after
/// the RequestGroup may no longer be available.
///
/// In C++ aria2, `executeStopHook()` is called while the group is still
/// alive. In Rust, we extract this data before demotion releases resources.
#[derive(Debug, Clone)]
pub struct DownloadEventContext {
    /// GID as hex string (for hook command argument).
    pub gid_hex: String,
    /// Number of requested file entries.
    pub num_files: usize,
    /// Path of the first requested file.
    pub first_file_path: String,
    /// Per-group hook commands (resolved at extraction time).
    pub on_download_complete: Option<String>,
    pub on_download_error: Option<String>,
    pub on_download_pause: Option<String>,
    pub on_download_stop: Option<String>,
    pub on_bt_download_complete: Option<String>,
}

impl DownloadEventContext {
    /// Extract event context from a RequestGroup before it is demoted.
    ///
    /// Must be called BEFORE `demote_group()` releases the download context.
    pub fn from_group(group: &RequestGroup) -> Self {
        // Canonical 16-digit hex, matching C++ `GroupId::toHex()` and the GID
        // format used by the JSON-RPC layer.
        let gid_hex = group.gid().to_hex_string();

        let (num_files, first_file_path) =
            if let Some(dctx) = group.download_context.recover().as_ref() {
                let num = dctx.count_requested_file_entry();
                let path = dctx.first_file_path().unwrap_or_default().to_string();
                (num, path)
            } else {
                (0, String::new())
            };

        let opts = group.options_arc();

        Self {
            gid_hex,
            num_files,
            first_file_path,
            on_download_complete: opts.on_download_complete.clone(),
            on_download_error: opts.on_download_error.clone(),
            on_download_pause: opts.on_download_pause.clone(),
            on_download_stop: opts.on_download_stop.clone(),
            on_bt_download_complete: opts.on_bt_download_complete.clone(),
        }
    }
}

/// Determine which event to fire for a stopped download.
///
/// Mirrors C++ `executeStopHook()` logic:
/// - If result == FINISHED → `Complete`
/// - If result != IN_PROGRESS && != REMOVED → `Error`
/// - Otherwise → `Stop`
///
/// Also fires `Pause` when the group was pause-requested.
pub fn determine_stop_event(
    is_complete: bool,
    is_error: bool,
    is_paused: bool,
) -> Option<DownloadEvent> {
    if is_paused {
        return Some(DownloadEvent::Pause);
    }
    if is_complete {
        return Some(DownloadEvent::Complete);
    }
    if is_error {
        return Some(DownloadEvent::Error);
    }
    // Not paused, not complete, not error → generic stop
    Some(DownloadEvent::Stop)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_determine_stop_event_complete() {
        assert_eq!(
            determine_stop_event(true, false, false),
            Some(DownloadEvent::Complete)
        );
    }

    #[test]
    fn test_determine_stop_event_error() {
        assert_eq!(
            determine_stop_event(false, true, false),
            Some(DownloadEvent::Error)
        );
    }

    #[test]
    fn test_determine_stop_event_paused() {
        assert_eq!(
            determine_stop_event(false, false, true),
            Some(DownloadEvent::Pause)
        );
    }

    #[test]
    fn test_determine_stop_event_generic_stop() {
        assert_eq!(
            determine_stop_event(false, false, false),
            Some(DownloadEvent::Stop)
        );
    }

    #[test]
    fn test_event_names() {
        assert_eq!(DownloadEvent::Start.name(), "on-download-start");
        assert_eq!(DownloadEvent::Complete.name(), "on-download-complete");
        assert_eq!(DownloadEvent::Error.name(), "on-download-error");
        assert_eq!(DownloadEvent::Pause.name(), "on-download-pause");
        assert_eq!(DownloadEvent::Stop.name(), "on-download-stop");
        assert_eq!(DownloadEvent::BtComplete.name(), "on-bt-download-complete");
    }

    #[test]
    fn test_global_hook_registration() {
        let hooks = DownloadEventHooks::new();
        hooks.set_global_hook(DownloadEvent::Start, "/usr/bin/echo".to_string());
        hooks.set_global_hook(DownloadEvent::Complete, "/usr/bin/notify".to_string());

        let guard = hooks.global_hooks.recover();
        assert_eq!(guard.len(), 2);
        assert!(guard.iter().any(|(e, _)| *e == DownloadEvent::Start));
        assert!(guard.iter().any(|(e, _)| *e == DownloadEvent::Complete));
    }

    #[test]
    fn test_global_hook_replacement() {
        let hooks = DownloadEventHooks::new();
        hooks.set_global_hook(DownloadEvent::Start, "/usr/bin/old".to_string());
        hooks.set_global_hook(DownloadEvent::Start, "/usr/bin/new".to_string());

        let guard = hooks.global_hooks.recover();
        let start_hook = guard.iter().find(|(e, _)| *e == DownloadEvent::Start);
        assert_eq!(start_hook.unwrap().1, "/usr/bin/new");
    }

    #[test]
    fn test_global_hook_removal() {
        let hooks = DownloadEventHooks::new();
        hooks.set_global_hook(DownloadEvent::Start, "/usr/bin/echo".to_string());
        hooks.remove_global_hook(DownloadEvent::Start);

        let guard = hooks.global_hooks.recover();
        assert!(guard.is_empty());
    }

    // ── Observer (DownloadEventListener) tests ───────────────────────────

    /// Records every event it is notified about.
    #[derive(Default)]
    struct RecordingListener {
        seen: std::sync::Mutex<Vec<(DownloadEvent, String)>>,
        metadata_seen: std::sync::Mutex<Vec<MetadataResolvedEvent>>,
    }

    impl RecordingListener {
        fn events(&self) -> Vec<(DownloadEvent, String)> {
            self.seen.lock().unwrap().clone()
        }

        fn metadata_events(&self) -> Vec<MetadataResolvedEvent> {
            self.metadata_seen.lock().unwrap().clone()
        }
    }

    impl DownloadEventListener for RecordingListener {
        fn on_download_event(&self, event: DownloadEvent, gid: &str) {
            self.seen.lock().unwrap().push((event, gid.to_string()));
        }

        fn on_metadata_resolved(&self, event: &MetadataResolvedEvent) {
            self.metadata_seen.lock().unwrap().push(event.clone());
        }
    }

    #[test]
    fn test_add_listener_tracks_registration() {
        let hooks = DownloadEventHooks::new();
        assert_eq!(hooks.listener_count(), 0);
        hooks.add_listener(Arc::new(RecordingListener::default()));
        hooks.add_listener(Arc::new(RecordingListener::default()));
        assert_eq!(hooks.listener_count(), 2);
    }

    #[test]
    fn test_listener_can_be_removed_explicitly() {
        let hooks = DownloadEventHooks::new();
        let id = hooks.add_listener_with_id(Arc::new(RecordingListener::default()));
        assert_eq!(hooks.listener_count(), 1);
        assert!(hooks.remove_listener(id));
        assert_eq!(hooks.listener_count(), 0);
        assert!(!hooks.remove_listener(id));
    }

    struct ToggleListener {
        alive: std::sync::atomic::AtomicBool,
    }

    impl DownloadEventListener for ToggleListener {
        fn on_download_event(&self, _event: DownloadEvent, _gid: &str) {}

        fn is_alive(&self) -> bool {
            self.alive.load(std::sync::atomic::Ordering::Relaxed)
        }
    }

    #[test]
    fn test_registration_prunes_dead_listeners() {
        let hooks = DownloadEventHooks::new();
        let stale = Arc::new(ToggleListener {
            alive: std::sync::atomic::AtomicBool::new(true),
        });
        hooks.add_listener(stale.clone());
        stale
            .alive
            .store(false, std::sync::atomic::Ordering::Relaxed);

        hooks.add_listener(Arc::new(RecordingListener::default()));

        assert_eq!(hooks.listener_count(), 1);
    }

    #[test]
    fn test_notify_listeners_delivers_to_all_listeners() {
        let hooks = DownloadEventHooks::new();
        let a = Arc::new(RecordingListener::default());
        let b = Arc::new(RecordingListener::default());
        hooks.add_listener(a.clone());
        hooks.add_listener(b.clone());

        hooks.notify_listeners(DownloadEvent::Complete, "00000000000000ff");

        let expected = vec![(DownloadEvent::Complete, "00000000000000ff".to_string())];
        assert_eq!(a.events(), expected);
        assert_eq!(b.events(), expected);
    }

    #[test]
    fn test_notify_metadata_resolved_delivers_structured_event() {
        let hooks = DownloadEventHooks::new();
        let listener = Arc::new(RecordingListener::default());
        hooks.add_listener(listener.clone());

        hooks.notify_metadata_resolved(MetadataResolvedEvent::new(
            crate::request::request_group::GroupId::new(10),
            vec![crate::request::request_group::GroupId::new(11)],
        ));

        assert_eq!(
            listener.metadata_events(),
            vec![MetadataResolvedEvent::new(
                crate::request::request_group::GroupId::new(10),
                vec![crate::request::request_group::GroupId::new(11)],
            )]
        );
    }

    #[tokio::test]
    async fn test_event_stream_receives_lifecycle_and_metadata_events() {
        let hooks = DownloadEventHooks::new();
        let mut stream = hooks.subscribe();

        hooks.notify_listeners(DownloadEvent::Start, "0000000000000001");
        assert_eq!(
            stream.recv().await.expect("lifecycle event"),
            DownloadNotification::Lifecycle {
                event: DownloadEvent::Start,
                gid: "0000000000000001".to_string(),
            }
        );

        let metadata = MetadataResolvedEvent::new(
            crate::request::request_group::GroupId::new(10),
            vec![crate::request::request_group::GroupId::new(11)],
        );
        hooks.notify_metadata_resolved(metadata.clone());
        assert_eq!(
            stream.recv().await.expect("metadata event"),
            DownloadNotification::MetadataResolved(metadata)
        );
    }

    #[tokio::test]
    async fn metadata_stream_helper_filters_by_metadata_or_download_gid() {
        let hooks = DownloadEventHooks::new();
        let mut stream = hooks.subscribe();
        let requested_gid = crate::request::request_group::GroupId::new(11);
        let unrelated = MetadataResolvedEvent::new(
            crate::request::request_group::GroupId::new(20),
            vec![crate::request::request_group::GroupId::new(21)],
        );
        let matching = MetadataResolvedEvent::new(
            crate::request::request_group::GroupId::new(10),
            vec![requested_gid],
        );

        hooks.notify_metadata_resolved(unrelated);
        hooks.notify_metadata_resolved(matching.clone());

        assert_eq!(
            stream
                .recv_metadata_for(requested_gid)
                .await
                .expect("matching metadata event"),
            matching
        );
    }

    #[tokio::test]
    async fn terminal_stream_helper_filters_by_gid_and_event_kind() {
        let hooks = DownloadEventHooks::new();
        let mut stream = hooks.subscribe();
        let requested_gid = crate::request::request_group::GroupId::new(11);

        hooks.notify_listeners(DownloadEvent::Start, "000000000000000b");
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000a");
        hooks.notify_listeners(DownloadEvent::Stop, "000000000000000b");

        assert_eq!(
            stream
                .recv_terminal_for(requested_gid)
                .await
                .expect("matching terminal event"),
            DownloadEvent::Stop
        );
    }

    #[tokio::test]
    async fn terminal_stream_helper_waits_past_bt_payload_completion() {
        let hooks = DownloadEventHooks::new();
        let mut stream = hooks.subscribe();
        let requested_gid = crate::request::request_group::GroupId::new(12);
        let gid = requested_gid.to_hex_string();

        hooks.notify_listeners(DownloadEvent::BtComplete, &gid);
        hooks.notify_listeners(DownloadEvent::Complete, &gid);

        assert_eq!(
            stream
                .recv_terminal_for(requested_gid)
                .await
                .expect("seeding completion is terminal"),
            DownloadEvent::Complete
        );
    }

    /// Regression test for the P0 defect: observers were only reached when a
    /// `--on-download-*` shell command happened to be configured, so RPC
    /// clients never saw `aria2.onDownloadComplete` in a default deployment.
    #[test]
    fn test_fire_event_with_params_notifies_listener_without_shell_command() {
        let hooks = DownloadEventHooks::new();
        let listener = Arc::new(RecordingListener::default());
        hooks.add_listener(listener.clone());

        // Empty command == no `--on-download-complete` configured.
        hooks.fire_event_with_params(
            DownloadEvent::Complete,
            "0000000000000001",
            1,
            "/tmp/a.bin",
            "",
        );

        assert_eq!(
            listener.events(),
            vec![(DownloadEvent::Complete, "0000000000000001".to_string())],
            "observers must be notified even with no shell hook configured"
        );
    }

    #[test]
    fn test_one_shot_events_are_deduplicated_per_gid() {
        let hooks = DownloadEventHooks::new();
        let listener = Arc::new(RecordingListener::default());
        hooks.add_listener(listener.clone());

        // Same terminal event emitted twice for the same download (state
        // transition + engine-loop demotion) must reach the observer once.
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000a");
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000a");
        // A different GID is a different download.
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000b");
        // A different terminal event for the first download still passes.
        hooks.notify_listeners(DownloadEvent::BtComplete, "000000000000000a");

        assert_eq!(
            listener.events(),
            vec![
                (DownloadEvent::Complete, "000000000000000a".to_string()),
                (DownloadEvent::Complete, "000000000000000b".to_string()),
                (DownloadEvent::BtComplete, "000000000000000a".to_string()),
            ]
        );
    }

    #[test]
    fn test_repeatable_events_are_not_deduplicated() {
        let hooks = DownloadEventHooks::new();
        let listener = Arc::new(RecordingListener::default());
        hooks.add_listener(listener.clone());

        // Pause/unpause cycles legitimately repeat Start and Pause.
        hooks.notify_listeners(DownloadEvent::Pause, "000000000000000c");
        hooks.notify_listeners(DownloadEvent::Start, "000000000000000c");
        hooks.notify_listeners(DownloadEvent::Pause, "000000000000000c");

        assert_eq!(listener.events().len(), 3);
    }

    #[test]
    fn test_notify_listeners_is_noop_without_listeners() {
        let hooks = DownloadEventHooks::new();
        // Must not panic and must not consume de-duplication budget, so a
        // listener registered later still receives the event.
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000d");

        let listener = Arc::new(RecordingListener::default());
        hooks.add_listener(listener.clone());
        hooks.notify_listeners(DownloadEvent::Complete, "000000000000000d");

        assert_eq!(listener.events().len(), 1);
    }

    #[test]
    fn test_shared_bus_is_a_singleton() {
        let a = DownloadEventHooks::shared();
        let b = DownloadEventHooks::shared();
        assert!(Arc::ptr_eq(a, b), "shared() must return the same instance");
    }

    #[test]
    fn test_is_once_per_download_classification() {
        assert!(DownloadEvent::Complete.is_once_per_download());
        assert!(DownloadEvent::Error.is_once_per_download());
        assert!(DownloadEvent::BtComplete.is_once_per_download());
        assert!(!DownloadEvent::Start.is_once_per_download());
        assert!(!DownloadEvent::Pause.is_once_per_download());
        assert!(!DownloadEvent::Stop.is_once_per_download());
    }

    #[test]
    fn test_terminal_event_classification() {
        assert!(DownloadEvent::Stop.is_terminal());
        assert!(DownloadEvent::Complete.is_terminal());
        assert!(DownloadEvent::Error.is_terminal());
        assert!(!DownloadEvent::BtComplete.is_terminal());
        assert!(!DownloadEvent::Start.is_terminal());
        assert!(!DownloadEvent::Pause.is_terminal());
    }

    #[test]
    fn test_one_shot_ledger_rotates_and_stays_bounded() {
        let mut ledger = OneShotLedger::default();
        for i in 0..(DEDUP_GENERATION_CAPACITY + 10) {
            assert!(ledger.claim((None, format!("{:016x}", i), DownloadEvent::Complete)));
        }
        // Rotation happened, so neither generation exceeds the cap.
        assert!(ledger.current.len() <= DEDUP_GENERATION_CAPACITY);
        assert!(ledger.previous.len() <= DEDUP_GENERATION_CAPACITY);
        // The most recent entries are still remembered.
        assert!(!ledger.claim((
            None,
            format!("{:016x}", DEDUP_GENERATION_CAPACITY + 9),
            DownloadEvent::Complete
        )));
    }
}