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
use std::borrow::Cow;
use std::fmt;

use serde_derive::{Deserialize, Serialize};
use shrinkwraprs::Shrinkwrap;

use crate::compiler::loader::Validate;
use crate::errors::*;
use crate::model::io::IOType;
use crate::model::name::Name;

/// A `Route` is a String that refers to a particular location within the flow hierarchy
/// and can be used to locate a function, flow, input or output uniquely
#[derive(Shrinkwrap, Hash, Debug, PartialEq, Clone, Default, Serialize, Deserialize, Eq)]
#[shrinkwrap(mutable)]
pub struct Route(pub String);

/// A `Route` can be of various Types
pub enum RouteType {
    /// The route refers to an input of a Process
    Input(Name, Route),
    /// The Route refers to the output of a Process
    Output(Name),
    /// The route is internal to a Process
    Internal(Name, Route),
    /// The route is invalid (needed for errors during deserialization)
    Invalid(String),
}

/// `Route` is used to locate Processes (Flows or Functions), their IOs and sub-elements of a
/// data structure within the flow hierarchy
///
/// Examples
/// "/my-flow" -> The flow called "my-flow, anchored at the root of the hierarchy, i.e. the context
/// "/my-flow/sub-flow" -> A flow called "sub-flow" that is within "my-flow"
/// "/my-flow/sub-flow/function" -> A function called "function" within "sub-flow"
/// "/my-flow/sub-flow/function/input_1" -> An IO called "input_1" of "function"
/// "/my-flow/sub-flow/function/input_1/1" -> An array element at index 1 of the Array output from "input_1"
/// "/my-flow/sub-flow/function/input_2/part_a" -> A part of the Json structure output by "input_2" called "part_a"
impl Route {
    /// `sub_route_of` returns an Option<Route> indicating if `self` is a subroute of `other`
    /// (i.e. `self` is a longer route to an element under the `other` route)
    /// Return values
    ///     None                    - `self` is not a sub-route of `other`
    ///     (e.g. ("/my-route1", "/my-route2")
    ///     (e.g. ("/my-route1", "/my-route1/something")
    ///     Some(Route::from(""))   - `self` and `other` are equal
    ///     (e.g. ("/my-route1", "/my-route1")
    ///     Some(Route::from(diff)) - `self` is a sub-route of `other` - with `diff` added
    ///     (e.g. ("/my-route1/something", "/my-route1")
    pub fn sub_route_of(&self, other: &Route) -> Option<Route> {
        if self == other {
            return Some(Route::from(""));
        }

        self.strip_prefix(&format!("{}/", other)).map(Route::from)
    }

    /// Insert another Route at the front of this Route
    pub fn insert<R: AsRef<str>>(&mut self, sub_route: R) -> &Self {
        self.insert_str(0, sub_route.as_ref());
        self
    }

    /// Extend a Route by appending another Route to the end, adding the '/' separator if needed
    pub fn extend(&mut self, sub_route: &Route) -> &Self {
        if !sub_route.is_empty() {
            if !self.to_string().ends_with('/') && !sub_route.starts_with('/') {
                self.push('/');
            }
            self.push_str(sub_route);
        }

        self
    }

    /// Return the type of this Route
    pub fn route_type(&self) -> RouteType {
        let segments: Vec<&str> = self.split('/').collect();

        match segments[0] {
            "input" => RouteType::Input(segments[1].into(), segments[2..].join("/").into()),
            "output" => RouteType::Output(segments[1].into()),
            "" => RouteType::Invalid(
                "'input' or 'output' or valid process name must be specified in route".into(),
            ),
            process_name => {
                RouteType::Internal(process_name.into(), segments[1..].join("/").into())
            }
        }
    }

