use std::collections::{HashSet, VecDeque};
use std::sync::{Arc, OnceLock, atomic::AtomicU64};
use tokio::sync::broadcast;
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();
mod bus;
#[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;