aria2-rpc 0.3.2

Remote control server for aria2-rust: aria2-compatible JSON-RPC 2.0, XML-RPC, and WebSocket download management
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;
use tokio::sync::broadcast;

/// Configuration for WebSocket connection keepalive behavior.
///
/// Controls ping/pong interval and timeout thresholds for detecting
/// stale or unresponsive WebSocket connections.
#[derive(Debug, Clone)]
pub struct WsConfig {
    /// Interval in seconds between sending Ping frames (default: 30)
    pub ping_interval_secs: u64,
    /// Timeout in seconds after which a missed Pong triggers connection close (default: 60)
    pub pong_timeout_secs: u64,
}

impl Default for WsConfig {
    fn default() -> Self {
        Self {
            ping_interval_secs: 30,
            pong_timeout_secs: 60,
        }
    }
}

impl WsConfig {
    /// Create a new WsConfig with custom values.
    pub fn new(ping_interval_secs: u64, pong_timeout_secs: u64) -> Self {
        Self {
            ping_interval_secs,
            pong_timeout_secs,
        }
    }

    /// Builder-style method to set custom ping interval.
    pub fn with_ping_interval(mut self, secs: u64) -> Self {
        self.ping_interval_secs = secs;
        self
    }

    /// Builder-style method to set custom pong timeout.
    pub fn with_pong_timeout(mut self, secs: u64) -> Self {
        self.pong_timeout_secs = secs;
        self
    }
}

/// Download event types matching C++ aria2 WebSocketSessionMan.
///
/// C++ aria2 defines exactly 6 notification events.
/// Non-standard events (BtCacheChanged, BtDownloadError, DownloadResume)
/// are intentionally excluded for client compatibility.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum EventType {
    DownloadStart,
    DownloadPause,
    DownloadStop,
    DownloadComplete,
    DownloadError,
    BtDownloadComplete,
}

impl EventType {
    pub fn method_name(&self) -> &'static str {
        match self {
            Self::DownloadStart => crate::constants::WS_EVENT_DOWNLOAD_START,
            Self::DownloadPause => crate::constants::WS_EVENT_DOWNLOAD_PAUSE,
            Self::DownloadStop => crate::constants::WS_EVENT_DOWNLOAD_STOP,
            Self::DownloadComplete => crate::constants::WS_EVENT_DOWNLOAD_COMPLETE,
            Self::DownloadError => crate::constants::WS_EVENT_DOWNLOAD_ERROR,
            Self::BtDownloadComplete => crate::constants::WS_EVENT_BT_DOWNLOAD_COMPLETE,
        }
    }

    pub fn from_method(method: &str) -> Option<Self> {
        match method {
            crate::constants::WS_EVENT_DOWNLOAD_START => Some(Self::DownloadStart),
            crate::constants::WS_EVENT_DOWNLOAD_PAUSE => Some(Self::DownloadPause),
            crate::constants::WS_EVENT_DOWNLOAD_STOP => Some(Self::DownloadStop),
            crate::constants::WS_EVENT_DOWNLOAD_COMPLETE => Some(Self::DownloadComplete),
            crate::constants::WS_EVENT_DOWNLOAD_ERROR => Some(Self::DownloadError),
            crate::constants::WS_EVENT_BT_DOWNLOAD_COMPLETE => Some(Self::BtDownloadComplete),
            _ => None,
        }
    }
}

/// JSON-RPC notification matching C++ aria2 WebSocketSessionMan::addNotification format.
///
/// C++ format: `{"jsonrpc":"2.0","method":"aria2.onDownloadStart","params":[{"gid":"hexgid"}]}`
///
/// The `params` array contains a single object with only the `gid` field,
/// matching the C++ implementation exactly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadEvent {
    #[serde(rename = "jsonrpc")]
    version: String,
    method: String,
    params: Vec<serde_json::Value>,
}

impl DownloadEvent {
    /// Create a new notification event with custom params.
    pub fn new(event_type: EventType, params: Vec<serde_json::Value>) -> Self {
        Self {
            version: "2.0".to_string(),
            method: event_type.method_name().to_string(),
            params,
        }
    }

    /// Create a notification matching C++ format: `params: [{"gid": gid}]`.
    fn from_gid(event_type: EventType, gid: impl Into<String>) -> Self {
        Self::new(event_type, vec![serde_json::json!({"gid": gid.into()})])
    }

