flowcore 1.0.0

Structures shared between runtime and clients
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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
use std::collections::BTreeMap;
use std::fmt;

use error_chain::bail;
use serde_derive::{Deserialize, Serialize};
use url::Url;

use crate::errors::{Result, ResultExt};
use crate::model::input::InputInitializer;
use crate::model::io::IOSet;
use crate::model::io::IOType;
use crate::model::name::HasName;
use crate::model::name::Name;
use crate::model::output_connection::OutputConnection;
use crate::model::route::HasRoute;
use crate::model::route::Route;
use crate::model::route::SetIORoutes;
use crate::model::route::SetRoute;
use crate::model::validation::Validate;

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
    !b
}

/// `FunctionDefinition` defines a Function (compile time) that implements some processing in the flow hierarchy
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct FunctionDefinition {
    /// `Name` of the function
    #[serde(rename = "function")]
    pub name: Name,
    /// Is this an impure function that interacts with the environment
    #[serde(default, skip_serializing_if = "is_false")]
    pub impure: bool,
    /// Name of the source file for the function implementation
    pub source: String,
    /// Name of any docs file associated with this Function
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub docs: String,
    /// Optional description of what this function does
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Type of build used to compile Function's implementation to WASM from source
    #[serde(default, rename = "type")]
    pub build_type: String,
    /// The set of inputs this function has
    #[serde(default, rename = "input")]
    pub inputs: IOSet,
    /// The set of outputs this function generates when executed
    #[serde(default, rename = "output", skip_serializing_if = "Vec::is_empty")]
    pub outputs: IOSet,
    /// As a function can be used multiple times in a single flow, the repeated instances must
    /// be referred to using an alias to disambiguate which instance is being referred to
    #[serde(skip)]
    pub alias: Name,
    /// `source_url` is where this function definition was read from
    #[serde(skip, default = "FunctionDefinition::default_url")]
    pub(crate) source_url: Url,
    /// the `route` in the flow hierarchy where this function is located
    #[serde(skip)]
    pub route: Route,
    /// Implementation is the relative path from the lib root to the compiled wasm implementation
    #[serde(skip)]
    pub implementation: String,
    /// Is the function being used part of a library and where is it found
    #[serde(skip)]
    pub lib_reference: Option<Url>,
    /// Is the function a context function and where is it found
    #[serde(skip)]
    pub context_reference: Option<Url>,
    /// The output connections from this function to other processes (functions or flows)
    #[serde(skip)]
    pub output_connections: Vec<OutputConnection>,
    /// A unique `process_id` assigned to the function as the flow is parsed hierarchically
    #[serde(skip)]
    pub(crate) process_id: usize,
    /// the `id` of the parent `FlowDefinition` that this `FunctionDefinition` lies within in the hierarchy
    #[serde(skip)]
    pub(crate) parent_id: usize,
}

impl Default for FunctionDefinition {
    fn default() -> Self {
        FunctionDefinition {
            name: String::default(),
            impure: false,
            source: String::new(),
            docs: String::new(),
            description: String::new(),
            build_type: String::new(),
            inputs: vec![],
            outputs: vec![],
            alias: String::default(),
            source_url: FunctionDefinition::default_url(),
            route: Route::default(),
            implementation: String::new(),
            lib_reference: None,
            context_reference: None,
            output_connections: vec![],
            process_id: 0,
            parent_id: 0,
        }
    }
}

impl HasName for FunctionDefinition {
    fn name(&self) -> &Name {
        &self.name
    }
    fn alias(&self) -> &Name {
        &self.alias
    }
}

impl HasRoute for FunctionDefinition {
    fn route(&self) -> &Route {
        &self.route
    }
    fn route_mut(&mut self) -> &mut Route {
        &mut self.route
    }
}

impl FunctionDefinition {
    #[allow(clippy::expect_used)]
    fn default_url() -> Url {
        Url::parse("file://").expect("Could not create default_url")
    }

