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
use std::any::Any;
use std::fmt;
use std::future::Future;
use std::pin::Pin;

use crate::anyhow::Result;
use crate::runtime::BlockMeta;
use crate::runtime::MessageIo;
use crate::runtime::MessageOutput;
use crate::runtime::Pmt;
use crate::runtime::StreamInput;
use crate::runtime::StreamIo;
use crate::runtime::StreamOutput;

pub struct WorkIo {
    pub call_again: bool,
    pub finished: bool,
    pub block_on: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
}

impl WorkIo {
    pub fn block_on<F: Future<Output = ()> + Send + 'static>(&mut self, f: F) {
        self.block_on = Some(Box::pin(f));
    }
}

impl fmt::Debug for WorkIo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("WorkIo")
            .field("call_again", &self.call_again)
            .field("finished", &self.finished)
            .finish()
    }
}

#[async_trait]
pub trait Kernel: Send {
    async fn work(
        &mut self,
        _io: &mut WorkIo,
        _s: &mut StreamIo,
        _m: &mut MessageIo<Self>,
        _b: &mut BlockMeta,
    ) -> Result<()> {
        Ok(())
    }
    async fn init(
        &mut self,
        _s: &mut StreamIo,
        _m: &mut MessageIo<Self>,
        _b: &mut BlockMeta,
    ) -> Result<()> {
        Ok(())
    }
    async fn deinit(
        &mut self,
        _s: &mut StreamIo,
        _m: &mut MessageIo<Self>,
        _b: &mut BlockMeta,
    ) -> Result<()> {
        Ok(())
    }
}

#[async_trait]
pub trait BlockT: Send + Any {
    // ##### BLOCK
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;

    // ##### META
    fn instance_name(&self) -> Option<&str>;
    fn set_instance_name(&mut self, name: &str);
    fn type_name(&self) -> &str;
    fn is_blocking(&self) -> bool;

    // ##### KERNEL
    async fn work(&mut self, io: &mut WorkIo) -> Result<()>;
    async fn init(&mut self) -> Result<()>;
    async fn deinit(&mut self) -> Result<()>;

    // ##### STREAM IO
    fn commit(&mut self);
    #[allow(clippy::type_complexity)]
    fn set_tag_propagation(
        &mut self,
        f: Box<dyn FnMut(&mut [StreamInput], &mut [StreamOutput]) + Send + 'static>,
    );
    fn stream_inputs(&self) -> &Vec<StreamInput>;
    fn stream_inputs_mut(&mut self) -> &mut Vec<StreamInput>;
    fn stream_input(&self, id: usize) -> &StreamInput;
    fn stream_input_mut(&mut self, id: usize) -> &mut StreamInput;
    fn stream_input_name_to_id(&self, name: &str) -> Option<usize>;
    fn stream_outputs(&self) -> &Vec<StreamOutput>;
    fn stream_outputs_mut(&mut self) -> &mut Vec<StreamOutput>;
    fn stream_output(&self, id: usize) -> &StreamOutput;
    fn stream_output_mut(&mut self, id: usize) -> &mut StreamOutput;
    fn stream_output_name_to_id(&self, name: &str) -> Option<usize>;

    // ##### MESSAGE IO
    fn message_input_name_to_id(&self, name: &str) -> Option<usize>;
    fn message_outputs(&self) -> &Vec<MessageOutput>;
    fn message_outputs_mut(&mut self) -> &mut Vec<MessageOutput>;
    fn message_output(&self, id: usize) -> &MessageOutput;
    fn message_output_mut(&mut self, id: usize) -> &mut MessageOutput;
    fn message_output_name_to_id(&self, name: &str) -> Option<usize>;

    async fn call_handler(&mut self, id: usize, p: Pmt) -> Result<Pmt>;
    async fn post(&mut self, id: usize, p: Pmt);
}

pub struct TypedBlock<T> {
    meta: BlockMeta,
    sio: StreamIo,
    mio: MessageIo<T>,
    kernel: T,
}

