async_callback_manager/
task.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use crate::{DynBackendTask, DynFallibleFuture, KillHandle, SenderId, TaskId};
use futures::{stream::FuturesUnordered, StreamExt};
use std::any::TypeId;
use tokio::sync::{mpsc, oneshot};

pub(crate) struct TaskList<Cstrnt> {
    pub inner: Vec<Task<Cstrnt>>,
}

// User visible struct for introspection.
#[derive(Debug, Clone)]
pub struct ResponseInformation {
    pub type_id: TypeId,
    pub type_name: &'static str,
    pub sender_id: SenderId,
    pub task_id: TaskId,
    pub task_is_now_finished: bool,
}

// User visible struct for introspection.
#[derive(Debug, Clone)]
pub struct TaskInformation<'a, Cstrnt> {
    pub type_id: TypeId,
    pub type_name: &'static str,
    pub sender_id: SenderId,
    pub constraint: &'a Option<Constraint<Cstrnt>>,
}

pub(crate) struct TaskFromFrontend<Bkend, Cstrnt> {
    pub(crate) type_id: TypeId,
    pub(crate) type_name: &'static str,
    pub(crate) metadata: Vec<Cstrnt>,
    pub(crate) task: DynBackendTask<Bkend>,
    pub(crate) receiver: TaskReceiver,
    pub(crate) sender_id: SenderId,
    pub(crate) constraint: Option<Constraint<Cstrnt>>,
    pub(crate) kill_handle: KillHandle,
}

pub(crate) struct Task<Cstrnt> {
    pub(crate) type_id: TypeId,
    pub(crate) type_name: &'static str,
    pub(crate) receiver: TaskReceiver,
    pub(crate) sender_id: SenderId,
    pub(crate) task_id: TaskId,
    pub(crate) kill_handle: KillHandle,
    pub(crate) metadata: Vec<Cstrnt>,
}

#[derive(Eq, PartialEq, Debug)]
pub struct Constraint<Cstrnt> {
    pub(crate) constraint_type: ConstraitType<Cstrnt>,
}

#[derive(Eq, PartialEq, Debug)]
pub enum ConstraitType<Cstrnt> {
    BlockSameType,
    KillSameType,
    BlockMatchingMetatdata(Cstrnt),
}

pub(crate) enum TaskReceiver {
    Future(oneshot::Receiver<DynFallibleFuture>),
    Stream(mpsc::Receiver<DynFallibleFuture>),
}
impl From<oneshot::Receiver<DynFallibleFuture>> for TaskReceiver {
    fn from(value: oneshot::Receiver<DynFallibleFuture>) -> Self {
        Self::Future(value)
    }
}
impl From<mpsc::Receiver<DynFallibleFuture>> for TaskReceiver {
    fn from(value: mpsc::Receiver<DynFallibleFuture>) -> Self {
        Self::Stream(value)
    }
}