    /// Create a new function - used mainly for testing as Functions are usually deserialized
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub fn new(
        name: Name,
        impure: bool,
        source: String,
        alias: Name,
        inputs: IOSet,
        outputs: IOSet,
        source_url: Url,
        route: Route,
        lib_reference: Option<Url>,
        context_reference: Option<Url>,
        output_connections: Vec<OutputConnection>,
        id: usize,
        parent_id: usize,
    ) -> Self {
        FunctionDefinition {
            name,
            impure,
            source,
            docs: String::default(),
            alias,
            inputs,
            outputs,
            source_url,
            route,
            implementation: String::default(),
            lib_reference,
            context_reference,
            output_connections,
            process_id: id,
            parent_id,
            build_type: String::default(),
            description: String::default(),
        }
    }

    /// Configure a function with additional information after it is deserialized as part of a flow
    ///
    /// # Errors
    ///
    /// Returns `Err` if the provided `initializations` cannot be set as initializers on the function
    #[allow(clippy::too_many_arguments)]
    pub fn config(
        &mut self,
        original_url: &Url,
        source_url: &Url,
        parent_route: &Route,
        alias: &Name,
        parent_id: usize,
        reference: Option<Url>,
        initializations: &BTreeMap<String, InputInitializer>,
    ) -> Result<()> {
        self.set_parent_id(parent_id);
        self.set_alias(alias);
        self.set_source_url(source_url);
        if let Some(function_reference) = reference {
            match function_reference.scheme() {
                "context" => {
                    if !alias.is_empty() {
                        bail!("context:// functions cannot be aliased");
                    }
                    self.set_context_reference(Some(function_reference));
                }
                "lib" => self.set_lib_reference(Some(function_reference)),
                _ => {}
            }
        }
        self.set_routes_from_parent(parent_route);
        self.set_initializers(initializations)?;
        self.check_impurity(original_url)?;
        self.validate()
    }

    /// Set the `process_id` of this function
    pub fn set_id(&mut self, id: usize) {
        self.process_id = id;
    }

    /// Get the `process_id` of this function
    #[must_use]
    pub fn get_id(&self) -> usize {
        self.process_id
    }

    /// Get the name of any associated docs file
    #[must_use]
    pub fn get_docs(&self) -> &str {
        &self.docs
    }

    // Set the id of the parent flow this function is a part of
    fn set_parent_id(&mut self, parent_id: usize) {
        self.parent_id = parent_id;
    }

    /// Get the id of the parent flow this function is a part of
    #[must_use]
    pub fn get_parent_id(&self) -> usize {
        self.parent_id
    }

    /// Return true if this function is impure or not
    #[must_use]
    pub fn is_impure(&self) -> bool {
        self.impure
    }

    // A function can only be impure if it is provided by 'context'
    fn check_impurity(&self, url: &Url) -> Result<()> {
        if self.impure && url.scheme() != "context" {
            bail!("Only functions provided by 'context' can be impure ('{url}')");
        }

        Ok(())
    }

    /// Get a reference to the set of inputs of this function
    #[must_use]
    pub fn get_inputs(&self) -> &IOSet {
        &self.inputs
    }

    /// Get a mutable reference to the set of inputs of this function
    pub fn get_mut_inputs(&mut self) -> &mut IOSet {
        &mut self.inputs
    }

    /// Get a reference to the set of outputs this function generates
    #[must_use]
    pub fn get_outputs(&self) -> IOSet {
        self.outputs.clone()
    }

    /// Add a connection from this function to another
    pub fn add_output_connection(&mut self, output_route: OutputConnection) {
        self.output_connections.push(output_route);
    }

    /// Get a reference to the set of output connections from this function to others
    #[must_use]
    pub fn get_output_connections(&self) -> &Vec<OutputConnection> {
        &self.output_connections
    }

    /// Get a reference to the implementation of this function
    #[must_use]
    pub fn get_implementation(&self) -> &str {
        &self.implementation
    }

    /// Set the implementation location of this function
    pub fn set_implementation(&mut self, implementation: &str) {
        implementation.clone_into(&mut self.implementation);
    }

