1
use std::{any::Any, collections::HashMap, fmt::Debug, sync::Arc};
2

            
3
use flume::{Receiver, Sender};
4
use tokio::sync::oneshot;
5

            
6
use crate::jobs::{
7
    manager::{ManagedJob, Manager},
8
    task::{Handle, Id},
9
    traits::Executable,
10
    Job, Keyed,
11
};
12

            
13
pub struct Jobs<Key> {
14
    last_task_id: u64,
15
    result_senders: HashMap<Id, Vec<Box<dyn AnySender>>>,
16
    keyed_jobs: 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_jobs", &self.keyed_jobs)
30
            .field("queuer", &self.queuer)
31
            .field("queue", &self.queue)
32
            .finish()
33
    }
34
}
35

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

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

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

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

            
75
172119
        self.create_new_task_handle(id, manager)
76
172119
    }
77

            
78
181127
    pub fn create_new_task_handle<T: Send + Sync + 'static, E: Send + Sync + 'static>(
79
181127
        &mut self,
80
181127
        id: Id,
81
181127
        manager: Manager<Key>,
82
181127
    ) -> Handle<T, E, Key> {
83
181127
        let (sender, receiver) = oneshot::channel();
84
181127
        let senders = self.result_senders.entry(id).or_insert_with(Vec::default);
85
181127
        senders.push(Box::new(Some(sender)));
86
181127

            
87
181127
        Handle {
88
181127
            id,
89
181127
            manager,
90
181127
            receiver,
91
181127
        }
92
181127
    }
93

            
94
128962
    pub fn lookup_or_enqueue<J: Keyed<Key>>(
95
128962
        &mut self,
96
128962
        job: J,
97
128962
        manager: Manager<Key>,
98
128962
    ) -> Handle<<J as Job>::Output, <J as Job>::Error, Key> {
99
128962
        let key = job.key();
100
128962
        if let Some(&id) = self.keyed_jobs.get(&key) {
101
9055
            self.create_new_task_handle(id, manager)
102
        } else {
103
119907
            let handle = self.enqueue(job, Some(key.clone()), manager);
104
119907
            self.keyed_jobs.insert(key, handle.id);
105
119907
            handle
106
        }
107
128962
    }
108

            
109
    pub fn job_completed<T: Clone + Send + Sync + 'static, E: Send + Sync + 'static>(
110
        &mut self,
111
        id: Id,
112
        key: Option<&Key>,
113
        result: Result<T, E>,
114
    ) {
115
171907
        if let Some(key) = key {
116
119743
            self.keyed_jobs.remove(key);
117
156834
        }
118

            
119
171907
        if let Some(senders) = self.result_senders.remove(&id) {
120
171907
            let result = result.map_err(Arc::new);
121
352822
            for mut sender_handle in senders {
122
180939
                let sender = sender_handle
123
180939
                    .as_any_mut()
124
180939
                    .downcast_mut::<Option<oneshot::Sender<Result<T, Arc<E>>>>>()
125
180939
                    .unwrap();
126
180939
                if let Some(sender) = sender.take() {
127
180915
                    drop(sender.send(result.clone()));
128
180915
                }
129
            }
130
        }
131
171883
    }
132
}
133

            
134
pub trait AnySender: Any + Send + Sync {
135
    fn as_any_mut(&mut self) -> &'_ mut dyn Any;
136
}
137

            
138
impl<T> AnySender for Option<oneshot::Sender<T>>
139
where
140
    T: Send + Sync + 'static,
141
{
142
180915
    fn as_any_mut(&mut self) -> &'_ mut dyn Any {
143
180915
        self
144
180915
    }
145
}