    pub fn event_type(&self) -> Option<EventType> {
        EventType::from_method(&self.method)
    }
    pub fn method(&self) -> &str {
        &self.method
    }
    pub fn params(&self) -> &[serde_json::Value] {
        &self.params
    }

    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Extract the GID from this event's params.
    ///
    /// Returns the GID string if present in the first param object,
    /// or an empty string if not found.
    pub fn gid(&self) -> String {
        self.params
            .first()
            .and_then(|p| p.get("gid"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string()
    }

    /// Get the event type as a string suitable for deduplication keys.
    ///
    /// Returns the method name (e.g., "aria2.onDownloadComplete") or empty string.
    pub fn event_type_str(&self) -> String {
        self.method.clone()
    }

    // -- C++ compatible notification constructors (5 core + BT event) --

    pub fn download_start(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::DownloadStart, gid)
    }

    pub fn download_complete(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::DownloadComplete, gid)
    }

    pub fn download_error(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::DownloadError, gid)
    }

    pub fn download_pause(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::DownloadPause, gid)
    }

    pub fn download_stop(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::DownloadStop, gid)
    }

    pub fn bt_download_complete(gid: impl Into<String>) -> Self {
        Self::from_gid(EventType::BtDownloadComplete, gid)
    }
}

struct Subscriber {
    #[allow(dead_code)] // Subscriber ID for debugging and connection management
    id: String,
    #[allow(dead_code)] // Event filter; stored for per-subscriber event filtering
    filter: Option<Vec<EventType>>,
}

/// Receiver registration that removes its bookkeeping entry when dropped.
///
/// The broadcast receiver itself already releases its channel slot on drop;
/// this companion guard keeps `EventPublisher::subscriber_count` aligned with
/// the active WebSocket session lifecycle as well.
pub(crate) struct ScopedSubscription {
    id: String,
    receiver: broadcast::Receiver<(EventType, DownloadEvent)>,
    subscribers: Arc<RwLock<HashMap<String, Subscriber>>>,
}

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

impl Drop for ScopedSubscription {
    fn drop(&mut self) {
        // Never panic while tearing down a WebSocket task. A poisoned lock can
        // only result from an earlier internal panic, and must not prevent the
        // receiver itself from being released.
        if let Ok(mut subscribers) = self.subscribers.write() {
            subscribers.remove(&self.id);
        }
    }
}

pub struct EventPublisher {
    tx: broadcast::Sender<(EventType, DownloadEvent)>,
    subscribers: Arc<RwLock<HashMap<String, Subscriber>>>,
}

