chord-core 0.1.13

async parallel case executor
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
use std::borrow::Borrow;
use std::collections::HashSet;
use std::time::Duration;

use async_std::path::Path;
use lazy_static::lazy_static;
use regex::Regex;

use crate::flow::Error::EntryLost;
use crate::flow::Error::*;
use crate::value::{Map, Value};

lazy_static! {
    pub static ref ID_PATTERN: Regex = Regex::new(r"^[\w]{1,50}$").unwrap();
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("invalid id `{0}`")]
    IdInvalid(String),
    #[error("duplicated id `{0}`")]
    IdDuplicated(String),
    #[error("{0} lost entry `{1}`")]
    EntryLost(String, String),
    #[error("{0} unexpect entry `{1}`")]
    EntryUnexpected(String, String),
    #[error("{0} must {1} but it {2}")]
    Violation(String, String, String),
    #[error("{0} unexpect value {1}")]
    ValueUnexpected(String, String),
}

#[derive(Debug, Clone)]
pub struct Flow {
    flow: Value,
    meta: Map,
}

impl Flow {
    pub fn new(flow: Value, dir: &Path) -> Result<Flow, Error> {
        let mut meta = Map::new();
        meta.insert(
            "task_dir".to_string(),
            Value::String(dir.to_path_buf().to_str().unwrap().to_string()),
        );

        let flow = Flow { flow, meta };

        flow._root_check()?;
        flow._version()?;

        let mut step_id_checked: HashSet<&str> = HashSet::new();
        let pre_step_id_vec = flow.pre_step_id_vec().unwrap_or(vec![]);
        for pre_step_id in pre_step_id_vec {
            if !ID_PATTERN.is_match(pre_step_id) {
                return Err(IdInvalid(pre_step_id.into()));
            }
            if step_id_checked.contains(pre_step_id) {
                return Err(IdDuplicated(pre_step_id.into()));
            } else {
                step_id_checked.insert(pre_step_id.into());
            }

            flow._pre_check()?;
        }

        let stage_id_vec = flow._stage_id_vec()?;
        if stage_id_vec.is_empty() {
            return Err(EntryLost("root".into(), "stage".into()));
        }

        for stage_id in stage_id_vec {
            if !ID_PATTERN.is_match(stage_id) {
                return Err(IdInvalid(stage_id.into()));
            }

            flow._stage_check(stage_id)?;
            flow._stage_concurrency(stage_id)?;
            flow._stage_duration(stage_id)?;
            flow._stage_round(stage_id)?;
            flow._stage_break_on(stage_id)?;

            let stage_step_id_vec = flow._stage_step_id_vec(stage_id)?;

            if stage_step_id_vec.is_empty() {
                return Err(EntryLost(stage_id.into(), "step".into()));
            }

            for stage_step_id in stage_step_id_vec {
                if !ID_PATTERN.is_match(stage_step_id) {
                    return Err(IdInvalid(stage_step_id.into()));
                }

                if step_id_checked.contains(stage_step_id) {
                    return Err(IdDuplicated(stage_step_id.into()));
                } else {
                    step_id_checked.insert(stage_step_id.into());
                }
            }
        }

        for step_id in step_id_checked.iter() {
            flow._step_check(step_id)?;
            flow._step_exec_check(step_id)?;
            flow._step_spec_check(step_id)?;

            let _ = flow._step_let(step_id)?;
            let _ = flow._step_assert(step_id)?;
            let _ = flow._step_then(step_id)?;
            let _ = flow._step_exec_action(step_id)?;
            let _ = flow._step_exec_args(step_id)?;
            let _ = flow._step_spec_timeout(step_id)?;
            let _ = flow._step_spec_catch_err(step_id)?;
        }

        return Ok(flow);
    }

    pub fn version(&self) -> &str {
        self._version().unwrap()
    }

    pub fn def(&self) -> Option<&Map> {
        self.flow["def"].as_object()
    }

