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;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DownloadEvent {
Start,
Complete,
Error,
Pause,
Stop,
BtComplete,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetadataResolvedEvent {
pub metadata_gid: GroupId,
pub download_gids: Vec<GroupId>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DownloadNotification {
Lifecycle { event: DownloadEvent, gid: String },
MetadataResolved(MetadataResolvedEvent),
}
pub struct DownloadEventStream {
receiver: broadcast::Receiver<DownloadNotification>,
}
impl DownloadEventStream {
pub async fn recv(&mut self) -> Result<DownloadNotification, broadcast::error::RecvError> {
self.receiver.recv().await
}
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(_) => {}
}
}
}
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 {
pub fn new(metadata_gid: GroupId, download_gids: Vec<GroupId>) -> Self {
Self {
metadata_gid,
download_gids,
}
}
}
impl DownloadEvent {
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",
}
}
pub fn is_once_per_download(&self) -> bool {
matches!(self, Self::Complete | Self::Error | Self::BtComplete)
}
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Stop | Self::Complete | Self::Error)
}
}
pub trait DownloadEventListener: Send + Sync {
fn on_download_event(&self, event: DownloadEvent, gid: &str);
fn on_download_event_scoped(&self, event: DownloadEvent, gid: &str, _scope_id: u64) {
self.on_download_event(event, gid);
}
fn on_metadata_resolved(&self, _event: &MetadataResolvedEvent) {}
fn is_alive(&self) -> bool {
true
}
}
pub type DownloadEventListenerId = u64;
const DEDUP_GENERATION_CAPACITY: usize = 4096;
const METADATA_HISTORY_CAPACITY: usize = 1024;
#[derive(Default)]
struct OneShotLedger {
current: HashSet<(Option<u64>, String, DownloadEvent)>,
previous: HashSet<(Option<u64>, String, DownloadEvent)>,
}
impl OneShotLedger {
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
}
}
pub struct DownloadEventHooks {
global_hooks: Arc<std::sync::RwLock<GlobalHookMap>>,
listeners: std::sync::RwLock<Vec<(DownloadEventListenerId, Arc<dyn DownloadEventListener>)>>,
next_listener_id: AtomicU64,
one_shot: std::sync::RwLock<OneShotLedger>,
notifications: broadcast::Sender<DownloadNotification>,
metadata_history: std::sync::RwLock<VecDeque<MetadataResolvedEvent>>,
}
type GlobalHookMap = Vec<(DownloadEvent, String)>;
static SHARED_HOOKS: OnceLock<Arc<DownloadEventHooks>> = OnceLock::new();
impl DownloadEventHooks {
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()),
}
}
pub fn shared() -> &'static Arc<DownloadEventHooks> {
SHARED_HOOKS.get_or_init(|| Arc::new(DownloadEventHooks::new()))
}
pub fn add_listener(&self, listener: Arc<dyn DownloadEventListener>) {
let _ = self.add_listener_with_id(listener);
}
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
}
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
}
pub fn listener_count(&self) -> usize {
self.listeners.recover().len()
}
pub fn subscribe(&self) -> DownloadEventStream {
DownloadEventStream {
receiver: self.notifications.subscribe(),
}
}
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()
}
pub fn notify_listeners(&self, event: DownloadEvent, gid: &str) {
self.notify_listeners_in_scope(event, gid, None);
}
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>) {
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()
};
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);
}
}
}
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);
}
}
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"
);
}
pub fn remove_global_hook(&self, event: DownloadEvent) {
let mut hooks = self.global_hooks.recover_mut();
hooks.retain(|(e, _)| *e != event);
}
pub fn fire_event(&self, event: DownloadEvent, group: &RequestGroup) {
let gid_hex = group.gid().to_hex_string();
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"
);
}
}
self.notify_listeners_scoped(event, &gid_hex, group.event_scope_id());
}
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>,
) {
if !command.is_empty() {
self.spawn_hook(command, gid_hex, num_files, first_file_path, event);
}
self.notify_listeners_in_scope(event, gid_hex, scope_id);
}
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())
}
}
fn resolve_hook_command(&self, event: DownloadEvent, group: &RequestGroup) -> Option<String> {
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());
}
let hooks = self.global_hooks.recover();
for (e, cmd) in hooks.iter() {
if *e == event && !cmd.is_empty() {
return Some(cmd.clone());
}
}
None
}
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"
);
let num_files_str = num_files.to_string();
#[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); 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");
}
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()
}
}
#[derive(Debug, Clone)]
pub struct DownloadEventContext {
pub gid_hex: String,
pub num_files: usize,
pub first_file_path: String,
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 {
pub fn from_group(group: &RequestGroup) -> Self {
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(),
}
}
}
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);
}
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());
}
#[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
);
}
#[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());
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());
hooks.notify_listeners(DownloadEvent::Complete, "000000000000000a");
hooks.notify_listeners(DownloadEvent::Complete, "000000000000000a");
hooks.notify_listeners(DownloadEvent::Complete, "000000000000000b");
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());
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();
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)));
}
assert!(ledger.current.len() <= DEDUP_GENERATION_CAPACITY);
assert!(ledger.previous.len() <= DEDUP_GENERATION_CAPACITY);
assert!(!ledger.claim((
None,
format!("{:016x}", DEDUP_GENERATION_CAPACITY + 9),
DownloadEvent::Complete
)));
}
}