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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use anyhow::{Context, Result};
#[cfg(not(target_arch = "wasm32"))]
use async_io::block_on;
#[cfg(not(target_arch = "wasm32"))]
use async_task::Task;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::future::join_all;
use futures::future::Either;
use futures::prelude::*;
use futures::FutureExt;
#[cfg(target_arch = "wasm32")]
use wasm_rs_async_executor::single_threaded;
#[cfg(target_arch = "wasm32")]
use wasm_rs_async_executor::single_threaded::block_on;
#[cfg(target_arch = "wasm32")]
type Task<T> = single_threaded::TaskHandle<T>;

use crate::runtime::config;
#[cfg(not(target_arch = "wasm32"))]
use crate::runtime::ctrl_port;
use crate::runtime::scheduler::Scheduler;
#[cfg(not(target_arch = "wasm32"))]
use crate::runtime::scheduler::SmolScheduler;
#[cfg(target_arch = "wasm32")]
use crate::runtime::scheduler::WasmScheduler;
use crate::runtime::AsyncMessage;
use crate::runtime::Block;
use crate::runtime::Flowgraph;
use crate::runtime::FlowgraphHandle;
use crate::runtime::WorkIo;

pub struct Runtime<S: Scheduler> {
    scheduler: S,
}

#[cfg(not(target_arch = "wasm32"))]
impl Runtime<SmolScheduler> {
    pub fn new() -> Runtime<SmolScheduler> {
        RuntimeBuilder {
            scheduler: SmolScheduler::default(),
        }
        .build()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for Runtime<SmolScheduler> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(target_arch = "wasm32")]
impl Runtime<WasmScheduler> {
    pub fn new() -> Runtime<WasmScheduler> {
        RuntimeBuilder {
            scheduler: WasmScheduler::default(),
        }
        .build()
    }
}

#[cfg(target_arch = "wasm32")]
impl Default for Runtime<WasmScheduler> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: Scheduler> Runtime<S> {
    pub fn custom(scheduler: S) -> RuntimeBuilder<S> {
        RuntimeBuilder { scheduler }
    }

    pub fn spawn<T: Send + 'static>(
        &self,
        future: impl Future<Output = T> + Send + 'static,
    ) -> Task<T> {
        self.scheduler.spawn(future)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn spawn_background<T: Send + 'static>(
        &self,
        future: impl Future<Output = T> + Send + 'static,
    ) {
        self.scheduler.spawn(future).detach();
    }

    pub fn spawn_blocking<T: Send + 'static>(
        &self,
        future: impl Future<Output = T> + Send + 'static,
    ) -> Task<T> {
        self.scheduler.spawn_blocking(future)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn spawn_blocking_background<T: Send + 'static>(
        &self,
        future: impl Future<Output = T> + Send + 'static,
    ) {
        self.scheduler.spawn_blocking(future).detach();
    }

    pub fn start(&self, fg: Flowgraph) -> (Task<Result<Flowgraph>>, FlowgraphHandle) {
        let queue_size = config::config().queue_size;
        let (fg_inbox, fg_inbox_rx) = channel::<AsyncMessage>(queue_size);

        let task = self.scheduler.spawn(run_flowgraph(
            fg,
            self.scheduler.clone(),
            fg_inbox.clone(),
            fg_inbox_rx,
        ));
        (task, FlowgraphHandle::new(fg_inbox))
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn run(&self, fg: Flowgraph) -> Result<Flowgraph> {
        let (handle, _) = self.start(fg);
        block_on(handle)
    }

    #[cfg(target_arch = "wasm32")]
    pub fn run(&self, fg: Flowgraph) -> Result<Flowgraph> {
        let (handle, _) = self.start(fg);
        block_on(handle).unwrap()
    }
}

pub struct RuntimeBuilder<S: Scheduler> {
    scheduler: S,
}

impl<S: Scheduler> RuntimeBuilder<S> {
    pub fn build(self) -> Runtime<S> {
        crate::runtime::init();
        Runtime {
            scheduler: self.scheduler,
        }
    }
}