    pub fn meta(&self) -> &Map {
        &self.meta
    }

    pub fn stage_step_id_vec(&self, stage_id: &str) -> Vec<&str> {
        self._stage_step_id_vec(stage_id).unwrap()
    }

    pub fn pre_step_id_vec(&self) -> Option<Vec<&str>> {
        let task_step_chain_arr = self.flow["pre"]["step"]
            .as_object()
            .map(|p| p.keys().map(|k| k.as_str()).collect());
        if task_step_chain_arr.is_none() {
            return None;
        }
        return Some(task_step_chain_arr.unwrap());
    }

    pub fn stage_id_vec(&self) -> Vec<&str> {
        self._stage_id_vec().unwrap()
    }

    pub fn stage_case_name<'a, 's>(&'s self, stage_id: &'a str) -> &'a str
    where
        's: 'a,
    {
        self.flow["stage"][stage_id]["case"]["name"]
            .as_str()
            .unwrap_or(stage_id)
    }

    pub fn stage_concurrency(&self, stage_id: &str) -> usize {
        self._stage_concurrency(stage_id).unwrap()
    }

    pub fn stage_round(&self, stage_id: &str) -> usize {
        self._stage_round(stage_id).unwrap()
    }

    pub fn stage_duration(&self, stage_id: &str) -> Duration {
        self._stage_duration(stage_id).unwrap()
    }

    pub fn stage_break_on(&self, stage_id: &str) -> &str {
        self._stage_break_on(stage_id).unwrap()
    }

    pub fn step_let(&self, step_id: &str) -> Option<&Map> {
        self._step_let(step_id).unwrap()
    }

    pub fn step_exec_action(&self, step_id: &str) -> &str {
        self._step_exec_action(step_id).unwrap()
    }

    pub fn step_exec_args(&self, step_id: &str) -> &Value {
        self._step_exec_args(step_id).unwrap()
    }

    pub fn step_spec_timeout(&self, step_id: &str) -> Duration {
        self._step_spec_timeout(step_id).unwrap()
    }

    pub fn step_spec_catch_err(&self, step_id: &str) -> bool {
        self._step_spec_catch_err(step_id).unwrap()
    }

    pub fn step_assert(&self, step_id: &str) -> Option<&str> {
        self._step_assert(step_id).unwrap()
    }

    pub fn step_then(&self, step_id: &str) -> Option<Vec<&Map>> {
        self._step_then(step_id).unwrap()
    }

    // -----------------------------------------------
    // private

    fn _root_check(&self) -> Result<(), Error> {
        let enable_keys = vec!["version", "def", "stage", "pre"];
        let root = self.flow.borrow();
        let object = root
            .as_object()
            .ok_or_else(|| Violation("root".into(), "be object".into(), "is not".into()))?;
        for (k, _) in object {
            if !enable_keys.contains(&k.as_str()) {
                return Err(EntryUnexpected("root".into(), k.into()));
            }
        }
        return Ok(());
    }

    fn _version(&self) -> Result<&str, Error> {
        let v = self.flow["version"]
            .as_str()
            .ok_or(EntryLost("root".into(), "version".into()))?;

        if v != "0.0.1" {
            return Err(Violation("version".into(), "0.0.1".into(), v.into()));
        } else {
            Ok(v)
        }
    }

    fn _pre_check(&self) -> Result<(), Error> {
        let enable_keys = vec!["step"];
        let pre = self.flow["pre"].borrow();
        let object = pre
            .as_object()
            .ok_or_else(|| Violation("pre".into(), "be object".into(), "is not".into()))?;
        for (k, _) in object {
            if !enable_keys.contains(&k.as_str()) {
                return Err(EntryUnexpected("pre".into(), k.into()));
            }
        }
        return Ok(());
    }

    fn _stage_id_vec(&self) -> Result<Vec<&str>, Error> {
        let step_id_vec = self.flow["stage"]
            .as_object()
            .map(|p| p.keys().map(|k| k.as_str()).collect())
            .ok_or(EntryLost("root".into(), "stage".into()))?;
        return Ok(step_id_vec);
    }