impl EventPublisher {
    pub fn new(capacity: usize) -> Self {
        let (tx, _) = broadcast::channel(capacity);
        Self {
            tx,
            subscribers: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    fn register(&self, id: String, filter: Option<Vec<EventType>>) {
        let mut subscribers = self
            .subscribers
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        subscribers.insert(id.clone(), Subscriber { id, filter });
    }

    pub async fn subscribe(
        &self,
        sub_id: impl Into<String>,
        filter: Option<Vec<EventType>>,
    ) -> broadcast::Receiver<(EventType, DownloadEvent)> {
        let id = sub_id.into();
        self.register(id, filter);
        self.tx.subscribe()
    }

    /// Subscribe a connection whose bookkeeping must end with its receiver.
    ///
    /// This is intentionally crate-private: public callers retain the
    /// established explicit `subscribe` / `unsubscribe` lifecycle.
    pub(crate) fn subscribe_scoped(
        &self,
        sub_id: impl Into<String>,
        filter: Option<Vec<EventType>>,
    ) -> ScopedSubscription {
        let id = sub_id.into();
        self.register(id.clone(), filter);
        ScopedSubscription {
            id,
            receiver: self.tx.subscribe(),
            subscribers: Arc::clone(&self.subscribers),
        }
    }

    pub async fn unsubscribe(&self, sub_id: &str) {
        let mut subscribers = self
            .subscribers
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        subscribers.remove(sub_id);
    }

    pub async fn subscriber_count(&self) -> usize {
        self.subscribers
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .len()
    }

    pub fn publish(&self, event_type: EventType, event: DownloadEvent) -> Result<usize, String> {
        match self.tx.send((event_type, event)) {
            Ok(_) => Ok(self.tx.receiver_count()),
            Err(e) => Err(format!("No subscribers: {}", e)),
        }
    }

    pub fn publish_event(&self, event: DownloadEvent) -> Result<usize, String> {
        if let Some(et) = event.event_type() {
            self.publish(et, event)
        } else {
            Err("Unknown event type".to_string())
        }
    }
}

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

// =========================================================================
// Notification Batcher (G7: Deduplication + Batching)
// =========================================================================

use std::collections::VecDeque;

/// Batches and deduplicates download event notifications.
///
/// Accumulates notifications and flushes them either when the batch size
/// limit is reached or when a time-based interval elapses. Deduplicates
/// events that share the same GID + event type combination, keeping only
/// the latest version (which may have updated progress/speed data).
///
/// # Example
///
/// ```ignore
/// let mut batcher = NotificationBatcher::new()
///     .with_max_batch_size(20)
///     .with_flush_interval_ms(500);
///
/// batcher.push(event1);
/// batcher.push(event2); // same GID+type as event1 → deduped
///
/// if let Some(batch) = batcher.maybe_flush() {
///     for notification in batch {
///         send_to_client(notification);
///     }
/// }
/// ```
pub struct NotificationBatcher {
    /// Maximum number of notifications before auto-flush triggers
    max_batch_size: usize,
    /// Time-based flush interval in milliseconds
    flush_interval_ms: u64,
    /// Accumulated notifications waiting to be flushed
    pending: VecDeque<DownloadEvent>,
    /// Tracks the latest event per (GID:event_type) key for deduplication
    latest_per_gid: HashMap<String, (DownloadEvent, Instant)>,
    /// Timestamp of last flush operation
    last_flush: Instant,
    /// Total number of notifications sent via flush
    total_sent: u64,
    /// Total number of notifications deduplicated (replaced by newer version)
    total_deduped: u64,
}

impl NotificationBatcher {
    /// Create a new NotificationBatcher with default settings.
    ///
    /// Defaults: max_batch_size=20, flush_interval_ms=500
    pub fn new() -> Self {
        Self {
            max_batch_size: 20,
            flush_interval_ms: 500,
            pending: VecDeque::new(),
            latest_per_gid: HashMap::new(),
            last_flush: Instant::now(),
            total_sent: 0,
            total_deduped: 0,
        }
    }

    /// Set the maximum batch size before auto-flush triggers.
    pub fn with_max_batch_size(mut self, size: usize) -> Self {
        self.max_batch_size = size;
        self
    }

    /// Set the timer-based flush interval in milliseconds.
    pub fn with_flush_interval_ms(mut self, ms: u64) -> Self {
        self.flush_interval_ms = ms;
        self
    }

    /// Push a notification into the batcher.
    ///
    /// Performs deduplication: if an event with the same (GID, event_type)
    /// already exists, it is replaced with this newer version.
    /// Returns `true` if the push triggered an auto-flush (batch full).
    pub fn push(&mut self, notification: DownloadEvent) -> bool {
        let gid = notification.gid();
        let event_type = notification.event_type_str();

        // Build dedup key from GID + event type combination
        let key = format!("{}:{}", gid, event_type);

        if let Some(existing) = self.latest_per_gid.get_mut(&key) {
            // Replace with newer version (updated progress/speed/etc.)
            *existing = (notification, Instant::now());
            self.total_deduped += 1;
            tracing::debug!("Deduped notification for {}: {}", gid, event_type);
        } else {
            // New event: store in both the dedup map and pending queue
            self.latest_per_gid
                .insert(key.clone(), (notification.clone(), Instant::now()));
            self.pending.push_back(notification);
        }

        // Auto-flush if over batch size limit
        if self.pending.len() >= self.max_batch_size {
            self.flush_internal();
            true
        } else {
            false
        }
    }

    /// Timer-based flush — call this periodically from main loop.
    ///
    /// Returns `Some(batch)` if notifications were flushed, `None` otherwise.
    /// Flushes when:
    /// - The flush interval has elapsed since last flush, AND
    /// - There are pending notifications
    pub fn maybe_flush(&mut self) -> Option<Vec<DownloadEvent>> {
        let elapsed_ms = self.last_flush.elapsed().as_millis() as u64;
        if elapsed_ms >= self.flush_interval_ms && !self.pending.is_empty() {
            self.flush_internal()
        } else {
            None
        }
    }

    /// Internal flush: drain all pending notifications and reset state.
    fn flush_internal(&mut self) -> Option<Vec<DownloadEvent>> {
        if self.pending.is_empty() {
            return None;
        }

        let batch: Vec<DownloadEvent> = self.pending.drain(..).collect();
        self.total_sent += batch.len() as u64;
        self.latest_per_gid.clear();
        self.last_flush = Instant::now();
        Some(batch)
    }

    /// Get statistics: (total_sent, total_deduped).
    pub fn stats(&self) -> (u64, u64) {
        (self.total_sent, self.total_deduped)
    }

    /// Returns the number of pending notifications awaiting flush.
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }
}

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

pub struct WsSession {
    id: String,
    rx: broadcast::Receiver<(EventType, DownloadEvent)>,
}

impl WsSession {
    pub fn new(id: impl Into<String>, rx: broadcast::Receiver<(EventType, DownloadEvent)>) -> Self {
        Self { id: id.into(), rx }
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub async fn recv(&mut self) -> Option<(EventType, DownloadEvent)> {
        self.rx.recv().await.ok()
    }
}

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

