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
use std::collections::BTreeMap;
use std::fmt;

use serde_derive::{Deserialize, Serialize};

use crate::errors::*;
use crate::model::input::InputInitializer;
use crate::model::name::HasName;
use crate::model::name::Name;
use crate::model::validation::Validate;

/// A `ProcessReference` is the struct used in a `Flow` to refer to a sub-process (Function or nested
/// Flow) it contains
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct ProcessReference {
    /// A reference may have an alias - this is used when multiple instances of the same Process
    /// are referenced from within a flow - they need difference aliases to distinguish between them
    /// in connections to/from them
    #[serde(default = "Name::default")]
    pub alias: Name,
    /// Relative or absolute source of the referenced process
    pub source: String,
    /// When a process is references, each reference can set different initial values on the inputs
    /// of the referenced process.
    #[serde(default, rename = "input")]
    pub initializations: BTreeMap<String, InputInitializer>,
}

impl ProcessReference {
    /// if the ProcessRef does not specify an alias for the process to be loaded
    /// then set the alias to be the name of the loaded process
    pub fn set_alias(&mut self, alias: &Name) {
        if self.alias.is_empty() {
            self.alias = alias.to_owned();
        }
    }
}

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

impl Validate for ProcessReference {
    fn validate(&self) -> Result<()> {
        self.alias.validate()
    }
}

impl fmt::Display for ProcessReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "\t\t\t\talias: {}\n\t\t\t\t\tsource: {}\n\t\t\t\t\tURL: {}\n",
            self.alias, self.source, self.source
        )
    }
}

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

    use crate::deserializers::deserializer::get_deserializer;
    use crate::errors::*;
    use crate::model::input::InputInitializer::{Always, Once};

    use super::ProcessReference;

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

    #[test]
    fn deserialize_simple() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        ";

        let _reference: ProcessReference =
            toml_from_str(input_str).expect("Could not deserialize ProcessReference from toml");
    }

    #[test]
    fn deserialize_with_once_input_initialization() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        input.input1 = {once = 1}
        ";

        let reference: ProcessReference =
            toml_from_str(input_str).expect("Could not deserialize ProcessReference from toml");
        assert_eq!(
            reference.initializations.len(),
            1,
            "Incorrect number of Input initializations parsed"
        );
        match reference.initializations.get("input1").expect("Could not get input") {
            Always(_) => panic!("Should have been a Once initializer"),
            Once(value) => assert_eq!(&json!(1), value, "input1 should be initialized to 1"),
        }
    }

    /*
        For completeness I test the alternative format of expressing the table, but I prefer to use
        and will document the inline table that is tested below.
    */
    #[test]
    fn deserialize_with_constant_input_initialization() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        input.input1 = {always = 1}
        ";

        let reference: ProcessReference =
            toml_from_str(input_str).expect("Could not deserialize ProcessReference from toml");
        assert_eq!(
            reference.initializations.len(),
            1,
            "Incorrect number of Input initializations parsed"
        );
        match reference.initializations.get("input1") {
            Some(Always(value)) => {
                assert_eq!(&json!(1), value, "input1 should be initialized to 1")
            }
            _ => panic!("Should have been a Constant initializer"),
        }
    }

    #[test]
    fn deserialize_with_constant_input_initialization_inline_table() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        input.input1 = { always = 1 }
        ";

        let reference: ProcessReference =
            toml_from_str(input_str).expect("Could not deserialize ProcessReference from toml");
        assert_eq!(
            reference.initializations.len(),
            1,
            "Incorrect number of Input initializations parsed"
        );
        match reference.initializations.get("input1") {
            Some(Always(value)) => {
                assert_eq!(&json!(1), value, "input1 should be initialized to 1")
            }
            _ => panic!("Should have been an Always initializer"),
        }
    }

    #[test]
    fn deserialize_with_multiple_input_initialization() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        input.input1 = {once = 1}
        input.input2 = {once = 'hello'}
        ";

        let reference: ProcessReference =
            toml_from_str(input_str).expect("Could not deserialize ProcessReference from toml");
        assert_eq!(
            reference.initializations.len(),
            2,
            "Incorrect number of Input initializations parsed"
        );
        match reference.initializations.get("input1") {
            Some(Once(value)) => assert_eq!(&json!(1), value, "input1 should be initialized to 1"),
            _ => panic!("Should have been a Once initializer"),
        }

        match reference.initializations.get("input2") {
            Some(Once(value)) => {
                assert_eq!("hello", value, "input2 should be initialized to 'hello'")
            }
            _ => panic!("Should have been a Once initializer"),
        }
    }

    #[test]
    fn deserialize_extra_field_fails() {
        let input_str = "
        alias = 'other'
        source = 'other.toml'
        foo = 'extra token'
        ";

        let reference: Result<ProcessReference> = toml_from_str(input_str);
        assert!(reference.is_err());
    }
}