-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.rs
More file actions
280 lines (238 loc) · 8.31 KB
/
executor.rs
File metadata and controls
280 lines (238 loc) · 8.31 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use core::fmt;
use std::{collections::HashMap, panic};
use futures::{future::select_all, FutureExt};
use tokio::sync::{mpsc, watch};
use vec_collections::{AbstractVecMap, VecMap};
use crate::{
node_graph::{InputId, NodeOutput},
pipeline::{
execution::{ConnectionHandle, InvalidationCause, InvalidationNotifier},
PipelineExecutor,
},
view::{views::DynDataView, DataViewsState, ViewId},
};
use super::DynDataViewTask;
// MARK: ViewsExecutor
/// Execution system for data view tasks, described by [super::DataViewTask].
///
/// Analog to the pipelines execution system. Tasks in this system can connect
/// to tasks in the pipelines execution system.
pub struct ViewsExecutor {
runners: HashMap<ViewId, ViewTaskRunner>,
}
impl ViewsExecutor {
pub fn new() -> Self {
Self {
runners: HashMap::new(),
}
}
pub fn update(
&mut self,
views_state: &mut DataViewsState,
pipeline_executor: &PipelineExecutor,
) {
// Deleted views
self.runners
.retain(|id, _| views_state.views.contains_key(id));
// New views
for (view_id, view) in &mut views_state.views {
if !self.runners.contains_key(view_id) {
self.runners
.insert(*view_id, ViewTaskRunner::from_view(view.as_mut()));
}
}
// Connections
for (view_id, runner) in &mut self.runners {
let view = views_state
.views
.get(view_id)
.expect("Views should be synced");
runner.sync_connections(view.as_ref(), pipeline_executor);
runner.sync_view(view.as_ref());
}
}
}
impl fmt::Debug for ViewsExecutor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ViewsExecutor")
.field("runners", &self.runners.keys().collect::<Vec<_>>())
.finish()
}
}
// MARK: ViewTaskRunner
struct ViewTaskRunner {
inputs: VecMap<[(InputId, NodeOutput); 4]>,
control_tx: mpsc::UnboundedSender<ControlMsg>,
sync_tx: watch::Sender<Box<dyn DynDataView>>,
}
impl ViewTaskRunner {
pub fn from_view(view: &mut dyn DynDataView) -> Self {
let task = view.create_view_task();
let (control_tx, control_rx) = mpsc::unbounded_channel();
let (sync_tx, sync_rx) = watch::channel(view.clone_boxed());
tokio::spawn(
RunningViewTask {
task,
control_rx,
sync_rx,
input_connections: Vec::new(),
error_on_last_run: false,
}
.run(),
);
Self {
inputs: VecMap::empty(),
control_tx,
sync_tx,
}
}
pub fn sync_view(&mut self, view: &dyn DynDataView) {
self.sync_tx.send_if_modified(|v| {
if v.changed(view) {
*v = view.clone_boxed();
true
} else {
false
}
});
}
pub fn sync_connections(&mut self, view: &dyn DynDataView, pipeline: &PipelineExecutor) {
let inputs = view.inputs();
for (input_id, incoming) in inputs {
let existing = self
.inputs
.iter()
.find(|(id, _)| *id == input_id)
.map(|(_, o)| *o);
match (incoming, existing) {
(i, e) if i == e => {
// Do nothing when equal
}
(Some(incoming), _) => {
self.connect_input(input_id, incoming, pipeline);
}
(None, _) => {
self.disconnect_input(input_id);
}
}
}
}
pub fn disconnect_input(&mut self, input_id: InputId) {
self.control_tx
.send(ControlMsg::Disconnect(input_id))
.expect("Task should be running");
self.inputs.retain(|(id, _)| *id != input_id);
}
pub fn connect_input(
&mut self,
input_id: InputId,
output: NodeOutput,
pipeline: &PipelineExecutor,
) {
// Find handle for output
let Some(connection) = pipeline.get_output(output.node_id, output.output_id) else {
eprintln!(
"Failed to find connection for output with id {:?}",
output.output_id
);
return;
};
// Send connect message to task
self.control_tx
.send(ControlMsg::Connect(input_id, connection.clone()))
.expect("Task should be running");
// Update input record
self.inputs.insert(input_id, output);
}
}
// MARK: RunningViewTask
struct RunningViewTask {
task: Box<dyn DynDataViewTask>,
control_rx: mpsc::UnboundedReceiver<ControlMsg>,
sync_rx: watch::Receiver<Box<dyn DynDataView>>,
input_connections: Vec<(InputId, InvalidationNotifier)>,
error_on_last_run: bool,
}
impl RunningViewTask {
pub async fn run(mut self) {
loop {
tokio::select! {
biased;
msg = self.control_rx.recv() => {
match msg {
Some(ControlMsg::Connect(input_id, mut connection)) => {
connection.reset_connection();
self.task.connect(input_id, &mut connection);
if connection.did_connect() {
self.input_connections.push((input_id, connection.get_invalidation_notifier()));
self.invalidate(InvalidationCause::Connected(input_id));
}
}
Some(ControlMsg::Disconnect(input_id)) => {
self.task.disconnect(input_id);
self.input_connections.retain(|(id, _)| *id != input_id);
self.invalidate(InvalidationCause::Disconnected(input_id));
}
None => break,
};
}
_ = self.sync_rx.changed() => {
self.task.sync_view(self.sync_rx.borrow().as_ref());
self.invalidate(InvalidationCause::Synced);
}
input_id = Self::on_invalidation(&mut self.input_connections) => {
self.invalidate(InvalidationCause::InputInvalidated(input_id));
}
is_error = Self::run_task(self.error_on_last_run, self.task.as_mut()) => {
self.error_on_last_run = is_error;
}
}
}
}
async fn run_task(error_on_last_run: bool, task: &mut dyn DynDataViewTask) -> bool {
if error_on_last_run {
let () = futures::future::pending().await;
}
let result = panic::AssertUnwindSafe(task.run()).catch_unwind().await;
let is_error = !matches!(result, Ok(Ok(_)));
match result {
Ok(Ok(_)) => {}
Ok(Err(e)) => eprintln!("Task failed: {:?}", e),
Err(e) => eprintln!(
"Task panicked: {}",
if let Some(msg) = e.downcast_ref::<&'static str>() {
msg.to_string()
} else if let Some(msg) = e.downcast_ref::<String>() {
msg.clone()
} else {
format!("?{:?}", e)
}
),
}
is_error
}
fn invalidate(&mut self, cause: InvalidationCause) {
self.task.invalidate(cause);
self.error_on_last_run = false;
}
async fn on_invalidation(notifiers: &mut Vec<(InputId, InvalidationNotifier)>) -> InputId {
// Cannot borrow self as mutable again at call site
if !notifiers.is_empty() {
let (is_channel_open, index, ..) =
select_all(notifiers.iter_mut().map(|(_, n)| n.on_invalidate())).await;
let id = notifiers[index].0;
if !is_channel_open {
// Partner dropped, already disconnected
notifiers.remove(index);
}
id
} else {
futures::future::pending().await
}
}
}
// MARK: ControlMsg
enum ControlMsg {
Connect(InputId, ConnectionHandle),
Disconnect(InputId),
}