    /// Set the source field of the function
    pub fn set_source(&mut self, source: &str) {
        source.clone_into(&mut self.source);
    }

    /// Get the name of the source file relative to the function definition
    #[must_use]
    pub fn get_source(&self) -> &str {
        &self.source
    }

    /// Get the source url for the file where this function was defined
    #[must_use]
    pub fn get_source_url(&self) -> &Url {
        &self.source_url
    }

    /// Set the source url where this function is defined
    pub fn set_source_url(&mut self, source_url: &Url) {
        self.source_url = source_url.clone();
    }

    // Set the alias of this function
    fn set_alias(&mut self, alias: &Name) {
        if alias.is_empty() {
            self.alias.clone_from(&self.name);
        } else {
            self.alias.clone_from(alias);
        }
    }

    // Set the InputInitializers on the IOs in an IOSet
    fn set_initializers(
        &mut self,
        initializer_map: &BTreeMap<String, InputInitializer>,
    ) -> Result<()> {
        for (input_name, initializer) in initializer_map {
            // initializer.0 is io name, initializer.1 is the initial value to set it to
            for (index, input) in self.inputs.iter_mut().enumerate() {
                if input.name() == input_name || (input_name.as_str() == "default" && index == 0) {
                    input
                        .set_initializer(Some(initializer.clone()))
                        .chain_err(|| {
                            format!(
                                "Failed to set initializers on IO#{index} on function {}",
                                self.route
                            )
                        })?;
                }
            }
        }
        Ok(())
    }

    /// Set a flow initializer on the specified input
    ///
    /// # Errors
    ///
    /// Will return `Err`if the input with number `io_number` does not exist
    pub fn set_flow_initializer(
        &mut self,
        io_number: usize,
        flow_initializer: Option<InputInitializer>,
    ) -> Result<()> {
        self.inputs
            .get_mut(io_number)
            .ok_or("No such input")?
            .set_flow_initializer(flow_initializer)
    }

    // Set the lib reference of this function
    fn set_lib_reference(&mut self, lib_reference: Option<Url>) {
        self.lib_reference = lib_reference;
    }

    /// Get the lib reference of this function
    #[must_use]
    pub fn get_lib_reference(&self) -> &Option<Url> {
        &self.lib_reference
    }

    // Set the context reference of this function
    fn set_context_reference(&mut self, context_reference: Option<Url>) {
        self.context_reference = context_reference;
    }

    /// Get the context reference of this function
    #[must_use]
    pub fn get_context_reference(&self) -> &Option<Url> {
        &self.context_reference
    }

    /// Convert a `FunctionDefinition` filename into the name of the struct used to implement it
    /// by removing underscores and camel case each word
    /// Example `duplicate_rows` -> `DuplicateRows`
    #[must_use]
    pub fn camel_case(original: &str) -> String {
        // split into parts by '_' and Uppercase the first character of the (ASCII) Struct name
        let words: Vec<String> = original
            .split('_')
            .map(|w| {
                format!(
                    "{}{}",
                    (w.get(..1).unwrap_or("").to_string()).to_uppercase(),
                    w.get(1..).unwrap_or("")
                )
            })
            .collect();
        // recombine
        words.join("")
    }
}

impl Validate for FunctionDefinition {
    fn validate(&self) -> Result<()> {
        self.name.validate()?;

        let mut io_count = 0;

        for i in &self.inputs {
            io_count += 1;
            i.validate()?;
        }

        for i in &self.outputs {
            io_count += 1;
            i.validate()?;
        }

        // A function must have at least one valid input or output
        if io_count == 0 {
            bail!("A function must have at least one input or output");
        }

        Ok(())
    }
}

impl fmt::Display for FunctionDefinition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "name: \t\t{}", self.name)?;
        writeln!(f, "alias: \t\t{}", self.alias)?;
        writeln!(f, "id: \t\t{}", self.process_id)?;
        writeln!(f, "parent_id: \t\t{}", self.parent_id)?;

        writeln!(f, "inputs:")?;
        for input in &self.inputs {
            writeln!(f, "\t{input:#?}")?;
        }

        writeln!(f, "outputs:")?;
        for output in &self.outputs {
            writeln!(f, "\t{output:#?}")?;
        }

        Ok(())
    }
}