#[async_trait]
impl<T: Kernel + Send + 'static> BlockT for TypedBlock<T> {
    // ##### Block
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    // ##### META
    fn instance_name(&self) -> Option<&str> {
        self.meta.instance_name()
    }
    fn set_instance_name(&mut self, name: &str) {
        self.meta.set_instance_name(name);
    }
    fn type_name(&self) -> &str {
        self.meta.type_name()
    }
    fn is_blocking(&self) -> bool {
        self.meta.is_blocking()
    }

    // ##### KERNEL
    async fn work(&mut self, io: &mut WorkIo) -> Result<()> {
        self.kernel
            .work(io, &mut self.sio, &mut self.mio, &mut self.meta)
            .await
    }
    async fn init(&mut self) -> Result<()> {
        self.kernel
            .init(&mut self.sio, &mut self.mio, &mut self.meta)
            .await
    }
    async fn deinit(&mut self) -> Result<()> {
        self.kernel
            .deinit(&mut self.sio, &mut self.mio, &mut self.meta)
            .await
    }

    // ##### STREAM IO
    fn commit(&mut self) {
        self.sio.commmit();
    }
    fn set_tag_propagation(
        &mut self,
        f: Box<dyn FnMut(&mut [StreamInput], &mut [StreamOutput]) + Send + 'static>,
    ) {
        self.sio.set_tag_propagation(f);
    }
    fn stream_inputs(&self) -> &Vec<StreamInput> {
        self.sio.inputs()
    }
    fn stream_inputs_mut(&mut self) -> &mut Vec<StreamInput> {
        self.sio.inputs_mut()
    }
    fn stream_input(&self, id: usize) -> &StreamInput {
        self.sio.input_ref(id)
    }
    fn stream_input_mut(&mut self, id: usize) -> &mut StreamInput {
        self.sio.input(id)
    }
    fn stream_input_name_to_id(&self, name: &str) -> Option<usize> {
        self.sio.input_name_to_id(name)
    }
    fn stream_outputs(&self) -> &Vec<StreamOutput> {
        self.sio.outputs()
    }
    fn stream_outputs_mut(&mut self) -> &mut Vec<StreamOutput> {
        self.sio.outputs_mut()
    }
    fn stream_output(&self, id: usize) -> &StreamOutput {
        self.sio.output_ref(id)
    }
    fn stream_output_mut(&mut self, id: usize) -> &mut StreamOutput {
        self.sio.output(id)
    }
    fn stream_output_name_to_id(&self, name: &str) -> Option<usize> {
        self.sio.output_name_to_id(name)
    }

    // ##### MESSAGE IO
    fn message_input_name_to_id(&self, name: &str) -> Option<usize> {
        self.mio.input_name_to_id(name)
    }
    fn message_outputs(&self) -> &Vec<MessageOutput> {
        self.mio.outputs()
    }
    fn message_outputs_mut(&mut self) -> &mut Vec<MessageOutput> {
        self.mio.outputs_mut()
    }
    fn message_output(&self, id: usize) -> &MessageOutput {
        self.mio.output(id)
    }
    fn message_output_mut(&mut self, id: usize) -> &mut MessageOutput {
        self.mio.output_mut(id)
    }
    fn message_output_name_to_id(&self, name: &str) -> Option<usize> {
        self.mio.output_name_to_id(name)
    }
    async fn call_handler(&mut self, id: usize, p: Pmt) -> Result<Pmt> {
        let h = self.mio.input(id).get_handler();
        let f = (h)(&mut self.kernel, &mut self.mio, &mut self.meta, p);
        f.await
    }
    async fn post(&mut self, id: usize, p: Pmt) {
        self.mio.post(id, p).await;
    }
}

#[derive(Debug)]
pub struct Block(Box<dyn BlockT>);