    fn _stage_check(&self, stage_id: &str) -> Result<(), Error> {
        let enable_keys = vec![
            "step",
            "case",
            "concurrency",
            "round",
            "duration",
            "break_on",
        ];
        let stage = self.flow["stage"][stage_id].borrow();
        let object = stage.as_object().ok_or_else(|| {
            Violation(
                format!("stage.{}", stage_id),
                "be object".into(),
                "is not".into(),
            )
        })?;
        for (k, _) in object {
            if !enable_keys.contains(&k.as_str()) {
                return Err(EntryUnexpected(format!("stage.{}", stage_id), k.into()));
            }
        }
        return Ok(());
    }

    fn _stage_concurrency(&self, stage_id: &str) -> Result<usize, Error> {
        let s = self.flow["stage"][stage_id]["concurrency"].as_u64();
        if s.is_none() {
            return Ok(10);
        }

        let s = s.unwrap();
        if s < 1 {
            return Err(Violation(
                format!("stage.{}.concurrency", stage_id),
                "> 0".into(),
                format!("is {}", s),
            ));
        }
        Ok(s as usize)
    }

    fn _stage_round(&self, stage_id: &str) -> Result<usize, Error> {
        let s = self.flow["stage"][stage_id]["round"].as_u64();
        if s.is_none() {
            return Ok(1);
        }

        let s = s.unwrap();
        if s < 1 {
            return Err(Violation(
                format!("stage.{}.round", stage_id),
                "> 0".into(),
                format!("is {}", s),
            ));
        }
        Ok(s as usize)
    }

    fn _stage_duration(&self, stage_id: &str) -> Result<Duration, Error> {
        let s = self.flow["stage"][stage_id]["duration"].as_u64();
        if s.is_none() {
            return Ok(Duration::from_secs(600));
        }

        let s = s.unwrap();
        if s < 1 {
            return Err(Violation(
                format!("stage.{}.duration", stage_id),
                "> 0".into(),
                format!("is {}", s),
            ));
        }
        Ok(Duration::from_secs(s))
    }

    fn _stage_break_on(&self, stage_id: &str) -> Result<&str, Error> {
        let break_on = self.flow["stage"][stage_id]["break_on"]
            .as_str()
            .unwrap_or("stage_fail");
        match break_on {
            "never" => Ok(break_on),
            "stage_fail" => Ok(break_on),
            o => Err(ValueUnexpected(
                format!("stage.{}.break_on", stage_id),
                o.into(),
            )),
        }
    }

    fn _stage_step_id_vec(&self, stage_id: &str) -> Result<Vec<&str>, Error> {
        let step_id_vec = self.flow["stage"][stage_id]["step"]
            .as_object()
            .map(|p| p.keys().map(|k| k.as_str()).collect())
            .ok_or(EntryLost(stage_id.into(), "step".into()))?;
        return Ok(step_id_vec);
    }

    fn _step_check(&self, step_id: &str) -> Result<(), Error> {
        let enable_keys = vec!["let", "spec", "exec", "assert", "then"];
        let step = self._step(step_id);
        let object = step.as_object().ok_or_else(|| {
            Violation(
                format!("step.{}", step_id),
                "be object".into(),
                "is not".into(),
            )
        })?;
        for (k, _) in object {
            if !enable_keys.contains(&k.as_str()) {
                return Err(EntryUnexpected(format!("step.{}", step_id), k.into()));
            }
        }
        return Ok(());
    }

    fn _step(&self, step_id: &str) -> &Value {
        for stage_id in self.stage_id_vec() {
            let step = self.flow["stage"][stage_id]["step"][step_id].borrow();
            if !step.is_null() {
                return step;
            }
        }

        return self.flow["pre"]["step"][step_id].borrow();
    }

