1
use std::any::Any;
2
use std::collections::HashMap;
3
use std::fmt::Debug;
4
use std::sync::Arc;
5

            
6
use flume::{Receiver, Sender};
7

            
8
use crate::tasks::handle::{Handle, Id};
9
use crate::tasks::manager::{ManagedJob, Manager};
10
use crate::tasks::traits::Executable;
11
use crate::tasks::{Job, Keyed};
12

            
13
pub struct Jobs<Key> {
14
    last_task_id: u64,
15
    result_senders: HashMap<Id, Vec<Box<dyn AnySender>>>,
16
    keyed: HashMap<Key, Id>,
17
    queuer: Sender<Box<dyn Executable>>,
18
    queue: Receiver<Box<dyn Executable>>,
19
}
20

            
21
impl<Key> Debug for Jobs<Key>
22
where
23
    Key: Debug,
24
{
25
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26
        f.debug_struct("Jobs")
27
            .field("last_task_id", &self.last_task_id)
28
            .field("result_senders", &self.result_senders.len())
29
            .field("keyed", &self.keyed)
30
            .field("queuer", &self.queuer)
31
            .field("queue", &self.queue)
32
            .finish()
33
    }
34
}
35

            
36
impl<Key> Default for Jobs<Key> {
37
5199
    fn default() -> Self {
38
5199
        let (queuer, queue) = flume::unbounded();
39
5199

            
40
5199
        Self {
41
5199
            last_task_id: 0,
42
5199
            result_senders: HashMap::new(),
43
5199
            keyed: HashMap::new(),
44
5199
            queuer,
45
5199
            queue,
46
5199
        }
47
5199
    }
48
}
49

            
50
impl<Key> Jobs<Key>
51
where
52
    Key: Clone + std::hash::Hash + Eq + Send + Sync + Debug + 'static,
53
{
54
41578
    pub fn queue(&self) -> Receiver<Box<dyn Executable>> {
55
41578
        self.queue.clone()
56
41578
    }
57

            
58
255640
    pub fn enqueue<J: Job + 'static>(
59
255640
        &mut self,
60
255640
        job: J,
61
255640
        key: Option<Key>,
62
255640
        manager: Manager<Key>,
63
255640
    ) -> Handle<J::Output, J::Error> {
64
255640
        self.last_task_id = self.last_task_id.wrapping_add(1);
65
255640
        let id = Id(self.last_task_id);
66
255640
        self.queuer
67
255640
            .send(Box::new(ManagedJob {
68
255640
                id,
69
255640
                job,
70
255640
                manager,
71
255640
                key,
72
255640
            }))
73
255640
            .unwrap();
74
255640

            
75
255640
        self.create_new_task_handle(id)
76
255640
    }
77

            
78
273581
    pub fn create_new_task_handle<T: Send + Sync + 'static, E: Send + Sync + 'static>(
79
273581
        &mut self,
80
273581
        id: Id,
81
273581
    ) -> Handle<T, E> {
82
273581
        let (sender, receiver) = flume::bounded(1);
83
273581
        let senders = self.result_senders.entry(id).or_default();
84
273581
        senders.push(Box::new(sender));
85
273581

            
86
273581
        Handle { id, receiver }
87
273581
    }
88

            
89
273580
    pub fn lookup_or_enqueue<J: Keyed<Key>>(
90
273580
        &mut self,
91
273580
        job: J,
92
273580
        manager: Manager<Key>,
93
273580
    ) -> Handle<<J as Job>::Output, <J as Job>::Error> {
94
273580
        let key = job.key();
95
273580
        if let Some(&id) = self.keyed.get(&key) {
96
17941
            self.create_new_task_handle(id)
97
        } else {
98
255639
            let handle = self.enqueue(job, Some(key.clone()), manager);
99
255639
            self.keyed.insert(key, handle.id);
100
255639
            handle
101
        }
102
273580
    }
103

            
104
255640
    pub fn job_completed<T: Clone + Send + Sync + 'static, E: Send + Sync + 'static>(
105
255640
        &mut self,
106
255640
        id: Id,
107
255640
        key: Option<&Key>,
108
255640
        result: Result<T, E>,
109
255640
    ) {
110
255640
        if let Some(key) = key {
111
255639
            self.keyed.remove(key);
112
255639
        }
113

            
114
255640
        if let Some(senders) = self.result_senders.remove(&id) {
115
255640
            let result = result.map_err(Arc::new);
116
529221
            for sender_handle in senders {
117
273581
                let sender = sender_handle
118
273581
                    .as_any()
119
273581
                    .downcast_ref::<flume::Sender<Result<T, Arc<E>>>>()
120
273581
                    .unwrap();
121
273581
                drop(sender.send(result.clone()));
122
273581
            }
123
        }
124
255640
    }
125
}
126

            
127
pub trait AnySender: Any + Send + Sync {
128
    fn as_any(&self) -> &'_ dyn Any;
129
}
130

            
131
impl<T> AnySender for flume::Sender<T>
132
where
133
    T: Send + Sync + 'static,
134
{
135
273581
    fn as_any(&self) -> &'_ dyn Any {
136
273581
        self
137
273581
    }
138
}