pipebuilder_common 0.2.2

lib for pipebuilder components
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
use crate::{
    append_dot_format_suffix, create_directory, invalid_catalog_name, json_schema_error,
    write_file, BlobResource, Resource, ResourceType, Result, Snapshot,
};
use chrono::{DateTime, Utc};
use jsonschema::JSONSchema;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
};

#[derive(Serialize, Deserialize)]
pub struct CatalogSchemaMetadata {
    // pull count
    pub pulls: u64,
    // catalog schema file size in byte
    pub size: usize,
    // created timestamp
    pub created: DateTime<Utc>,
}

impl BlobResource for CatalogSchemaMetadata {
    fn incr_usage(&mut self) {
        self.pulls += 1
    }

    fn new(size: usize) -> Self {
        CatalogSchemaMetadata {
            pulls: 0,
            size,
            created: Utc::now(),
        }
    }
}

impl Resource for CatalogSchemaMetadata {
    fn ty() -> ResourceType {
        ResourceType::CatalogSchemaMetadata
    }
}

#[derive(Serialize, Deserialize)]
pub struct CatalogSchemaSnapshot {
    pub latest_version: u64,
}

impl CatalogSchemaSnapshot {
    pub fn new() -> Self {
        CatalogSchemaSnapshot { latest_version: 0 }
    }
}

impl Default for CatalogSchemaSnapshot {
    fn default() -> Self {
        Self::new()
    }
}

impl Snapshot for CatalogSchemaSnapshot {
    fn incr_version(&mut self) {
        self.latest_version += 1
    }
    fn get_version(&self) -> u64 {
        self.latest_version
    }
}

impl Resource for CatalogSchemaSnapshot {
    fn ty() -> ResourceType {
        ResourceType::CatalogSchemaSnapshot
    }
}

#[derive(Serialize, Deserialize)]
pub struct CatalogSchemaMetadataKey {
    pub namespace: String,
    pub id: String,
    pub version: u64,
}

// Pipe configuration
#[derive(Serialize, Deserialize)]
pub struct Catalog {
    // schema info
    pub schema: CatalogSchemaMetadataKey,
    // catalog filename
    pub name: String,
    // catalog context in yaml
    pub yml: String,
}

impl Catalog {
    pub fn accept<V>(&self, visitor: &mut V) -> Result<()>
    where
        V: VisitCatalog,
    {
        visitor.visit(self)
    }

    pub fn get_schema_metadata_key(&self) -> &CatalogSchemaMetadataKey {
        &self.schema
    }

    pub fn get_name(&self) -> &String {
        &self.name
    }

    pub fn get_yml(&self) -> &String {
        &self.yml
    }

    // deserialize array of catalogs from bytes
    pub fn from_buffer(catalogs: &[u8]) -> Result<Vec<Self>> {
        let catalogs: Vec<Self> = serde_yaml::from_slice(catalogs)?;
        Ok(catalogs)
    }

    pub async fn dump_catalogs<P>(catalogs: &[u8], directory: P) -> Result<()>
    where
        P: AsRef<Path>,
    {
        create_directory(&directory).await?;
        let catalogs = Self::from_buffer(catalogs)?;
        let mut path = PathBuf::new();
        path.push(directory);
        for catalog in catalogs.iter() {
            let name = append_dot_format_suffix(catalog.name.as_str(), "yml");
            let yml = catalog.yml.as_bytes();
            path.push(name);
            write_file(path.as_path(), yml).await?;
            path.pop();
        }
        Ok(())
    }
}

pub trait VisitCatalog {
    fn visit(&mut self, c: &Catalog) -> Result<()>;
}

pub trait ValidateCatalog: VisitCatalog {
    fn validate(&self) -> Result<()>;
}

pub struct CatalogSchemaValidator {
    pub schema: JSONSchema,
    pub instance: Option<serde_json::Value>,
}

impl CatalogSchemaValidator {
    pub fn from_literal(schema: &str) -> Result<Self> {
        let schema = serde_json::from_str(schema)?;
        Self::from_json_value(&schema)
    }

    pub fn from_buffer(schema: &[u8]) -> Result<Self> {
        let schema = serde_json::from_slice(schema)?;
        Self::from_json_value(&schema)
    }