    fn _step_let(&self, step_id: &str) -> Result<Option<&Map>, Error> {
        let lv = &self._step(step_id)["let"];
        if lv.is_null() {
            return Ok(None);
        }
        lv.as_object()
            .map(|o| Some(o))
            .ok_or(EntryLost(format!("step.{}", step_id), "let".into()))
    }

    fn _step_exec_check(&self, step_id: &str) -> Result<(), Error> {
        let exec = self._step(step_id)["exec"].as_object().ok_or(Violation(
            step_id.into(),
            "be object".into(),
            "is not".into(),
        ))?;

        if exec.is_empty() {
            return Err(EntryLost(format!("step.{}", step_id), "exec.action".into()));
        }

        if exec.len() != 1 {
            return Err(Violation(
                format!("step.{}.exec.action", step_id),
                "have only 1 entry".into(),
                format!("has {}", exec.len()),
            ));
        }

        Ok(())
    }

    fn _step_exec_action(&self, step_id: &str) -> Result<&str, Error> {
        let exec = &self._step(step_id)["exec"].as_object().ok_or(Violation(
            format!("step.{}.exec.action", step_id),
            "be object".into(),
            "is not".into(),
        ))?;

        return exec
            .keys()
            .nth(0)
            .map(|s| s.as_str())
            .ok_or(EntryLost(format!("step.{}", step_id), "exec.action".into()));
    }

    pub fn _step_exec_args(&self, step_id: &str) -> Result<&Value, Error> {
        let action = self._step_exec_action(step_id)?;
        let args = &self._step(step_id)["exec"][action];
        return if args.is_null() {
            Err(EntryLost(format!("step.{}", step_id), "exec.args".into()))
        } else {
            Ok(args)
        };
    }

    fn _step_spec_check(&self, step_id: &str) -> Result<(), Error> {
        let spec = self._step(step_id)["spec"].borrow();
        if spec.is_null() {
            return Ok(());
        } else {
            let enable_keys = vec!["timeout", "catch_err"];
            let object = spec.as_object().ok_or(Violation(
                format!("step.{}.spec", step_id),
                "be object".into(),
                "is not".into(),
            ))?;

            for (k, _) in object {
                if !enable_keys.contains(&k.as_str()) {
                    return Err(EntryUnexpected(format!("step.{}", step_id), k.into()));
                }
            }

            Ok(())
        }
    }

    fn _step_spec_timeout(&self, step_id: &str) -> Result<Duration, Error> {
        let s = self._step(step_id)["spec"]["timeout"].as_u64();
        if s.is_none() {
            return Ok(Duration::from_secs(60));
        }

        let s = s.unwrap();
        if s < 1 {
            return Err(Violation(
                format!("step.{}.spec.timeout", step_id),
                "> 0".into(),
                format!("is {}", s),
            ));
        }
        Ok(Duration::from_secs(s))
    }

    fn _step_spec_catch_err(&self, step_id: &str) -> Result<bool, Error> {
        Ok(self._step(step_id)["spec"]["catch_err"]
            .as_bool()
            .unwrap_or(false))
    }

    pub fn _step_assert(&self, step_id: &str) -> Result<Option<&str>, Error> {
        match &self._step(step_id)["assert"] {
            Value::Null => Ok(None),
            Value::String(s) => Ok(Some(s.as_str())),
            _ => {
                return Err(Violation(
                    format!("step.{}.assert", step_id),
                    "be string".into(),
                    "is not".into(),
                ));
            }
        }
    }

    pub fn _step_then(&self, step_id: &str) -> Result<Option<Vec<&Map>>, Error> {
        let array = self._step(step_id)["then"].as_array();
        if array.is_none() {
            return Ok(None);
        } else {
            let array = array.unwrap();
            Ok(Some(
                array
                    .iter()
                    .filter(|v| v.is_object())
                    .map(|m| m.as_object().unwrap())
                    .collect(),
            ))
        }
    }
}