    /// Return a route that is one level up, such that
    ///     `/context/function/output/subroute -> /context/function/output`
    pub fn pop(&self) -> (Cow<Route>, Option<Route>) {
        let mut segments: Vec<&str> = self.split('/').collect();
        let sub_route = segments.pop();
        match sub_route {
            None => (Cow::Borrowed(self), None),
            Some("") => (Cow::Borrowed(self), None),
            Some(sr) => (
                Cow::Owned(Route::from(segments.join("/"))),
                Some(Route::from(sr)),
            ),
        }
    }

    /// Return the io route without a trailing number (array index) and if it has one or not
    /// If the trailing number was present then return the route with a trailing '/'
    pub fn without_trailing_array_index(&self) -> (Cow<Route>, usize, bool) {
        let mut parts: Vec<&str> = self.split('/').collect();
        if let Some(last_part) = parts.pop() {
            if let Ok(index) = last_part.parse::<usize>() {
                let route_without_number = parts.join("/");
                return (Cow::Owned(Route::from(route_without_number)), index, true);
            }
        }

        (Cow::Borrowed(self), 0, false)
    }
}

impl AsRef<str> for Route {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Validate for Route {
    fn validate(&self) -> Result<()> {
        if let RouteType::Invalid(error) = self.route_type() {
            bail!("{}", error);
        }

        if self.parse::<usize>().is_ok() {
            bail!("Route '{}' is invalid - cannot be an integer", self);
        }

        Ok(())
    }
}

/// A trait implemented by objects that have Routes
pub trait HasRoute {
    /// Return a reference to the Route of the struct that implements this trait
    fn route(&self) -> &Route;
    /// Return a mutable reference to the Route of the struct that implements this trait
    fn route_mut(&mut self) -> &mut Route;
}

/// Some structs with Routes will be able to have their route set by using parent route
pub trait SetRoute {
    /// Set the routes in fields of this struct based on the route of it's parent.
    fn set_routes_from_parent(&mut self, parent: &Route);
}

/// structs with IOs will be able to have the IOs routes set by using parent route
#[allow(clippy::upper_case_acronyms)]
pub trait SetIORoutes {
    /// Set the route and IO type of IOs in this struct based on parent's route
    fn set_io_routes_from_parent(&mut self, parent: &Route, io_type: IOType);
}

impl fmt::Display for Route {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for Route {
    fn from(string: &str) -> Self {
        Route(string.to_string())
    }
}

impl From<String> for Route {
    fn from(string: String) -> Self {
        Route(string)
    }
}

impl From<&String> for Route {
    fn from(string: &String) -> Self {
        Route(string.to_string())
    }
}

impl From<&Name> for Route {
    fn from(name: &Name) -> Self {
        Route(name.to_string())
    }
}

#[cfg(test)]
mod test {
    use crate::compiler::loader::Validate;
    use crate::model::name::Name;

    use super::Route;

    #[test]
    fn test_from_string() {
        let route = Route::from("my-route".to_string());
        assert_eq!(route, Route::from("my-route"));
    }

    #[test]
    fn test_from_ref_string() {
        let route = Route::from(&format!("{}{}", "my-route", "/subroute"));
        assert_eq!(route, Route::from("my-route/subroute"));
    }

    #[test]
    fn test_from_name() {
        let name = Name::from("my-route-name");
        assert_eq!(Route::from(&name), Route::from("my-route-name"));
    }

    #[test]
    fn test_route_pop() {
        let original = Route::from("/context/function/output/subroute");
        let (level_up, sub) = original.pop();
        assert_eq!(
            level_up.into_owned(),
            Route::from("/context/function/output")
        );
        assert_eq!(sub, Some(Route::from("subroute")));
    }

    #[test]
    fn test_root_route_pop() {
        let original = Route::from("/");
        let (level_up, sub) = original.pop();
        assert_eq!(level_up.into_owned(), Route::from("/"));
        assert_eq!(sub, None);
    }

    #[test]
    fn test_empty_route_pop() {
        let original = Route::from("");
        let (level_up, sub) = original.pop();
        assert_eq!(level_up.into_owned(), Route::from(""));
        assert_eq!(sub, None);
    }

