flowrlib 0.8.3

The runtime library for executing 'flow' programs compiled with the 'flowc' compiler
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
#[cfg(feature = "debugger")]
use std::fmt;
use std::sync::Arc;

use flow_impl::{Implementation, RunAgain};
use log::{debug, error};
use serde_derive::{Deserialize, Serialize};
use serde_json::json;
use serde_json::Value;

use crate::input::Input;

#[derive(Deserialize, Serialize, Clone)]
/// `Function` contains all the information needed about a fubction and its implementation
/// to be able to execute a flow using it.
pub struct Function {
    #[cfg(feature = "debugger")]
    #[serde(default, skip_serializing_if = "String::is_empty")]
    name: String,

    #[cfg(feature = "debugger")]
    #[serde(default, skip_serializing_if = "String::is_empty")]
    route: String,

    id: usize,

    implementation_location: String,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    inputs: Vec<Input>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    output_routes: Vec<(String, usize, usize)>,

    #[serde(skip)]
    #[serde(default = "Function::default_implementation")]
    implementation: Arc<dyn Implementation>,
}

#[derive(Debug)]
struct ImplementationNotFound;

impl Implementation for ImplementationNotFound {
    fn run(&self, _inputs: Vec<Vec<Value>>) -> (Option<Value>, RunAgain) {
        error!("Implementation not found");
        (None, false)
    }
}

#[cfg(feature = "debugger")]
impl fmt::Display for Function {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Function #{} '{}'\n", self.id, self.name)?;
        for (number, input) in self.inputs.iter().enumerate() {
            if input.is_empty() {
                write!(f, "\tInput :{} empty\n", number)?;
            } else {
                write!(f, "\tInput :{} {}\n", number, input)?;
            }
        }
        for output_route in &self.output_routes {
            write!(f, "\tOutput route '/{}' -> {}:{}\n", output_route.0, output_route.1, output_route.2)?;
        }
        write!(f, "")
    }
}

impl Function {
    /// Create a new `fubction` with the specified `name`, `route`, `implemenation` etc.
    /// This only needs to be used by compilers or IDE generating `manifests` with functions
    /// The runtime library `flowrlib` just deserializes them from the `manifest`
    pub fn new(name: String,
               route: String,
               implementation_location: String,
               inputs: Vec<Input>,
               id: usize,
               output_routes: &Vec<(String, usize, usize)>) -> Function {
        Function {
            name,
            route,
            id,
            implementation_location,
            implementation: Function::default_implementation(),
            output_routes: (*output_routes).clone(),
            inputs,
        }
    }

    #[cfg(feature = "debugger")]
    /// Reset a `Function` to initial state. Used by a debugger at runtime to reset a fubction
    /// as part of a whole flow reset to run it again.
    pub fn reset(&mut self) {
        for input in &mut self.inputs {
            input.reset();
        }
    }

    /// A default `Function` - used in deserialization of a `Manifest`
    pub fn default_implementation() -> Arc<dyn Implementation> {
        Arc::new(super::function::ImplementationNotFound {})
    }

    /// Accessor for a `Functions` `name`
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Accessor for a `Functions` `id`
    pub fn id(&self) -> usize {
        self.id
    }

    /// Initialize all of a `Functions` `Inputs` - as they may have initializers that need running
    pub fn init_inputs(&mut self, first_time: bool) -> Vec<usize> {
        let mut refilled = vec!();
        for (io_number, input) in &mut self.inputs.iter_mut().enumerate() {
            if input.init(first_time) {
                refilled.push(io_number);
            }
        }
        refilled
    }

    /// Accessor for a `Functions` `implementation_location`
    pub fn implementation_location(&self) -> &str {
        &self.implementation_location
    }

    /// write a value to a `Functions` input -
    /// The value being written maybe an Array of values, in which case if the destination input does
    /// not accept Array, then iterate over the contents of the array and send each one to the
    /// input individually
    pub fn write_input(&mut self, input_number: usize, input_value: &Value) {
        let input = &mut self.inputs[input_number];
        if input_value.is_array() {
            // Serialize Array value into the non-Array input
            if !input.is_array {
                debug!("Serializing Array value to non-Array input");
                for value in input_value.as_array().unwrap().iter() {
                    input.push(value.clone());
                }
            } else {
                // Send Array value to the Array input
                input.push(input_value.clone());
            }
        } else {
            if input.is_array {
                // Send Non-Array value to the Array input
                input.push(json!([input_value]));
            } else {
                // Send Non-Array value to Non-Array input
                input.push(input_value.clone());
            }
        }
    }

    /// Accessor for a `Functions` `output_routes` field
    pub fn output_destinations(&self) -> &Vec<(String, usize, usize)> {
        &self.output_routes
    }

    /// Get a clone of the `Functions` `implementation`
    pub fn get_implementation(&self) -> Arc<dyn Implementation> {
        self.implementation.clone()
    }

    /// Set a `Functions` `implementation`
    pub fn set_implementation(&mut self, implementation: Arc<dyn Implementation>) {
        self.implementation = implementation;
    }

    /// Determine if the `Functions` `input` number `input_number` is full or not
    pub fn input_full(&self, input_number: usize) -> bool {
        self.inputs[input_number].full()
    }

    /// Determine if all of the `Functions` `inputs` are full and this function can be run
    pub fn inputs_full(&self) -> bool {
        for input in &self.inputs {
            if !input.full() {
                return false;
            }
        }

        return true;
    }

