logic-mesh 1.0.0

Control logic engine using event based and reactive blocks written in Rust.
Documentation
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright (c) 2022-2023, Radu Racariu.

//!
//! Defines the block connection trait
//!

use uuid::Uuid;

use super::desc::BlockStaticDesc;
use super::{Block, BlockProps};
use crate::base::input::InputProps;
use crate::base::link::{BaseLink, Link, LinkState};
use crate::base::output::Output;

/// Block connection functions
pub trait BlockConnect: BlockStaticDesc {
    /// Connect a block output to the given input
    ///
    /// # Arguments
    /// - output_name: The name of the output to be connected
    /// - input: The block input to be connected
    ///
    fn connect_output(
        &mut self,
        output_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<Uuid, &'static str>;

    /// Connect a block input to another's block input
    ///
    /// # Arguments
    /// - input_name: The name of the output to be connected
    /// - input: The block input to be connected
    ///
    fn connect_input(
        &mut self,
        input_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<Uuid, &'static str>;

    /// Disconnect a block output from the given input
    /// # Arguments
    /// - source_output_name: The name of the source output to be disconnected
    /// - target_input: The target input to be disconnected
    ///
    fn disconnect_output(
        &mut self,
        source_output_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<(), &'static str>;

    /// Disconnect a block input from the given output
    /// # Arguments
    /// - source_input_name: The name of the source input to be disconnected
    /// - target_input: The target input to be disconnected
    fn disconnect_input(
        &mut self,
        source_input_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<(), &'static str>;
}

///
/// Implements the `BlockConnect` trait for all types
/// that are `Block`s
///
impl<T: Block + ?Sized> BlockConnect for T {
    fn connect_output(
        &mut self,
        source_output_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<Uuid, &'static str> {
        let mut outputs = self.outputs_mut();
        let source_output = if let Some(out) = outputs
            .iter_mut()
            .find(|output| output.desc().name == source_output_name)
        {
            out
        } else {
            return Err("Output not found");
        };

        connect_output(*source_output, target_input)
    }

    fn connect_input(
        &mut self,
        source_input_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<Uuid, &'static str> {
        let mut inputs = self.inputs_mut();
        let source_input = if let Some(input) = inputs
            .iter_mut()
            .find(|input| input.name() == source_input_name)
        {
            *input as &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>
        } else {
            return Err("Input not found");
        };
        connect_input(source_input, target_input)
    }

    fn disconnect_output(
        &mut self,
        source_output_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<(), &'static str> {
        let mut outputs = self.outputs_mut();
        let source_output = if let Some(out) = outputs
            .iter_mut()
            .find(|output| output.desc().name == source_output_name)
        {
            out
        } else {
            return Err("Output not found");
        };

        disconnect_output(*source_output, target_input)
    }

    fn disconnect_input(
        &mut self,
        source_input_name: &str,
        target_input: &mut dyn InputProps<Reader = Self::Reader, Writer = Self::Writer>,
    ) -> Result<(), &'static str> {
        let mut inputs = self.inputs_mut();
        let source_input = if let Some(in_) = inputs
            .iter_mut()
            .find(|input| input.name() == source_input_name)
        {
            in_
        } else {
            return Err("Input not found");
        };

        let link_id = link_id_for_input(source_input.links(), target_input);

        if let Some(id) = link_id {
            source_input.remove_link_by_id(&id);
            target_input.decrement_conn();
            Ok(())
        } else {
            Err("No connection found")
        }
    }
}

/// Connect a block output to the given input
/// # Arguments
/// - source_output: The output to be connected
/// - target_input: The block input to be connected
pub fn connect_output<Reader, Writer: Clone>(
    source_output: &mut dyn Output<Writer = Writer>,
    target_input: &mut dyn InputProps<Reader = Reader, Writer = Writer>,
) -> Result<Uuid, &'static str> {
    // Connections should be unique.
    if source_output.links().iter().any(|link| {
        link.target_block_id() == target_input.block_id()
            && link.target_input() == target_input.name()
    }) {
        return Err("Already connected");
    }

    let mut link = BaseLink::new(*target_input.block_id(), target_input.name().to_string());
    let id = link.id;

    link.tx = Some(target_input.writer().clone());

    link.state = LinkState::Connected;

    source_output.add_link(link);
    target_input.increment_conn();

    Ok(id)
}

/// Disconnect a block output from the given input
/// # Arguments
/// - source_output: The output to be disconnected
/// - target_input: The block input to be disconnected
///
/// # Returns
/// - `Ok(())` if the disconnection was successful, `Err` otherwise
pub fn disconnect_output<Reader, Writer: Clone>(
    source_output: &mut dyn Output<Writer = Writer>,
    target_input: &mut dyn InputProps<Reader = Reader, Writer = Writer>,
) -> Result<(), &'static str> {
    let link_id = link_id_for_input(source_output.links(), target_input);

    if let Some(id) = link_id {
        source_output.remove_link_by_id(&id);
        target_input.decrement_conn();
        Ok(())
    } else {
        Err("No connection found")
    }
}

/// Connect a block input to another's block input
/// # Arguments
/// - source_input: The input to be connected to
/// - target_input: The block input to be connected
pub fn connect_input<Reader, Writer: Clone>(
    source_input: &mut dyn InputProps<Reader = Reader, Writer = Writer>,
    target_input: &mut dyn InputProps<Reader = Reader, Writer = Writer>,
) -> Result<Uuid, &'static str> {
    if source_input.block_id() == target_input.block_id() {
        return Err("Cannot connect to the same block");
    }

