use std::collections::HashSet;
use std::sync::{Arc, OnceLock};
use tracing::{debug, info, warn};
use crate::request::request_group::RequestGroup;
use crate::util::rwlock_ext::RwLockRecover;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DownloadEvent {
Start,
Complete,
Error,
Pause,
Stop,
BtComplete,
}
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 trait DownloadEventListener: Send + Sync {
fn on_download_event(&self, event: DownloadEvent, gid: &str);
}
const DEDUP_GENERATION_CAPACITY: usize = 4096;
#[derive(Default)]
struct OneShotLedger {
current: HashSet<(String, DownloadEvent)>,
previous: HashSet<(String, DownloadEvent)>,
}
impl OneShotLedger {
fn claim(&mut self, key: (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<Arc<dyn DownloadEventListener>>>,
one_shot: std::sync::RwLock<OneShotLedger>,
}
type GlobalHookMap = Vec<(DownloadEvent, String)>;
static SHARED_HOOKS: OnceLock<Arc<DownloadEventHooks>> = OnceLock::new();
impl DownloadEventHooks {
pub fn new() -> Self {
Self {
global_hooks: Arc::new(std::sync::RwLock::new(Vec::new())),
listeners: std::sync::RwLock::new(Vec::new()),
one_shot: std::sync::RwLock::new(OneShotLedger::default()),
}
}
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 mut listeners = self.listeners.recover_mut();
listeners.push(listener);
debug!(
count = listeners.len(),
"Registered download event listener"
);
}
pub fn listener_count(&self) -> usize {
self.listeners.recover().len()
}
pub fn notify_listeners(&self, event: DownloadEvent, gid: &str) {
let listeners: Vec<Arc<dyn DownloadEventListener>> = {
let guard = self.listeners.recover();
if guard.is_empty() {
return;
}
guard.clone()
};
if event.is_once_per_download()
&& !self.one_shot.recover_mut().claim((gid.to_string(), event))
{
debug!(
event = event.name(),
gid, "Suppressed duplicate one-shot download event"
);
return;
}
debug!(
event = event.name(),
gid,
listeners = listeners.len(),
"Notifying download event listeners"
);
for listener in listeners {
listener.on_download_event(event, gid);
}
}
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(event, &gid_hex);
}
pub fn fire_event_with_params(
&self,
event: DownloadEvent,
gid_hex: &str,
num_files: usize,
first_file_path: &str,
command: &str,
) {
if !command.is_empty() {
self.spawn_hook(command, gid_hex, num_files, first_file_path, event);
}
self.notify_listeners(event, gid_hex);
}
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)>>,
}
impl RecordingListener {
fn events(&self) -> Vec<(DownloadEvent, String)> {
self.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()));
}
}
#[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_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_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_one_shot_ledger_rotates_and_stays_bounded() {
let mut ledger = OneShotLedger::default();
for i in 0..(DEDUP_GENERATION_CAPACITY + 10) {
assert!(ledger.claim((format!("{:016x}", i), DownloadEvent::Complete)));
}
assert!(ledger.current.len() <= DEDUP_GENERATION_CAPACITY);
assert!(ledger.previous.len() <= DEDUP_GENERATION_CAPACITY);
assert!(!ledger.claim((
format!("{:016x}", DEDUP_GENERATION_CAPACITY + 9),
DownloadEvent::Complete
)));
}
}