    pub fn from_json_value(schema: &serde_json::Value) -> Result<Self> {
        let schema = match JSONSchema::compile(schema) {
            Ok(schema) => schema,
            Err(err) => {
                let operation = String::from("compile");
                let messages = vec![format!("{}", err)];
                return Err(json_schema_error(operation, messages));
            }
        };
        Ok(CatalogSchemaValidator {
            schema,
            instance: None,
        })
    }
}

impl VisitCatalog for CatalogSchemaValidator {
    fn visit(&mut self, c: &Catalog) -> Result<()> {
        // convert yml to json
        let json = yml_to_json(c.yml.as_str())?;
        let instance = serde_json::from_str(json.as_str())?;
        self.instance = Some(instance);
        Ok(())
    }
}

impl ValidateCatalog for CatalogSchemaValidator {
    fn validate(&self) -> Result<()> {
        let instance = self.instance.as_ref().expect("instance not defined");
        match self.schema.validate(instance) {
            Ok(_) => Ok(()),
            Err(errs) => {
                let messages: Vec<String> =
                    errs.into_iter().map(|err| format!("{}", err)).collect();
                Err(json_schema_error(String::from("validate"), messages))
            }
        }
    }
}

#[derive(Default)]
pub struct CatalogsNameValidator {
    names: Vec<String>,
}

impl VisitCatalog for CatalogsNameValidator {
    fn visit(&mut self, c: &Catalog) -> Result<()> {
        let name = c.get_name().to_owned();
        self.names.push(name);
        Ok(())
    }
}

impl ValidateCatalog for CatalogsNameValidator {
    fn validate(&self) -> Result<()> {
        let len = self.names.len();
        let mut name_set: HashSet<String> = HashSet::new();
        // validate snake & lower case and non-empty
        // validate uniqueness
        for i in 0..len {
            let name = self.names.get(i).unwrap();
            if !is_non_empty(name) {
                return Err(invalid_catalog_name(
                    String::from("empty string"),
                    format!(".[{}], empty catalog name", i),
                ));
            }
            if !is_snake_lower_case(name) {
                return Err(invalid_catalog_name(
                    String::from("expect snake and lower case"),
                    format!(".[{}], catalog name not in snake or lower case", i),
                ));
            }
            if name_set.contains(name) {
                return Err(invalid_catalog_name(
                    String::from("duplicate string"),
                    format!(".[{}], catalog name duplicate", i),
                ));
            }
            name_set.insert(name.to_owned());
        }
        Ok(())
    }
}

fn is_non_empty(s: &str) -> bool {
    !s.is_empty()
}

fn is_snake_lower_case(s: &str) -> bool {
    is_snake_case(s, false)
}

fn is_snake_case(s: &str, uppercase: bool) -> bool {
    // no leading underscore
    let mut underscore = true;
    let mut initial_char = true;
    for c in s.chars() {
        if initial_char && !c.is_ascii() {
            return false;
        }
        initial_char = false;
        if c.is_numeric() {
            underscore = false;
            continue;
        }
        if c.is_ascii() && c.is_ascii_uppercase() == uppercase {
            underscore = false;
            continue;
        }
        if c == '_' {
            if underscore {
                // consecutive underscore
                return false;
            }
            underscore = true;
            continue;
        }
        return false;
    }
    true
}

fn yml_to_json(yml: &str) -> Result<String> {
    let value: serde_yaml::Value = serde_yaml::from_str(yml)?;
    let json = serde_json::to_string(&value)?;
    Ok(json)
}

#[derive(Serialize, Deserialize)]
pub struct CatalogsMetadata {
    // pull count
    pub pulls: u64,
    // catalogs file size in byte
    pub size: usize,
    // created timestamp
    pub created: DateTime<Utc>,
}

impl BlobResource for CatalogsMetadata {
    fn incr_usage(&mut self) {
        self.pulls += 1
    }

    fn new(size: usize) -> Self {
        CatalogsMetadata {
            pulls: 0,
            size,
            created: Utc::now(),
        }
    }
}

impl Resource for CatalogsMetadata {
    fn ty() -> ResourceType {
        ResourceType::CatalogsMetadata
    }
}

#[derive(Serialize, Deserialize)]
pub struct CatalogsSnapshot {
    pub latest_version: u64,
}