    if source_input.links().iter().any(|link| {
        link.target_block_id() == target_input.block_id()
            && link.target_input() == target_input.name()
    }) {
        return Err("Already connected");
    }

    let mut link = BaseLink::new(*target_input.block_id(), target_input.name().to_string());
    let id = link.id;

    link.tx = Some(target_input.writer().clone());

    link.state = LinkState::Connected;

    source_input.add_link(link);
    target_input.increment_conn();

    Ok(id)
}

/// Disconnect a block input from another's block input
/// # Arguments
/// - source_input: The input to be disconnected from
/// - target_input: The block input to be disconnected
/// # Returns
/// - `Ok(())` if the disconnection was successful, `Err` otherwise
pub fn disconnect_input<I: InputProps + ?Sized>(
    source_input: &mut I,
    target_input: &mut I,
) -> Result<(), &'static str> {
    let link_id = link_id_for_input(source_input.links(), target_input);

    if let Some(id) = link_id {
        source_input.remove_link_by_id(&id);
        target_input.decrement_conn();
        Ok(())
    } else {
        Err("No connection found")
    }
}

/// Disconnect all the inputs and outputs of a block
/// # Arguments
/// - block: The block to be disconnected
/// - decrement_target_input: A function that decrements the number of connections of a block input
pub fn disconnect_block<B, F>(block: &mut B, mut decrement_target_input: F)
where
    B: BlockProps + ?Sized,
    F: FnMut(&Uuid, &str) -> Option<usize>,
{
    block
        .outputs_mut()
        .iter()
        .filter(|output| output.is_connected())
        .for_each(|out| {
            out.links().iter_mut().for_each(|link| {
                decrement_target_input(link.target_block_id(), link.target_input());
            });
        });

    block
        .inputs_mut()
        .iter()
        .filter(|input| input.has_output())
        .for_each(|src_input| {
            src_input.links().iter_mut().for_each(|link| {
                decrement_target_input(link.target_block_id(), link.target_input());
            });
        });

    block.remove_all_links();
}

/// Disconnect a link from a block
/// # Arguments
/// - block: The block to be disconnected
/// - link_id: The id of the link to be disconnected
/// - decrement_target_input: A function that decrements the number of connections of a block input
pub fn disconnect_link<B, F>(block: &mut B, link_id: &Uuid, mut decrement_target_input: F) -> bool
where
    B: BlockProps + ?Sized,
    F: FnMut(&Uuid, &str) -> Option<usize>,
{
    if !block
        .outputs_mut()
        .iter()
        .filter(|output| output.is_connected())
        .any(|out| {
            out.links().iter_mut().any(|link| {
                if link.id() == link_id {
                    decrement_target_input(link.target_block_id(), link.target_input());
                    true
                } else {
                    false
                }
            })
        })
        && !block
            .inputs_mut()
            .iter()
            .filter(|input| input.has_output())
            .any(|src_input| {
                src_input.links().iter_mut().any(|link| {
                    if link.id() == link_id {
                        decrement_target_input(link.target_block_id(), link.target_input());
                        true
                    } else {
                        false
                    }
                })
            })
    {
        return false;
    }

    block.remove_link_by_id(link_id);
    true
}