    // =========================================================================
    // EventType Tests
    // =========================================================================

    #[test]
    fn test_event_type_method_names() {
        assert_eq!(
            EventType::DownloadStart.method_name(),
            "aria2.onDownloadStart"
        );
        assert_eq!(
            EventType::DownloadComplete.method_name(),
            "aria2.onDownloadComplete"
        );
        assert_eq!(
            EventType::DownloadError.method_name(),
            "aria2.onDownloadError"
        );
    }

    #[test]
    fn test_event_type_from_method() {
        assert!(EventType::from_method("aria2.onDownloadStart").is_some());
        assert!(EventType::from_method("aria2.unknown").is_none());
    }

    // =========================================================================
    // DownloadEvent Tests
    // =========================================================================

    #[test]
    fn test_download_event_creation() {
        let event = DownloadEvent::download_start("abc123");
        assert_eq!(event.event_type().unwrap(), EventType::DownloadStart);
        assert_eq!(event.method(), "aria2.onDownloadStart");
        assert_eq!(event.params().len(), 1);
    }

    #[test]
    fn test_download_event_serialization() {
        let event = DownloadEvent::download_error("def456");
        let json = event.to_json().unwrap();
        assert!(json.contains("\"method\":\"aria2.onDownloadError\""));
        // C++ format: params only contains {"gid": "..."}, no errorCode
        assert!(json.contains("\"gid\":\"def456\""));
        assert!(
            !json.contains("errorCode"),
            "C++ notification should not contain errorCode"
        );
    }

    #[test]
    fn test_all_event_constructors() {
        let _ = DownloadEvent::download_start("g1");
        let _ = DownloadEvent::download_pause("g2");
        let _ = DownloadEvent::download_stop("g3");
        let _ = DownloadEvent::download_complete("g4");
        let _ = DownloadEvent::download_error("g5");
        let _ = DownloadEvent::bt_download_complete("g6");
    }

    #[test]
    fn test_download_event_gid_extraction() {
        let event = DownloadEvent::download_complete("gid-001");
        assert_eq!(event.gid(), "gid-001");

        let event2 = DownloadEvent::download_error("gid-err");
        assert_eq!(event2.gid(), "gid-err");
    }

    #[test]
    fn test_download_event_event_type_str() {
        let event = DownloadEvent::download_start("g1");
        assert_eq!(event.event_type_str(), "aria2.onDownloadStart");

        let event2 = DownloadEvent::bt_download_complete("g2");
        assert_eq!(event2.event_type_str(), "aria2.onBtDownloadComplete");
    }

    // =========================================================================
    // C++ Compatibility Format Tests
    // =========================================================================