    #[test]
    fn no_path_no_change() {
        let route = Route::from("");
        let (new_route, _num, trailing_number) = route.without_trailing_array_index();
        assert_eq!(new_route.into_owned(), Route::default());
        assert!(!trailing_number);
    }

    #[test]
    fn just_slash_no_change() {
        let route = Route::from("/");
        let (new_route, _num, trailing_number) = route.without_trailing_array_index();
        assert_eq!(new_route.into_owned(), Route::from("/"));
        assert!(!trailing_number);
    }

    #[test]
    fn no_trailing_number_no_change() {
        let route = Route::from("/output1");
        let (new_route, _num, trailing_number) = route.without_trailing_array_index();
        assert_eq!(new_route.into_owned(), route);
        assert!(!trailing_number);
    }

    #[test]
    fn detect_array_at_output_root() {
        let route = Route::from("/0");
        let (new_route, num, trailing_number) = route.without_trailing_array_index();
        assert_eq!(new_route.into_owned(), Route::from(""));
        assert_eq!(num, 0);
        assert!(trailing_number);
    }

    #[test]
    fn detect_array_at_output_subroute() {
        let route = Route::from("/array_output/0");
        let (new_route, num, trailing_number) = route.without_trailing_array_index();
        assert_eq!(new_route.into_owned(), Route::from("/array_output"));
        assert_eq!(num, 0);
        assert!(trailing_number);
    }

    #[test]
    fn valid_process_route() {
        let route = Route::from("sub_process/i1");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn valid_process_route_with_subroute() {
        let route = Route::from("sub_process/i1/sub_route");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn valid_input_route() {
        let route = Route::from("input/i1");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn valid_input_route_with_subroute() {
        let route = Route::from("input/i1/sub_route");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn valid_output_route() {
        let route = Route::from("output/i1");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn valid_output_route_with_subroute() {
        let route = Route::from("output/i1/sub_route");
        assert!(route.validate().is_ok());
    }

    #[test]
    fn validate_invalid_empty_route() {
        let route = Route::from("");
        assert!(route.validate().is_err());
    }

    #[test]
    fn validate_invalid_route() {
        let route = Route::from("123");
        assert!(route.validate().is_err());
    }

    #[test]
    fn subroute_equal_route() {
        let route = Route::from("/context/function");
        assert!(route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn subroute_distinct_route() {
        let route = Route::from("/context/function");
        assert!(!route.sub_route_of(&Route::from("/context/foo")).is_some())
    }

    #[test]
    fn subroute_extended_name_route() {
        let route = Route::from("/context/function_foo");
        assert!(!route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn is_a_subroute() {
        let route = Route::from("/context/function/input");
        assert!(route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn is_a_sub_subroute() {
        let route = Route::from("/context/function/input/element");
        assert!(route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn is_array_element_subroute() {
        let route = Route::from("/context/function/1");
        assert!(route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn is_array_element_sub_subroute() {
        let route = Route::from("/context/function/input/1");
        assert!(route
            .sub_route_of(&Route::from("/context/function"))
            .is_some())
    }

    #[test]
    fn extend_empty_route() {
        let mut route = Route::default();

        route.extend(&Route::from("sub"));
        assert_eq!(route, Route::from("/sub"));
    }

    #[test]
    fn extend_root_route() {
        let mut route = Route::from("/");

        route.extend(&Route::from("sub"));
        assert_eq!(route, Route::from("/sub"));
    }

    #[test]
    fn extend_route() {
        let mut route = Route::from("/context/function");

        route.extend(&Route::from("sub"));
        assert_eq!(route, Route::from("/context/function/sub"));
    }

    #[test]
    fn extend_route_with_nothing() {
        let mut route = Route::from("/context/function");

        route.extend(&Route::from(""));
        assert_eq!(route, Route::from("/context/function"));
    }
}