impl Block {
    pub fn new<T: Kernel + Send + 'static>(
        meta: BlockMeta,
        sio: StreamIo,
        mio: MessageIo<T>,
        kernel: T,
    ) -> Block {
        Self(Box::new(TypedBlock {
            meta,
            sio,
            mio,
            kernel,
        }))
    }

    pub fn kernel<T: Kernel + Send + 'static>(&self) -> Option<&T> {
        self.0
            .as_any()
            .downcast_ref::<TypedBlock<T>>()
            .map(|b| &b.kernel)
    }

    pub fn kernel_mut<T: Kernel + Send + 'static>(&mut self) -> Option<&T> {
        self.0
            .as_any_mut()
            .downcast_mut::<TypedBlock<T>>()
            .map(|b| &b.kernel)
    }

    // ##### META
    pub fn instance_name(&self) -> Option<&str> {
        self.0.instance_name()
    }
    pub fn set_instance_name(&mut self, name: &str) {
        self.0.set_instance_name(name)
    }
    pub fn type_name(&self) -> &str {
        self.0.type_name()
    }
    pub fn is_blocking(&self) -> bool {
        self.0.is_blocking()
    }

    // ##### KERNEL
    pub async fn init(&mut self) -> Result<()> {
        self.0.init().await
    }
    pub async fn work(&mut self, io: &mut WorkIo) -> Result<()> {
        self.0.work(io).await
    }
    pub async fn deinit(&mut self) -> Result<()> {
        self.0.deinit().await
    }

    // ##### STREAM IO
    pub fn commit(&mut self) {
        self.0.commit();
    }
    #[allow(clippy::type_complexity)]
    pub fn set_tag_propagation(
        &mut self,
        f: Box<dyn FnMut(&mut [StreamInput], &mut [StreamOutput]) + Send + 'static>,
    ) {
        self.0.set_tag_propagation(f);
    }
    pub fn stream_inputs(&self) -> &Vec<StreamInput> {
        self.0.stream_inputs()
    }
    pub fn stream_inputs_mut(&mut self) -> &mut Vec<StreamInput> {
        self.0.stream_inputs_mut()
    }
    pub fn stream_input(&self, id: usize) -> &StreamInput {
        self.0.stream_input(id)
    }
    pub fn stream_input_mut(&mut self, id: usize) -> &mut StreamInput {
        self.0.stream_input_mut(id)
    }
    pub fn stream_input_name_to_id(&self, name: &str) -> Option<usize> {
        self.0.stream_input_name_to_id(name)
    }
    pub fn stream_outputs(&self) -> &Vec<StreamOutput> {
        self.0.stream_outputs()
    }
    pub fn stream_outputs_mut(&mut self) -> &mut Vec<StreamOutput> {
        self.0.stream_outputs_mut()
    }
    pub fn stream_output(&self, id: usize) -> &StreamOutput {
        self.0.stream_output(id)
    }
    pub fn stream_output_mut(&mut self, id: usize) -> &mut StreamOutput {
        self.0.stream_output_mut(id)
    }
    pub fn stream_output_name_to_id(&self, name: &str) -> Option<usize> {
        self.0.stream_output_name_to_id(name)
    }

    // ##### MESSAGE IO
    pub fn message_input_name_to_id(&self, name: &str) -> Option<usize> {
        self.0.message_input_name_to_id(name)
    }
    pub fn message_outputs(&self) -> &Vec<MessageOutput> {
        self.0.message_outputs()
    }
    pub fn message_outputs_mut(&mut self) -> &mut Vec<MessageOutput> {
        self.0.message_outputs_mut()
    }
    pub fn message_output(&self, id: usize) -> &MessageOutput {
        self.0.message_output(id)
    }
    pub fn message_output_mut(&mut self, id: usize) -> &mut MessageOutput {
        self.0.message_output_mut(id)
    }
    pub fn message_output_name_to_id(&self, name: &str) -> Option<usize> {
        self.0.message_output_name_to_id(name)
    }
    pub async fn call_handler(&mut self, id: usize, p: Pmt) -> Result<Pmt> {
        self.0.call_handler(id, p).await
    }
    pub async fn post(&mut self, id: usize, p: Pmt) {
        self.0.post(id, p).await
    }
}

impl<T: Kernel + Send + 'static> fmt::Debug for TypedBlock<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsyncBlock")
            .field("type_name", &self.type_name().to_string())
            .finish()
    }
}

impl fmt::Debug for dyn BlockT {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BlockT")
            .field("type_name", &self.type_name().to_string())
            .finish()
    }
}