    /// Verify that all 6 C++ notification events serialize to the exact
    /// JSON-RPC format produced by C++ aria2's WebSocketSessionMan::addNotification.
    ///
    /// C++ produces: `{"jsonrpc":"2.0","method":"aria2.on<Event>","params":[{"gid":"<hex>"}]}`
    #[test]
    fn test_cpp_compatible_notification_format() {
        let test_cases: Vec<(EventType, &str, &str)> = vec![
            (
                EventType::DownloadStart,
                "aria2.onDownloadStart",
                "2089b05ecca3d829",
            ),
            (
                EventType::DownloadPause,
                "aria2.onDownloadPause",
                "a2bc3d4e5f6a7b8c",
            ),
            (
                EventType::DownloadStop,
                "aria2.onDownloadStop",
                "deadbeef12345678",
            ),
            (
                EventType::DownloadComplete,
                "aria2.onDownloadComplete",
                "c0ffee0000000001",
            ),
            (
                EventType::DownloadError,
                "aria2.onDownloadError",
                "bada5590abcdef01",
            ),
            (
                EventType::BtDownloadComplete,
                "aria2.onBtDownloadComplete",
                "1a2b3c4d5e6f7a8b",
            ),
        ];

        for (event_type, expected_method, gid) in &test_cases {
            let event = match event_type {
                EventType::DownloadStart => DownloadEvent::download_start(*gid),
                EventType::DownloadPause => DownloadEvent::download_pause(*gid),
                EventType::DownloadStop => DownloadEvent::download_stop(*gid),
                EventType::DownloadComplete => DownloadEvent::download_complete(*gid),
                EventType::DownloadError => DownloadEvent::download_error(*gid),
                EventType::BtDownloadComplete => DownloadEvent::bt_download_complete(*gid),
            };

            let json_str = event.to_json().expect("serialization should succeed");
            let parsed: serde_json::Value =
                serde_json::from_str(&json_str).expect("should parse back");

            // Verify jsonrpc version
            assert_eq!(
                parsed["jsonrpc"], "2.0",
                "jsonrpc version mismatch for {}",
                expected_method
            );

            // Verify method name
            assert_eq!(parsed["method"], *expected_method, "method mismatch");

            // Verify params structure: must be an array with exactly 1 element
            let params = parsed["params"].as_array().expect("params should be array");
            assert_eq!(
                params.len(),
                1,
                "params should have exactly 1 element for {}",
                expected_method
            );

            // The single param must be an object containing ONLY "gid"
            let param_obj = params[0].as_object().expect("param[0] should be object");
            assert_eq!(
                param_obj.len(),
                1,
                "param[0] should contain only 'gid' for {}",
                expected_method
            );
            assert_eq!(
                param_obj["gid"], *gid,
                "gid mismatch for {}",
                expected_method
            );

            // Verify no extra fields (files, errorCode, etc.)
            assert!(
                !param_obj.contains_key("files"),
                "C++ notification should NOT contain 'files' for {}",
                expected_method
            );
            assert!(
                !param_obj.contains_key("errorCode"),
                "C++ notification should NOT contain 'errorCode' for {}",
                expected_method
            );

            // Also verify the exact expected JSON string for one case
            if *expected_method == "aria2.onDownloadStart" {
                let expected = r#"{"jsonrpc":"2.0","method":"aria2.onDownloadStart","params":[{"gid":"2089b05ecca3d829"}]}"#;
                assert_eq!(
                    json_str, expected,
                    "exact C++ format mismatch for onDownloadStart"
                );
            }
        }
    }

    /// Verify only 6 EventType variants exist (matching C++).
    #[test]
    fn test_exactly_six_event_types() {
        let all_methods: Vec<&'static str> = vec![
            EventType::DownloadStart.method_name(),
            EventType::DownloadPause.method_name(),
            EventType::DownloadStop.method_name(),
            EventType::DownloadComplete.method_name(),
            EventType::DownloadError.method_name(),
            EventType::BtDownloadComplete.method_name(),
        ];
        assert_eq!(
            all_methods.len(),
            6,
            "Should have exactly 6 event types matching C++"
        );
    }

    // =========================================================================
    // WsConfig Tests (G4 Part A)
    // =========================================================================

    #[test]
    fn test_ws_config_default() {
        let cfg = WsConfig::default();
        assert_eq!(cfg.ping_interval_secs, 30);
        assert_eq!(cfg.pong_timeout_secs, 60);
    }

    #[test]
    fn test_ws_config_new() {
        let cfg = WsConfig::new(15, 45);
        assert_eq!(cfg.ping_interval_secs, 15);
        assert_eq!(cfg.pong_timeout_secs, 45);
    }

    #[test]
    fn test_ws_config_builder() {
        let cfg = WsConfig::default()
            .with_ping_interval(10)
            .with_pong_timeout(30);
        assert_eq!(cfg.ping_interval_secs, 10);
        assert_eq!(cfg.pong_timeout_secs, 30);
    }