async fn run_flowgraph<S: Scheduler>(
    mut fg: Flowgraph,
    scheduler: S,
    mut main_channel: Sender<AsyncMessage>,
    mut main_rx: Receiver<AsyncMessage>,
) -> Result<Flowgraph> {
    debug!("in run_flowgraph");
    let mut topology = fg.topology.take().context("flowgraph not initialized")?;
    topology.validate()?;

    let mut inboxes = scheduler.run_topology(&mut topology, &main_channel);

    debug!("connect stream io");
    // connect stream IO
    for ((src, src_port, buffer_builder), v) in topology.stream_edges.iter() {
        debug_assert!(!v.is_empty());

        let src_inbox = inboxes[*src].as_ref().unwrap().clone();
        let mut writer = buffer_builder.build(src_inbox, *src_port);

        for (dst, dst_port) in v.iter() {
            let dst_inbox = inboxes[*dst].as_ref().unwrap().clone();

            inboxes[*dst]
                .as_mut()
                .unwrap()
                .send(AsyncMessage::StreamInputInit {
                    dst_port: *dst_port,
                    reader: writer.add_reader(dst_inbox, *dst_port),
                })
                .await
                .unwrap();
        }

        inboxes[*src]
            .as_mut()
            .unwrap()
            .send(AsyncMessage::StreamOutputInit {
                src_port: *src_port,
                writer,
            })
            .await
            .unwrap();
    }

    debug!("connect message io");
    // connect message IO
    for (src, src_port, dst, dst_port) in topology.message_edges.iter() {
        let dst_box = inboxes[*dst].as_ref().unwrap().clone();
        inboxes[*src]
            .as_mut()
            .unwrap()
            .send(AsyncMessage::MessageOutputConnect {
                src_port: *src_port,
                dst_port: *dst_port,
                dst_inbox: dst_box,
            })
            .await
            .unwrap();
    }

    debug!("init blocks");
    // init blocks
    let mut active_blocks = 0u32;
    for (_, opt) in inboxes.iter_mut() {
        if let Some(ref mut chan) = opt {
            chan.send(AsyncMessage::Initialize).await.unwrap();
            active_blocks += 1;
        }
    }

    debug!("wait for blocks init");
    // wait until all blocks are initialized
    let mut i = active_blocks;
    let mut queue = Vec::new();
    loop {
        if i == 0 {
            break;
        }

        let m = main_rx.next().await.context("no msg")?;
        match m {
            AsyncMessage::Initialized => i -= 1,
            x => {
                debug!(
                    "queueing unhandled message received during initialization {:?}",
                    &x
                );
                queue.push(x);
            }
        }
    }

    debug!("running blocks");
    for (_, opt) in inboxes.iter_mut() {
        if let Some(ref mut chan) = opt {
            if chan.send(AsyncMessage::Notify).await.is_err() {
                debug!("runtime wanted to start block that already terminated");
            }
        }
    }

    for m in queue.drain(..) {
        main_channel
            .try_send(m)
            .expect("main inbox exceeded capacity during startup");
    }

    // Start Control Port
    #[cfg(not(target_arch = "wasm32"))]
    ctrl_port::start_control_port(inboxes.clone());

    // main loop
    loop {
        if active_blocks == 0 {
            break;
        }

        let m = main_rx.next().await.context("no msg")?;
        match m {
            AsyncMessage::BlockCall {
                block_id,
                port_id,
                data,
            } => {
                inboxes[block_id]
                    .as_mut()
                    .unwrap()
                    .send(AsyncMessage::Call { port_id, data })
                    .await
                    .unwrap();
            }
            AsyncMessage::BlockCallback {
                block_id,
                port_id,
                data,
                tx,
            } => {
                inboxes[block_id]
                    .as_mut()
                    .unwrap()
                    .send(AsyncMessage::Callback { port_id, data, tx })
                    .await
                    .unwrap();
            }
            AsyncMessage::BlockDone { id, block } => {
                *topology.blocks.get_mut(id).unwrap() = Some(block);

                active_blocks -= 1;
            }
            _ => warn!("main loop received unhandled message"),
        }
    }

    fg.topology = Some(topology);
    Ok(fg)
}

