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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use std::fmt;

use log::debug;
use serde_derive::{Deserialize, Serialize};

use crate::compiler::loader::Validate;
use crate::errors::*;
use crate::model::datatype::DataType;
use crate::model::io::IO;
use crate::model::name::Name;
use crate::model::route::HasRoute;
use crate::model::route::Route;

/// `Connection` defines a connection between the output of one function or flow to the input
/// of another function or flow and maybe optionally named for legibility/debugging.
#[derive(Deserialize, Serialize, Default, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct Connection {
    /// Optional name given to a connection for legibility and debugging
    #[serde(default, skip_serializing_if = "String::is_empty")]
    name: Name,
    /// `from` defines the origin of the connection
    from: Route,
    /// `to` defines the destination(s) of this connection
    #[serde(deserialize_with = "super::route_array_serde::route_or_route_array")]
    to: Vec<Route>,
    /// `from_io` is used during the compilation process and refers to a found output for the connection
    // TODO make these references, not clones
    #[serde(skip)]
    from_io: IO,
    /// `to_io` is used during the compilation process and refers to a found input for the connection
    #[serde(skip)]
    to_io: IO,
    /// `level` defines at what level in the flow hierarchy of nested flows this connections belongs
    #[serde(skip)]
    level: usize,
}

/// `Direction` defines whether a `Connection` is coming from an IO or to an IO
#[derive(Debug)]
#[allow(clippy::upper_case_acronyms)]
pub enum Direction {
    /// The `Connection` is `FROM` this IO to another
    FROM,
    /// The `Connection` is `TO` this IO from another
    TO,
}

impl fmt::Display for Connection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match (self.from_io.flow_io(), self.to_io.flow_io()) {
            (true, true) => write!(
                f,
                "(f){} --> {}(f)",
                self.from_io.route(),
                self.to_io.route()
            ),
            (true, false) => write!(f, "(f){} --> {}", self.from_io.route(), self.to_io.route()),
            (false, true) => write!(
                f,
                "   {} --> {}(f)",
                self.from_io.route(),
                self.to_io.route()
            ),
            (false, false) => write!(f, "   {} --> {}", self.from_io.route(), self.to_io.route()),
        }
    }
}

impl Validate for Connection {
    // TODO maybe validate some of the combinations here that are checked in build_connections here?
    fn validate(&self) -> Result<()> {
        self.name.validate()?;
        self.from.validate()?;
        for destination in &self.to {
            destination.validate()?;
        }
        Ok(())
    }
}

impl Connection {
    /// Create a new Route with `from_route` as the source `Route` and `to_route` as the destination
    #[cfg(test)]
    pub fn new<R>(from_route: R, to_route: R) -> Self
    where
        R: Into<Route>,
    {
        Connection {
            from: from_route.into(),
            to: vec![to_route.into()],
            ..Default::default()
        }
    }

    /// Return the name
    #[cfg(feature = "debugger")]
    pub fn name(&self) -> &Name {
        &self.name
    }

    /// Connect the `from_io` to the `to_io` if they are compatible
    pub fn connect(&mut self, from_io: IO, to_io: IO, level: usize) -> Result<()> {
        if Self::compatible_types(from_io.datatypes(), to_io.datatypes(), &self.from) {
            debug!(
                "Connection built from '{}' to '{}'",
                from_io.route(),
                to_io.route()
            );
            self.from_io = from_io;
            self.to_io = to_io;
            self.level = level;
            return Ok(());
        }

        bail!("Cannot connect types: from {:#?} to\n{:#?}", from_io, to_io);
    }

    /// Return the `from` Route specified in this connection
    pub(crate) fn from(&self) -> &Route {
        &self.from
    }

    /// Return a reference to the from_io
    pub fn from_io(&self) -> &IO {
        &self.from_io
    }

    /// Return the `to` Route specified in this connection
    pub(crate) fn to(&self) -> &Vec<Route> {
        &self.to
    }

    /// Return a mutable reference to the from_io
    pub fn from_io_mut(&mut self) -> &mut IO {
        &mut self.from_io
    }

    /// Return a reference to the to_io
    pub fn to_io(&self) -> &IO {
        &self.to_io
    }

    /// Return a mutable reference to the to_io
    pub fn to_io_mut(&mut self) -> &mut IO {
        &mut self.to_io
    }

    /// Get at what level in the flow hierarchy this connection exists (source)
    pub fn level(&self) -> usize {
        self.level
    }

    /// For a set of output types to be compatible with a destination's set of types
    /// ALL of the output_types must have a compatible input type, to guarantee that any
    /// of the valid types produced can be handled by the destination
    fn compatible_types(from: &[DataType], to: &[DataType], _from_route: &Route) -> bool {
        if from.is_empty() || to.is_empty() {
            return false;
        }

        for output_type in from {
            let mut compatible_destination_type = false;
            for input_type in to {
                if Self::two_compatible_types(output_type, input_type) {
                    compatible_destination_type = true;
                }
            }
            if !compatible_destination_type {
                return false; // we could not find a compatible_destination_type for this output_type
            }
        }

        true // all output_types found a compatible destination type
    }

    /// Determine if the type of the source of a connection and the type of the destination are
    /// compatible, what type of conversion maybe required and if a Connection can be formed
    /// TODO calculate the real from type based on the subroute of the output used by
    /// the connection from_route
    fn two_compatible_types(from: &DataType, to: &DataType) -> bool {
        if from == to {
            return true;
        }

        if to.is_generic() {
            return true;
        }

        if to.array_of(from) {
            return true;
        }

        if to.array_of(&DataType::from("Value")) {
            return true;
        }

        if from.array_of(to) {
            return true;
        }

        // Faith for now!
        if from.is_generic() && !to.array_of(&DataType::from("Value")) {
            return true;
        }

        // Faith for now!
        if from.array_of(&DataType::from("Value")) && !to.is_array() {
            return true;
        }

        // Faith that "Value" elements can be converted to whatever the destination array is
        if from.array_of(&DataType::from("Value")) && to.is_array() {
            return true;
        }

        false
    }
}