    // =========================================================================
    // EventPublisher Tests
    // =========================================================================

    #[tokio::test]
    async fn test_publisher_subscribe_publish() {
        let publisher = EventPublisher::new(16);
        let mut rx = publisher.subscribe("client-1", None).await;

        let event = DownloadEvent::download_start("test-gid");
        let count = publisher.publish(EventType::DownloadStart, event).unwrap();
        assert_eq!(count, 1);

        let (et, received) = rx.recv().await.unwrap();
        assert_eq!(et, EventType::DownloadStart);
        assert_eq!(received.method(), "aria2.onDownloadStart");
    }

    #[tokio::test]
    async fn test_publisher_unsubscribe() {
        let publisher = EventPublisher::new(16);
        publisher.subscribe("client-1", None).await;
        assert_eq!(publisher.subscriber_count().await, 1);

        publisher.unsubscribe("client-1").await;
        assert_eq!(publisher.subscriber_count().await, 0);
    }

    #[tokio::test]
    async fn test_scoped_subscription_releases_bookkeeping_on_drop() {
        let publisher = EventPublisher::new(16);
        let mut subscription = publisher.subscribe_scoped("ws-conn-1", None);
        assert_eq!(publisher.subscriber_count().await, 1);

        publisher
            .publish(
                EventType::DownloadStart,
                DownloadEvent::download_start("gid-1"),
            )
            .expect("scoped subscription must receive broadcast events");
        let (event_type, event) = subscription.recv().await.unwrap();
        assert_eq!(event_type, EventType::DownloadStart);
        assert_eq!(event.gid(), "gid-1");

        drop(subscription);
        assert_eq!(publisher.subscriber_count().await, 0);
    }

    #[tokio::test]
    async fn test_publisher_multiple_subscribers() {
        let publisher = EventPublisher::new(16);
        let _rx1 = publisher.subscribe("c1", None).await;
        let _rx2 = publisher.subscribe("c2", None).await;
        let _rx3 = publisher.subscribe("c3", None).await;
        assert_eq!(publisher.subscriber_count().await, 3);
    }

    // =========================================================================
    // WsSession Tests
    // =========================================================================

    #[test]
    fn test_ws_session() {
        let (tx, rx) = broadcast::channel::<(EventType, DownloadEvent)>(4);
        let session = WsSession::new("session-abc", rx);
        assert_eq!(session.id(), "session-abc");
        drop(tx);
    }

    #[test]
    fn test_default_publisher() {
        use futures::future::FutureExt;
        let p = EventPublisher::default();
        assert_eq!(p.subscriber_count().now_or_never().unwrap(), 0);
    }

    // =========================================================================
    // NotificationBatcher Tests (G7)
    // =========================================================================

    #[test]
    fn test_batcher_default() {
        let batcher = NotificationBatcher::default();
        assert_eq!(batcher.pending_count(), 0);
        assert_eq!(batcher.stats(), (0, 0));
    }

    #[test]
    fn test_batcher_builder() {
        let batcher = NotificationBatcher::new()
            .with_max_batch_size(50)
            .with_flush_interval_ms(1000);
        assert_eq!(batcher.pending_count(), 0);
    }

    /// Test: push 2 onComplete for same GID → only 1 sent after flush
    #[test]
    fn test_dedup_same_event_replaces_old() {
        let mut batcher = NotificationBatcher::new().with_max_batch_size(100);

        let event1 = DownloadEvent::download_complete("gid-same-001");
        let event2 = DownloadEvent::download_complete("gid-same-001");

        batcher.push(event1);
        batcher.push(event2); // Should deduplicate: same GID + same event type

        // After dedup, only 1 pending (the latest replaces the old one)
        assert_eq!(
            batcher.pending_count(),
            1,
            "Dedup should keep only latest event"
        );
        let (sent, deduped) = batcher.stats();
        assert_eq!(sent, 0, "No events sent yet (not flushed)");
        assert_eq!(deduped, 1, "One event should have been deduplicated");

        // Flush should return exactly 1 event
        let _batch = batcher.maybe_flush(); // force flush by checking
        // Use flush via maybe_flush with elapsed time — but since we just pushed,
        // we need to verify the pending count is correct.
        // The maybe_flush won't trigger immediately if interval hasn't passed,
        // so let's just check pending count and stats.
        assert_eq!(batcher.pending_count(), 1);
    }