pub(crate) async fn run_block(
    mut block: Block,
    block_id: usize,
    mut main_inbox: Sender<AsyncMessage>,
    mut inbox: Receiver<AsyncMessage>,
) -> Result<()> {
    // init work io
    let mut work_io = WorkIo {
        call_again: false,
        finished: false,
        block_on: None,
    };

    // setup phase
    loop {
        match inbox.next().await.context("no msg")? {
            AsyncMessage::Initialize => {
                block.init().await?;
                main_inbox.send(AsyncMessage::Initialized).await?;
                break;
            }
            AsyncMessage::StreamOutputInit { src_port, writer } => {
                block.stream_output_mut(src_port).init(writer);
            }
            AsyncMessage::StreamInputInit { dst_port, reader } => {
                block.stream_input_mut(dst_port).set_reader(reader);
            }
            AsyncMessage::MessageOutputConnect {
                src_port,
                dst_port,
                dst_inbox,
            } => {
                block
                    .message_output_mut(src_port)
                    .connect(dst_port, dst_inbox);
            }
            t => warn!(
                "{} unhandled message during init {:?}",
                block.instance_name().unwrap(),
                t
            ),
        }
    }

    let inbox = inbox.peekable();
    futures::pin_mut!(inbox);

    // main loop
    loop {
        // ================== non blocking
        loop {
            match inbox.next().now_or_never() {
                Some(Some(AsyncMessage::Notify)) => {}
                Some(Some(AsyncMessage::StreamInputDone { input_id })) => {
                    block.stream_input_mut(input_id).finish();
                }
                Some(Some(AsyncMessage::StreamOutputDone { .. })) => {
                    work_io.finished = true;
                }
                Some(Some(AsyncMessage::Call { port_id, data })) => {
                    if block.message_input_is_async(port_id) {
                        block.call_async_handler(port_id, data).await?;
                    } else {
                        block.call_sync_handler(port_id, data)?;
                    }
                }
                Some(Some(AsyncMessage::Callback { port_id, data, tx })) => {
                    let res = {
                        if block.message_input_is_async(port_id) {
                            block.call_async_handler(port_id, data).await?
                        } else {
                            block.call_sync_handler(port_id, data)?
                        }
                    };

                    tx.send(res).unwrap();
                }
                Some(Some(AsyncMessage::Terminate)) => work_io.finished = true,
                Some(Some(t)) => warn!("block unhandled message in main loop {:?}", t),
                _ => break,
            }
            // received at least one message
            work_io.call_again = true;
        }

        // ================== shutdown
        if work_io.finished {
            debug!("{} terminating ", block.instance_name().unwrap());
            join_all(
                block
                    .stream_inputs_mut()
                    .iter_mut()
                    .map(|i| i.notify_finished()),
            )
            .await;
            join_all(
                block
                    .stream_outputs_mut()
                    .iter_mut()
                    .map(|o| o.notify_finished()),
            )
            .await;
            join_all(
                block
                    .message_outputs_mut()
                    .iter_mut()
                    .map(|o| o.notify_finished()),
            )
            .await;

            block.deinit().await?;

            // ============= notify main thread
            main_inbox
                .send(AsyncMessage::BlockDone {
                    id: block_id,
                    block,
                })
                .await
                .unwrap();
            break;
        }

        // ================== blocking
        if !work_io.call_again {
            if let Some(f) = work_io.block_on.take() {
                let p = inbox.as_mut().peek();

                match future::select(f, p).await {
                    Either::Left(_) => {
                        work_io.call_again = true;
                    }
                    Either::Right((_, f)) => {
                        work_io.block_on = Some(f);
                        continue;
                    }
                };
            } else {
                inbox.as_mut().peek().await;
                continue;
            }
        }

        // ================== work
        work_io.call_again = false;
        match &mut block {
            Block::Sync(b) => b.work(&mut work_io)?,
            Block::Async(b) => b.work(&mut work_io).await?,
        }

        futures_lite::future::yield_now().await;
    }

    Ok(())
}