impl SetRoute for FunctionDefinition {
    fn set_routes_from_parent(&mut self, parent_route: &Route) {
        self.route = Route::from(format!("{parent_route}/{}", self.alias));
        self.inputs
            .set_io_routes_from_parent(&self.route, IOType::FunctionInput);
        self.outputs
            .set_io_routes_from_parent(&self.route, IOType::FunctionOutput);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod test {
    use url::Url;

    use crate::deserializers::deserializer::get;
    use crate::errors::Result;
    use crate::model::datatype::{DataType, NUMBER_TYPE, STRING_TYPE};
    use crate::model::name::HasName;
    use crate::model::name::Name;
    use crate::model::output_connection::OutputConnection;
    use crate::model::output_connection::Source::Output;
    use crate::model::route::HasRoute;
    use crate::model::route::Route;
    use crate::model::route::SetRoute;
    use crate::model::validation::Validate;

    use super::FunctionDefinition;

    #[test]
    fn function_with_no_io_not_valid() {
        let fun = FunctionDefinition {
            name: Name::from("test_function"),
            alias: Name::from("test_function"),
            output_connections: vec![OutputConnection::new(
                Output("test_function".into()),
                0,
                0,
                0,
                false,
                String::default(),
                #[cfg(feature = "debugger")]
                String::default(),
            )],
            ..Default::default()
        };

        assert!(fun.validate().is_err());
    }

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

    #[test]
    fn deserialize_missing_name() {
        let function_str = "
        type = 'object'
        ";

        let r_f: Result<FunctionDefinition> = toml_from_str(function_str);
        assert!(r_f.is_err());
    }

    #[test]
    fn deserialize_invalid() {
        let function_str = "
        name = 'test_function'
        ";

        let function: Result<FunctionDefinition> = toml_from_str(function_str);
        assert!(function.is_err());
    }

    #[test]
    fn deserialize_no_inputs_or_outputs() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'
        ";

        let function: FunctionDefinition =
            toml_from_str(function_str).expect("Couldn't read function from toml");
        assert!(function.validate().is_err());
    }

    #[test]
    fn deserialize_extra_field_fails() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'
        [[output]]
        foo = 'true'
        ";

        let function: Result<FunctionDefinition> = toml_from_str(function_str);
        assert!(function.is_err());
    }

    #[test]
    fn impure_not_allowed() {
        let function_str = "
        function = 'disallowed_impure'
        source = 'disallowed_impure.rs'
        docs = 'disallowed_impure.md'
        type = 'rust'
        impure = true

        [[input]]
        name = 'left'
        type = 'number'
        ";

        let function = toml_from_str(function_str).expect("Couldn't load function from toml");
        assert!(function.check_impurity(function.get_source_url()).is_err());
    }

    #[test]
    fn deserialize_default_output() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'
        [[output]]
        type = 'string'
        ";