    /// Test: onComplete + onError for same GID → both kept (different event types)
    #[test]
    fn test_different_events_not_deduped() {
        let mut batcher = NotificationBatcher::new().with_max_batch_size(100);

        let complete = DownloadEvent::download_complete("gid-mixed-001");
        let error = DownloadEvent::download_error("gid-mixed-001");

        batcher.push(complete);
        batcher.push(error); // Different event type → NOT deduplicated

        assert_eq!(
            batcher.pending_count(),
            2,
            "Different event types should both be kept"
        );
        let (_, deduped) = batcher.stats();
        assert_eq!(deduped, 0, "No deduplication for different event types");
    }

    /// Test: 21st push triggers auto-flush of 20 when max_batch_size=20
    #[test]
    fn test_batch_size_limit_triggers_flush() {
        let mut batcher = NotificationBatcher::new()
            .with_max_batch_size(20)
            .with_flush_interval_ms(60_000);

        // Push 19 events — no flush yet
        for i in 0..19 {
            let flushed = batcher.push(DownloadEvent::download_start(format!("gid-{}", i)));
            assert!(!flushed, "Push {} should not trigger flush yet", i);
        }
        assert_eq!(batcher.pending_count(), 19);

        // Push 20th event — hits limit, should auto-flush
        let flushed = batcher.push(DownloadEvent::download_start("gid-19"));
        assert!(flushed, "20th push should trigger auto-flush");

        // After auto-flush, pending should be empty (all 20 were drained)
        assert_eq!(
            batcher.pending_count(),
            0,
            "Pending should be empty after auto-flush"
        );
        let (sent, _) = batcher.stats();
        assert_eq!(sent, 20, "Should have sent 20 notifications");
    }

    /// Test: timer-based flush emits accumulated events after interval
    #[test]
    fn test_timer_flush_emits_accumulated() {
        let mut batcher = NotificationBatcher::new()
            .with_max_batch_size(100)
            .with_flush_interval_ms(50);

        for i in 0..5 {
            batcher.push(DownloadEvent::download_complete(format!("gid-timer-{}", i)));
        }
        assert_eq!(batcher.pending_count(), 5);

        // Wait well beyond the flush interval to handle CI jitter
        std::thread::sleep(std::time::Duration::from_millis(200));

        let batch = batcher.maybe_flush();
        assert!(
            batch.is_some(),
            "Timer flush should emit accumulated events"
        );
        let batch = batch.unwrap();
        assert_eq!(batch.len(), 5, "Should emit all 5 pending events");

        let (sent, _) = batcher.stats();
        assert_eq!(sent, 5, "Total sent should be 5");
        assert_eq!(
            batcher.pending_count(),
            0,
            "Pending should be empty after flush"
        );
    }

    /// Test: maybe_flush returns None when no time has passed
    #[test]
    fn test_maybe_flush_noop_when_fresh() {
        let mut batcher = NotificationBatcher::new()
            .with_max_batch_size(100)
            .with_flush_interval_ms(60_000); // Long interval

        batcher.push(DownloadEvent::download_start("gid-fresh"));

        // Immediately after push, before interval elapses
        let result = batcher.maybe_flush();
        assert!(result.is_none(), "Should not flush before interval elapses");
        assert_eq!(batcher.pending_count(), 1);
    }

    /// Test: maybe_flush returns None when pending is empty
    #[test]
    fn test_maybe_flush_noop_when_empty() {
        let mut batcher = NotificationBatcher::new().with_flush_interval_ms(0);

        // Even with 0 interval, empty pending should return None
        let result = batcher.maybe_flush();
        assert!(result.is_none(), "Should not flush when no pending events");
    }

    /// Test: cross-GID events are never deduplicated
    #[test]
    fn test_different_gids_not_deduped() {
        let mut batcher = NotificationBatcher::new().with_max_batch_size(100);

        batcher.push(DownloadEvent::download_complete("gid-a"));
        batcher.push(DownloadEvent::download_complete("gid-b"));
        batcher.push(DownloadEvent::download_complete("gid-c"));

        assert_eq!(
            batcher.pending_count(),
            3,
            "Different GIDs should all be kept"
        );
        let (_, deduped) = batcher.stats();
        assert_eq!(deduped, 0, "No dedup across different GIDs");
    }
}