impl<Cstrnt: PartialEq> TaskList<Cstrnt> {
    pub(crate) fn new() -> Self {
        Self { inner: vec![] }
    }
    /// Returns Some(ResponseInformation, Option<DynFallibleFuture>) if a task
    /// existed in the list, and it was processed. Returns None, if no tasks
    /// were in the list. The DynFallibleFuture represents a future that
    /// forwards messages from the manager back to the sender.
    pub(crate) async fn process_next_response(
        &mut self,
    ) -> Option<(ResponseInformation, Option<DynFallibleFuture>)> {
        let task_completed = self
            .inner
            .iter_mut()
            .enumerate()
            .map(|(idx, task)| async move {
                match task.receiver {
                    TaskReceiver::Future(ref mut receiver) => {
                        if let Ok(forwarder) = receiver.await {
                            return (
                                Some(idx),
                                Some(forwarder),
                                task.type_id,
                                task.type_name,
                                task.sender_id,
                                task.task_id,
                            );
                        }
                        (
                            Some(idx),
                            None,
                            task.type_id,
                            task.type_name,
                            task.sender_id,
                            task.task_id,
                        )
                    }
                    TaskReceiver::Stream(ref mut receiver) => {
                        if let Some(forwarder) = receiver.recv().await {
                            return (
                                None,
                                Some(forwarder),
                                task.type_id,
                                task.type_name,
                                task.sender_id,
                                task.task_id,
                            );
                        }
                        (
                            Some(idx),
                            None,
                            task.type_id,
                            task.type_name,
                            task.sender_id,
                            task.task_id,
                        )
                    }
                }
            })
            .collect::<FuturesUnordered<_>>()
            .next()
            .await;
        let (maybe_completed_id, maybe_forwarder, type_id, type_name, sender_id, task_id) =
            task_completed?;
        if let Some(task_completed) = maybe_completed_id {
            // Safe - this value is in range as produced from enumerate on original list.
            self.inner.swap_remove(task_completed);
        }
        Some((
            ResponseInformation {
                type_id,
                type_name,
                sender_id,
                task_id,
                task_is_now_finished: maybe_completed_id.is_some(),
            },
            maybe_forwarder,
        ))
    }
    pub(crate) fn push(&mut self, task: Task<Cstrnt>) {
        self.inner.push(task)
    }
    // TODO: Tests
    pub(crate) fn handle_constraint(
        &mut self,
        constraint: Constraint<Cstrnt>,
        type_id: TypeId,
        sender_id: SenderId,
    ) {
        // Assuming here that kill implies block also.
        let task_doesnt_match_constraint =
            |task: &Task<_>| (task.type_id != type_id) || (task.sender_id != sender_id);
        let task_doesnt_match_metadata =
            |task: &Task<_>, constraint| !task.metadata.contains(constraint);
        match constraint.constraint_type {
            ConstraitType::BlockMatchingMetatdata(metadata) => self
                .inner
                .retain(|task| task_doesnt_match_metadata(task, &metadata)),
            ConstraitType::BlockSameType => {
                self.inner.retain(task_doesnt_match_constraint);
            }
            ConstraitType::KillSameType => self.inner.retain_mut(|task| {
                if !task_doesnt_match_constraint(task) {
                    task.kill_handle.kill().expect("Task should still be alive");
                    return false;
                }
                true
            }),
        }
    }
}

impl<Bkend, Cstrnt> TaskFromFrontend<Bkend, Cstrnt> {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        type_id: TypeId,
        type_name: &'static str,
        metadata: Vec<Cstrnt>,
        task: impl FnOnce(&Bkend) -> DynFallibleFuture + 'static,
        receiver: impl Into<TaskReceiver>,
        sender_id: SenderId,
        constraint: Option<Constraint<Cstrnt>>,
        kill_handle: KillHandle,
    ) -> Self {
        Self {
            type_id,
            type_name,
            metadata,
            task: Box::new(task),
            receiver: receiver.into(),
            sender_id,
            constraint,
            kill_handle,
        }
    }
    pub(crate) fn get_information(&self) -> TaskInformation<'_, Cstrnt> {
        TaskInformation {
            type_id: self.type_id,
            type_name: self.type_name,
            sender_id: self.sender_id,
            constraint: &self.constraint,
        }
    }
}

impl<Cstrnt> Task<Cstrnt> {
    pub(crate) fn new(
        type_id: TypeId,
        type_name: &'static str,
        metadata: Vec<Cstrnt>,
        receiver: TaskReceiver,
        sender_id: SenderId,
        task_id: TaskId,
        kill_handle: KillHandle,
    ) -> Self {
        Self {
            type_id,
            type_name,
            receiver,
            sender_id,
            kill_handle,
            task_id,
            metadata,
        }
    }
}

impl<Cstrnt> Constraint<Cstrnt> {
    pub fn new_block_same_type() -> Self {
        Self {
            constraint_type: ConstraitType::BlockSameType,
        }
    }
    pub fn new_kill_same_type() -> Self {
        Self {
            constraint_type: ConstraitType::KillSameType,
        }
    }
    pub fn new_block_matching_metadata(metadata: Cstrnt) -> Self {
        Self {
            constraint_type: ConstraitType::BlockMatchingMetatdata(metadata),
        }
    }
}