        let function: FunctionDefinition =
            toml_from_str(function_str).expect("Couldn't read function from toml");
        function.validate().expect("Function did not validate");
        assert!(!function.outputs.is_empty());
        let output = &function
            .outputs
            .first()
            .expect("Could not get first output");
        assert_eq!(*output.name(), Name::default());
        assert_eq!(output.datatypes().len(), 1);
        assert_eq!(
            output.datatypes().first(),
            Some(&DataType::from(STRING_TYPE))
        );
    }

    #[test]
    fn deserialize_output_specified() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'

        [[output]]
        name = 'sub_output'
        type = 'string'
        ";

        let function: FunctionDefinition =
            toml_from_str(function_str).expect("Could not deserialize function from toml");
        function.validate().expect("Function does not validate");
        assert!(!function.outputs.is_empty());
        let output = &function
            .outputs
            .first()
            .expect("Could not get first output");
        assert_eq!(*output.name(), Name::from("sub_output"));
        assert_eq!(output.datatypes().len(), 1);
        assert_eq!(
            output.datatypes().first(),
            Some(&DataType::from(STRING_TYPE))
        );
    }

    #[test]
    fn deserialize_two_outputs_specified() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'

        [[output]]
        name = 'sub_output'
        type = 'string'
        [[output]]
        name = 'other_output'
        type = 'number'
        ";

        let function: FunctionDefinition =
            toml_from_str(function_str).expect("Couldn't read function from toml");
        function.validate().expect("Function didn't validate");
        assert!(!function.outputs.is_empty());
        let outputs = function.outputs;
        assert_eq!(outputs.len(), 2);
        let output_0 = &outputs.first().expect("Could not get first output");
        assert_eq!(*output_0.name(), Name::from("sub_output"));
        assert_eq!(output_0.datatypes().len(), 1);
        assert_eq!(
            output_0.datatypes().first(),
            Some(&DataType::from(STRING_TYPE))
        );
        let output_1 = &outputs.get(1).expect("Could nopt get output[1]");
        assert_eq!(*output_1.name(), Name::from("other_output"));
        assert_eq!(output_1.datatypes().len(), 1);
        assert_eq!(
            output_1.datatypes().first(),
            Some(&DataType::from(NUMBER_TYPE))
        );
    }

    #[test]
    fn set_routes() {
        let function_str = "
        function = 'test_function'
        source = 'test.rs'

        [[output]]
        name = 'sub_output'
        type = 'string'
        [[output]]
        name = 'other_output'
        type = 'number'
        ";

        // Setup
        let mut function: FunctionDefinition =
            toml_from_str(function_str).expect("Couldn't read function from toml");
        function.alias = Name::from("test_alias");

        // Test
        function.set_routes_from_parent(&Route::from("/flow"));

        assert_eq!(function.route, Route::from("/flow/test_alias"));

        let output0 = &function
            .outputs
            .first()
            .expect("Could not get first output");
        assert_eq!(*output0.route(), Route::from("/flow/test_alias/sub_output"));

        let output1 = &function.outputs.get(1).expect("Could not get output[1]");
        assert_eq!(
            *output1.route(),
            Route::from("/flow/test_alias/other_output")
        );
    }

    #[test]
    fn runtime_fields_not_serialized() {
        let mut func = FunctionDefinition {
            name: "test".into(),
            source: "test.rs".into(),
            ..FunctionDefinition::default()
        };
        func.alias = "my_alias".into();
        func.set_source_url(&Url::parse("file:///tmp/test.toml").expect("valid url"));
        func.route = Route::from("/flow/my_alias");
        func.implementation = "test.wasm".into();
        func.lib_reference = Some(Url::parse("lib://testlib").expect("valid url"));
        func.context_reference = Some(Url::parse("context://stdio").expect("valid url"));
        func.set_id(42);

        let serialized = toml::to_string(&func).expect("serialization failed");
        assert!(
            !serialized.contains("alias"),
            "alias should not be serialized"
        );
        assert!(
            !serialized.contains("source_url"),
            "source_url should not be serialized"
        );
        assert!(
            !serialized.contains("route"),
            "route should not be serialized"
        );
        assert!(
            !serialized.contains("implementation"),
            "implementation should not be serialized"
        );
        assert!(
            !serialized.contains("lib_reference"),
            "lib_reference should not be serialized"
        );
        assert!(
            !serialized.contains("context_reference"),
            "context_reference should not be serialized"
        );
        assert!(
            !serialized.contains("output_connections"),
            "output_connections should not be serialized"
        );
        assert!(
            !serialized.contains("process_id"),
            "process_id should not be serialized"
        );
        assert!(
            !serialized.contains("parent_id"),
            "parent_id should not be serialized"
        );
        assert!(
            serialized.contains("function = \"test\""),
            "name should be serialized"
        );
        assert!(
            serialized.contains("source = \"test.rs\""),
            "source should be serialized"
        );
    }
}