#[cfg(test)]
mod test {
    use url::Url;

    use flowcore::deserializers::deserializer::get_deserializer;
    use flowcore::errors::*;

    use crate::compiler::loader::Validate;

    use super::Connection;

    fn toml_from_str(content: &str) -> Result<Connection> {
        let url = Url::parse("file:///fake.toml").expect("Could not parse URL");
        let deserializer =
            get_deserializer::<Connection>(&url).expect("Could not get deserializer");
        deserializer.deserialize(content, Some(&url))
    }

    #[test]
    fn single_destination_deserialization() {
        let input_str = "
        from = 'source'
        to = 'destination'
        ";

        let connection: Result<Connection> = toml_from_str(input_str);
        assert!(connection.is_ok(), "Could not deserialize Connection");
    }

    #[test]
    fn multiple_destination_deserialization() {
        let input_str = "
        from = 'source'
        to = ['destination', 'destination2']
        ";

        let connection: Result<Connection> = toml_from_str(input_str);
        assert!(connection.is_ok(), "Could not deserialize Connection");
    }

    #[test]
    fn display_connection() {
        let connection1 = Connection::new("input/number", "process_1");
        println!("Connection: {}", connection1);
    }

    #[test]
    fn validate_connection() {
        let connection1 = Connection::new("input/number", "process_1");
        assert!(connection1.validate().is_ok());
    }

    #[test]
    fn deserialize_extra_field_fails() {
        let input_str = "
        name = 'input'
        foo = 'extra token'
        type = 'Value'
        ";

        let connection: Result<Connection> = toml_from_str(input_str);
        assert!(
            connection.is_err(),
            "Deserialized invalid connection TOML without error, but should not have."
        );
    }

    mod type_conversion {
        use crate::model::datatype::DataType;
        use crate::model::io::IO;
        use crate::model::route::Route;

        use super::super::Connection;

        /// # Compatible Types in a Connection
        ///
        /// ## Simple Object Value being sent
        ///   Value Type        Input Type
        /// * Simple Object --> Simple Object (is_array = false)
        /// input and sent to the function as an array
        /// * Simple Object --> Array (is_array = true)
        ///
        /// ## Array Object being sent
        ///   Value Type        Input Type
        /// * Array Object  --> Array (is_array = true)
        /// * Array Object  --> Simple Object (is_array = false) (values in Array will be
        /// serialized and sent to input one by one)

        #[test]
        fn type_conversions() {
            let valid_type_conversions: Vec<(&str, &str)> = vec![
                ("Number", "Value"),
                ("Value", "Value"),
                ("Array/Value", "Value"),
                ("Number", "Number"),
                ("Number", "Value"),
                ("Array/Number", "Value"),
                ("Number", "Array/Number"),
                ("Array/Number", "Number"),
                ("Number", "Array/Value"),
                ("Array/Number", "Array/Number"),
                ("Array/Value", "Array/Array/Number"),
                ("Array/Array/Number", "Array/Number"),
                ("Array/Array/Number", "Value"),
                ("Value", "Number"), // Trust me!
                ("Array/Value", "Array/Number"),
            ];

            for test in valid_type_conversions.iter() {
                assert!(Connection::compatible_types(
                    &[DataType::from(test.0)],
                    &[DataType::from(test.1)],
                    &Route::default()
                ));
            }
        }
        #[test]
        fn simple_to_simple() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn simple_indexed_to_simple() {
            let from_io = IO::new(vec!("String".into()), "/p1/output/0");
            let to_io = IO::new(vec!("String".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn simple_to_simple_mismatch() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("Number".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn simple_indexed_to_array() {
            let from_io = IO::new(vec!("String".into()), "/p1/output/0");
            let to_io = IO::new(vec!("Array/String".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn simple_to_array() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("Array/String".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn simple_to_array_mismatch() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("Array/Number".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn array_to_array() {
            let from_io = IO::new(vec!("Array".into()), "/p1/output");
            let to_io = IO::new(vec!("Array".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn array_to_simple() {
            let from_io = IO::new(vec!("Array/String".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_single_input_type() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_value_input_type() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("Value".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_matching_input_types() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into(), "Number".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn single_output_type_to_superset_input_types() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into(), "Number".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_superset_input_types() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into(), "Number".into(), "Array".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_non_matching_input_types() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("String".into(), "Array".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn single_output_type_to_non_matching_input_types() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("Array".into(), "Number".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn multiple_output_type_to_value_input_types() {
            let from_io = IO::new(vec!("String".into(), "Number".into()), "/p1/output");
            let to_io = IO::new(vec!("Array".into(), "Value".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn single_output_type_to_value_input_types() {
            let from_io = IO::new(vec!("String".into()), "/p1/output");
            let to_io = IO::new(vec!("Array".into(), "Value".into()), "/p2");
            assert!(Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn null_output_type_to_valid_input_types() {
            let from_io = IO::new(vec!(), "/p1/output");
            let to_io = IO::new(vec!("Value".into()), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn valid_output_type_to_null_input_types() {
            let from_io = IO::new(vec!("Value".into()), "/p1/output");
            let to_io = IO::new(vec!(), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }

        #[test]
        fn null_output_type_to_null_input_types() {
            let from_io = IO::new(vec!(), "/p1/output");
            let to_io = IO::new(vec!(), "/p2");
            assert!(!Connection::compatible_types(
                from_io.datatypes(),
                to_io.datatypes(),
                &Route::default()
            ));
        }
    }
}