    #[cfg(feature = "debugger")]
    /// Inpect the values of the `inputs` of a feature. Only used by the `debugger` feature
    pub fn inputs(&self) -> &Vec<Input> {
        &self.inputs
    }

    /// Read the values from the inputs and return them for use in executing the function
    pub fn take_input_set(&mut self) -> Vec<Vec<Value>> {
        let mut input_set: Vec<Vec<Value>> = Vec::new();
        for input in &mut self.inputs {
            input_set.push(input.take());
        }
        input_set
    }
}

#[cfg(test)]
mod test {
    use std::sync::Arc;

    use flow_impl::Implementation;
    use serde_json::json;
    use serde_json::value::Value;

    use crate::input::Input;

    use super::Function;
    use super::ImplementationNotFound;

    /*************** Below are tests for basic json.pointer functionality *************************/

    #[test]
    fn destructure_output_base_route() {
        let json = json!("simple");
        assert_eq!("simple", json.pointer("").unwrap(), "json pointer functionality not working!");
    }

    #[test]
    fn destructure_json_value() {
        let json: Value = json!({ "sub_route": "sub_output" });
        assert_eq!("sub_output", json.pointer("/sub_route").unwrap(), "json pointer functionality not working!");
    }

    #[test]
    fn access_array_elements() {
        let args: Vec<&str> = vec!("arg0", "arg1", "arg2");
        let json = json!(args);
        assert_eq!("arg0", json.pointer("/0").unwrap(), "json pointer array indexing functionality not working!");
        assert_eq!("arg1", json.pointer("/1").unwrap(), "json pointer array indexing functionality not working!");
    }

    /*************** Below are tests for inputs with depth = 1 ***********************/

    #[test]
    fn can_send_simple_object() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        assert_eq!(json!(1), function.take_input_set().remove(0).remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    fn can_send_array_object() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, true)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!([1, 2]));
        assert_eq!(json!([1, 2]), function.take_input_set().remove(0).remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    fn can_send_simple_object_to_array_input() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, true)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        assert_eq!(vec!(json!([1])), function.take_input_set().remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    fn can_send_array_to_simple_object_depth_1() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!([1, 2]));
        assert_eq!(vec!(json!(1)), function.take_input_set().remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    fn can_oversend_inputs() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        function.write_input(0, &json!(2));
        assert_eq!(json!(1), function.take_input_set().remove(0).remove(0),
                   "Value from input set wasn't what was expected");
        assert_eq!(json!(2), function.take_input_set().remove(0).remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    #[should_panic]
    fn cannot_take_input_set_if_not_full() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(1, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.take_input_set().remove(0);
    }

    /*************** Below are tests for inputs with depth > 1 ***********************/

    #[test]
    fn can_send_array_to_simple_object_depth_2() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(2, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!([1, 2]));
        assert_eq!(vec!(json!(1), json!(2)), function.take_input_set().remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    fn can_send_simple_object_when_depth_more_than_1() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(2, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        function.write_input(0, &json!(2));
        assert_eq!(vec!(json!(1), json!(2)), function.take_input_set().remove(0),
                   "Value from input set wasn't the array of numbers expected");
    }

    #[test]
    fn can_send_array_objects_when_input_depth_more_than_1() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(2, &None, true)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!([1, 2]));
        function.write_input(0, &json!([3, 4]));
        assert_eq!(vec!(json!([1, 2]), json!([3, 4])), function.take_input_set().remove(0),
                   "Value from input set wasn't what was expected");
    }

    #[test]
    #[should_panic]
    fn cannot_take_input_set_if_not_full_depth_2() {
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(2, &None, false)),
                                         0,
                                         &vec!());
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        function.take_input_set().remove(0);
    }

    fn test_function() -> Function {
        Function::new("test".to_string(),
                      "/context/test".to_string(),
                      "/implementation".to_string(),
                      vec!(Input::new(2, &None, false)),
                      1,
                      &vec!(("/other/input/1".to_string(), 1, 1)))
    }

    #[cfg(feature = "debugger")]
    #[test]
    fn debugger_can_inspect_non_full_input() {
        let mut function = test_function();
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        assert_eq!(function.inputs().len(), 1, "Could not read incomplete input set");
    }

    #[test]
    fn call_implementation_not_found_panics() {
        let inf = ImplementationNotFound {};
        assert_eq!((None, false), inf.run(vec!()), "ImplementationNotFound should return (None, false)");
    }

    #[cfg(feature = "debugger")]
    #[test]
    fn can_display_function() {
        let function = test_function();
        let _ = format!("{}", function);
    }

    #[cfg(feature = "debugger")]
    #[test]
    fn can_display_function_with_inputs() {
        let output_route = ("/other/input/1".to_string(), 1, 1);
        let mut function = Function::new("test".to_string(),
                                         "/context/test".to_string(),
                                         "/test".to_string(),
                                         vec!(Input::new(2, &None, false)),
                                         0,
                                         &vec!(output_route.clone()));
        function.init_inputs(true);
        function.write_input(0, &json!(1));
        let _ = format!("{}", function);
        assert_eq!(&vec!(output_route), function.output_destinations(),
                   "output routes not as originally set");
    }

    #[test]
    fn can_get_function_name_and_id_and_location() {
        let function = test_function();
        assert_eq!("test".to_string(), function.name());
        assert_eq!(1, function.id());
        assert_eq!("/implementation", function.implementation_location());
    }

    #[test]
    fn can_set_and_get_implementation() {
        let mut function = test_function();
        let inf = Arc::new(ImplementationNotFound {});
        function.set_implementation(inf);
        let _ = function.get_implementation();
    }
}