use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;
use tokio::sync::broadcast;
#[derive(Debug, Clone)]
pub struct WsConfig {
pub ping_interval_secs: u64,
pub pong_timeout_secs: u64,
}
impl Default for WsConfig {
fn default() -> Self {
Self {
ping_interval_secs: 30,
pong_timeout_secs: 60,
}
}
}
impl WsConfig {
pub fn new(ping_interval_secs: u64, pong_timeout_secs: u64) -> Self {
Self {
ping_interval_secs,
pong_timeout_secs,
}
}
pub fn with_ping_interval(mut self, secs: u64) -> Self {
self.ping_interval_secs = secs;
self
}
pub fn with_pong_timeout(mut self, secs: u64) -> Self {
self.pong_timeout_secs = secs;
self
}
}
#[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,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadEvent {
#[serde(rename = "jsonrpc")]
version: String,
method: String,
params: Vec<serde_json::Value>,
}
impl DownloadEvent {
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,
}
}
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)
}
pub fn gid(&self) -> String {
self.params
.first()
.and_then(|p| p.get("gid"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string()
}
pub fn event_type_str(&self) -> String {
self.method.clone()
}
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)] id: String,
#[allow(dead_code)] filter: Option<Vec<EventType>>,
}
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) {
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()
}
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)
}
}
use std::collections::VecDeque;
pub struct NotificationBatcher {
max_batch_size: usize,
flush_interval_ms: u64,
pending: VecDeque<DownloadEvent>,
latest_per_gid: HashMap<String, (DownloadEvent, Instant)>,
last_flush: Instant,
total_sent: u64,
total_deduped: u64,
}
impl NotificationBatcher {
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,
}
}
pub fn with_max_batch_size(mut self, size: usize) -> Self {
self.max_batch_size = size;
self
}
pub fn with_flush_interval_ms(mut self, ms: u64) -> Self {
self.flush_interval_ms = ms;
self
}
pub fn push(&mut self, notification: DownloadEvent) -> bool {
let gid = notification.gid();
let event_type = notification.event_type_str();
let key = format!("{}:{}", gid, event_type);
if let Some(existing) = self.latest_per_gid.get_mut(&key) {
*existing = (notification, Instant::now());
self.total_deduped += 1;
tracing::debug!("Deduped notification for {}: {}", gid, event_type);
} else {
self.latest_per_gid
.insert(key.clone(), (notification.clone(), Instant::now()));
self.pending.push_back(notification);
}
if self.pending.len() >= self.max_batch_size {
self.flush_internal();
true
} else {
false
}
}
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
}
}
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)
}
pub fn stats(&self) -> (u64, u64) {
(self.total_sent, self.total_deduped)
}
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::*;
#[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());
}
#[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\""));
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");
}
#[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");
assert_eq!(
parsed["jsonrpc"], "2.0",
"jsonrpc version mismatch for {}",
expected_method
);
assert_eq!(parsed["method"], *expected_method, "method mismatch");
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
);
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
);
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
);
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"
);
}
}
}
#[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++"
);
}
#[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);
}
#[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);
}
#[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);
}
#[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]
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);
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");
let _batch = batcher.maybe_flush(); assert_eq!(batcher.pending_count(), 1);
}
#[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);
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]
fn test_batch_size_limit_triggers_flush() {
let mut batcher = NotificationBatcher::new()
.with_max_batch_size(20)
.with_flush_interval_ms(60_000);
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);
let flushed = batcher.push(DownloadEvent::download_start("gid-19"));
assert!(flushed, "20th push should trigger auto-flush");
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]
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);
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]
fn test_maybe_flush_noop_when_fresh() {
let mut batcher = NotificationBatcher::new()
.with_max_batch_size(100)
.with_flush_interval_ms(60_000);
batcher.push(DownloadEvent::download_start("gid-fresh"));
let result = batcher.maybe_flush();
assert!(result.is_none(), "Should not flush before interval elapses");
assert_eq!(batcher.pending_count(), 1);
}
#[test]
fn test_maybe_flush_noop_when_empty() {
let mut batcher = NotificationBatcher::new().with_flush_interval_ms(0);
let result = batcher.maybe_flush();
assert!(result.is_none(), "Should not flush when no pending events");
}
#[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");
}
}