impl CatalogsSnapshot {
    pub fn new() -> Self {
        CatalogsSnapshot { latest_version: 0 }
    }
}

impl Default for CatalogsSnapshot {
    fn default() -> Self {
        Self::new()
    }
}

impl Snapshot for CatalogsSnapshot {
    fn incr_version(&mut self) {
        self.latest_version += 1
    }
    fn get_version(&self) -> u64 {
        self.latest_version
    }
}

impl Resource for CatalogsSnapshot {
    fn ty() -> ResourceType {
        ResourceType::CatalogsSnapshot
    }
}

#[cfg(test)]
mod tests {

    use crate::{
        Catalog, CatalogSchemaMetadataKey, CatalogSchemaValidator, CatalogsNameValidator,
        ValidateCatalog,
    };

    const TEST_NAMESPACE: &str = "test";
    const TEST_CATALOG_SCHEMA_SCHEMA_ID: &str = "test_schema";
    const TEST_CATALOG_SCHEMA_VERSION: u64 = 0;
    const TEST_CATALOG_NAME: &str = "test_catalog";
    const TEST_CATALOG_YAML: &str = r#"
---
interval:
    Secs: 1000
ticks: 10
"#;
    const TEST_CATALOG_SCHEMA: &str = r##"
{
    "title": "test_catalog_schema",
    "type": "object",
    "definitions": {
        "interval_in_millis": {
            "type": "object",
            "properties": {
                "Millis": {
                    "type": "integer"
                }
            },
            "required": [ "Millis" ],
            "additionalProperties": false
        },
        "interval_in_secs": {
            "type": "object",
            "properties": {
                "Secs": {
                    "type": "integer"
                }
            },
            "required": [ "Secs" ],
            "additionalProperties": false
        },
        "interval_in_minutes": {
            "type": "object",
            "properties": {
                "Minutes": {
                    "type": "integer"
                }
            },
            "required": [ "Minutes" ],
            "additionalProperties": false
        },
        "interval_in_hours": {
            "type": "object",
            "properties": {
                "Hours": {
                    "type": "integer"
                }
            },
            "required": [ "Hours" ],
            "additionalProperties": false
        },
        "interval_in_days": {
            "type": "object",
            "properties": {
                "Days": {
                    "type": "integer"
                }
            },
            "required": [ "Days" ],
            "additionalProperties": false
        },
        "intervals": {
            "oneOf": [
                {
                    "$ref": "#/definitions/interval_in_millis"
                },
                {
                    "$ref": "#/definitions/interval_in_secs"
                },
                {
                    "$ref": "#/definitions/interval_in_minutes"
                },
                {
                    "$ref": "#/definitions/interval_in_hours"
                },
                {
                    "$ref": "#/definitions/interval_in_days"
                }
            ]
        }
    },
    "properties": {
        "interval": {
            "oneOf": [
                {
                    "$ref": "#/definitions/intervals"
                }
            ]
        },
        "delay": {
            "oneOf": [
                {
                    "$ref": "#/definitions/intervals"
                }
            ]
        },
        "ticks": {
            "type": "integer"
        }
    },
    "required": [ "interval", "ticks" ],
    "additionalProperties": false
}
"##;

    // sample validation for timer catalog
    #[test]
    fn test_valid_catalog() {
        let test_catalog_schema = CatalogSchemaMetadataKey {
            namespace: String::from(TEST_NAMESPACE),
            id: String::from(TEST_CATALOG_SCHEMA_SCHEMA_ID),
            version: TEST_CATALOG_SCHEMA_VERSION,
        };
        let test_catalog = Catalog {
            schema: test_catalog_schema,
            name: String::from(TEST_CATALOG_NAME),
            yml: String::from(TEST_CATALOG_YAML),
        };
        let mut schema_validator = CatalogSchemaValidator::from_literal(TEST_CATALOG_SCHEMA)
            .expect("failed to create schema validator");
        test_catalog
            .accept(&mut schema_validator)
            .expect("failed to visit catalog");
        schema_validator.validate().expect("invalid catalog schema");

        let mut name_validator = CatalogsNameValidator::default();
        test_catalog
            .accept(&mut name_validator)
            .expect("failed to visit catalog");
        name_validator.validate().expect("invalidate catalog name");
    }
}