fn link_id_for_input<I: InputProps + ?Sized>(
    links: Vec<&(dyn Link + Send)>,
    target_input: &I,
) -> Option<Uuid> {
    links
        .iter()
        .find(|link| {
            link.target_input() == target_input.name()
                && link.target_block_id() == target_input.block_id()
        })
        .map(|link| *link.id())
}

#[cfg(test)]
mod test {

    use uuid::Uuid;

    use crate::base::{
        block::{Block, BlockDesc, BlockProps, BlockState, connect::disconnect_block},
        input::InputProps,
    };

    use super::BlockConnect;

    use crate::base::block::test_utils::mock::{InputImpl, OutputImpl};

    use libhaystack::val::kind::HaystackKind;

    #[block]
    #[derive(BlockProps, Debug)]
    #[category = "test"]
    struct Block1 {
        #[input(kind = "Number")]
        input1: InputImpl,
        #[output(kind = "Number")]
        out: OutputImpl,
    }
    impl Block for Block1 {
        async fn execute(&mut self) {
            todo!()
        }
    }

    #[block]
    #[derive(BlockProps, Debug)]
    #[category = "test"]
    struct Block2 {
        #[input(kind = "Number")]
        input1: InputImpl,
        #[output(kind = "Number")]
        out: OutputImpl,
    }
    impl Block for Block2 {
        async fn execute(&mut self) {
            todo!()
        }
    }

    #[test]
    fn test_block_out_links() {
        let mut block1 = Block1::new();
        let mut block2 = Block2::new();

        assert_eq!(block1.name(), "Block1");
        assert_eq!(block2.name(), "Block2");

        let input = &mut block2.inputs_mut()[0];
        block1
            .connect_output("out", *input)
            .expect("Could not connect");

        assert!(input.is_connected());
        assert_eq!(block1.outputs()[0].links().len(), 1);

        assert!(
            block1.connect_output("out", *input).is_err(),
            "Should not be able to connect twice"
        );

        assert!(
            block1.connect_output("invalid out", *input).is_err(),
            "Should not be able to connect to invalid output"
        );

        block1
            .disconnect_output("out", *input)
            .expect("Could not disconnect");

        assert!(!input.is_connected());
        assert_eq!(block1.outputs()[0].links().len(), 0);
    }

    #[test]
    fn test_block_input_links() {
        let mut block1 = Block1::new();
        let mut block2 = Block2::new();

        let input2 = &mut block2.inputs_mut()[0];

        block1
            .connect_input("input1", *input2)
            .expect("Could not connect");

        assert!(
            block1.connect_input("input1", *input2).is_err(),
            "Should not be able to connect twice"
        );
        assert!(
            block1.connect_input("invalid input", *input2).is_err(),
            "Should not be able to connect to invalid input"
        );

        assert!(block1.input1.has_output());
        assert!(input2.is_connected());
        assert_eq!(block1.input1.links().len(), 1);
        assert_eq!(input2.links().len(), 0);

        block1
            .disconnect_input("input1", *input2)
            .expect("Could not disconnect");

        assert!(!block1.input1.is_connected());
        assert_eq!(block1.outputs()[0].links().len(), 0);
    }

    #[test]
    fn test_block_disconnect() {
        let mut block1 = Block1::new();
        let mut block2 = Block2::new();
        {
            let input2 = &mut block2.inputs_mut()[0];

            block1
                .connect_input("input1", *input2)
                .expect("Could not connect");

            assert!(
                block1.connect_input("input1", *input2).is_err(),
                "Should not be able to connect twice"
            );
            assert!(
                block1.connect_input("invalid input", *input2).is_err(),
                "Should not be able to connect to invalid input"
            );

            assert!(input2.is_connected());
            assert!(block1.input1.links().len() == 1);
        }

        let gid = *block2.id();
        let input1 = &mut block2.input1;

        disconnect_block(&mut block1, |id, name| {
            assert!(*id == gid);
            assert!(name == "input1");
            Some(input1.decrement_conn())
        });

        assert!(!input1.is_connected());
        assert!(block1.input1.links().is_empty());
    }
}