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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! # rsgen-avro
//!
//! **[Apache Avro](https://avro.apache.org/)** is a data serialization system which provides
//! rich data structures and a compact, fast, binary data format.
//!
//! All data in Avro is schematized, as in the following example:
//!
//! ```text
//! {
//!     "type": "record",
//!     "name": "test",
//!     "fields": [
//!         {"name": "a", "type": "long", "default": 42},
//!         {"name": "b", "type": "string"}
//!     ]
//! }
//! ```
//!
//! The **[avro-rs](https://github.com/flavray/avro-rs)** crate provides a way to
//! read and write Avro data with both Avro-specialized and Rust serde-compatible types.
//!
//! **[rsgen-avro](https://github.com/lerouxrgd/rsgen-avro)** provides a way to generate Rust serde-compatible types based on Avro schemas. Both a command line tool and library crate are available.
//!
//! # Using the library
//!
//! Add to your Cargo.toml:
//!
//! ```text
//! [dependencies]
//! rsgen-avro = "x.y.z"
//! ```
//!
//! Then, the basic usage is:
//!
//! ```rust
//! use rsgen_avro::{Source, Generator};
//!
//! let raw_schema = r#"
//! {
//!     "type": "record",
//!     "name": "test",
//!     "fields": [
//!         {"name": "a", "type": "long", "default": 42},
//!         {"name": "b", "type": "string"}
//!     ]
//! }
//! "#;
//!
//! let source = Source::SchemaStr(&raw_schema);
//!
//! let mut out = std::io::stdout();
//!
//! let g = Generator::new().unwrap();
//! g.gen(&source, &mut out).unwrap();
//! ```
//!
//! This will generate the following output:
//!
//! ```text
//! use serde::{Deserialize, Serialize};
//!
//! #[serde(default)]
//! #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
//! pub struct Test {
//!     pub a: i64,
//!     pub b: String,
//! }
//!
//! impl Default for Test {
//!     fn default() -> Test {
//!         Test {
//!             a: 42,
//!             b: String::default(),
//!         }
//!     }
//! }
//! ```
//!
//! Various `Schema` sources can be used with `Generator`'s `.gen(..)` method:
//!
//! ```rust
//! pub enum Source<'a> {
//!     Schema(&'a avro_rs::Schema), // from `avro-rs` crate
//!     SchemaStr(&'a str),
//!     FilePath(&'a std::path::Path),
//!     DirPath(&'a std::path::Path),
//! }
//! ```
//!
//! Note also that the `Generator` can be customized with a builder:
//!
//! ```rust
//! # use rsgen_avro::Generator;
//! let g = Generator::builder().precision(2).build().unwrap();
//! ```

pub mod error;
mod templates;

use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

use avro_rs::{schema::RecordField, Schema};

use crate::error::{Error, Result};
use crate::templates::*;

/// Represents a schema input source.
pub enum Source<'a> {
    /// An Avro schema enum from `avro-rs` crate.
    Schema(&'a Schema),
    /// An Avro schema string in json format.
    SchemaStr(&'a str),
    /// Path to a file containing an Avro schema in json format.
    FilePath(&'a Path),
    /// Path to a directory containing multiple files in Avro schema.
    DirPath(&'a Path),
}

/// The main component of this library.
/// It is stateless and can be reused many times.
pub struct Generator {
    templater: Templater,
}

impl Generator {
    /// Create a new `Generator` through a builder with default config.
    pub fn new() -> Result<Generator> {
        GeneratorBuilder::new().build()
    }

    /// Returns a fluid builder for custom `Generator` instantiation.
    pub fn builder() -> GeneratorBuilder {
        GeneratorBuilder::new()
    }

    /// Generates Rust code from an Avro schema `Source`.
    /// Writes all generated types to the ouput.
    pub fn gen(&self, source: &Source, output: &mut impl Write) -> Result<()> {
        output.write_all(self.templater.str_serde()?.as_bytes())?;

        if self.templater.nullable {
            output.write_all(DESER_NULLABLE.as_bytes())?;
        }

        match source {
            Source::Schema(schema) => self.gen_in_order(schema, output)?,

            Source::SchemaStr(raw_schema) => {
                let schema = Schema::parse_str(&raw_schema)?;
                self.gen_in_order(&schema, output)?
            }

            Source::FilePath(schema_file) => {
                let mut raw_schema = String::new();
                File::open(&schema_file)?.read_to_string(&mut raw_schema)?;
                let schema = Schema::parse_str(&raw_schema)?;
                self.gen_in_order(&schema, output)?
            }

            Source::DirPath(schemas_dir) => {
                for entry in std::fs::read_dir(schemas_dir)? {
                    let path = entry?.path();
                    if !path.is_dir() {
                        let mut raw_schema = String::new();
                        File::open(&path)?.read_to_string(&mut raw_schema)?;
                        let schema = Schema::parse_str(&raw_schema)?;
                        self.gen_in_order(&schema, output)?
                    }
                }
            }
        }

        Ok(())
    }

    /// Given an Avro `schema`:
    /// * Find its ordered, nested dependencies with `deps_stack(schema)`
    /// * Pops sub-schemas and generate appropriate Rust types
    /// * Keeps tracks of nested schema->name with `GenState` mapping
    /// * Appends generated Rust types to the output
    fn gen_in_order(&self, schema: &Schema, output: &mut impl Write) -> Result<()> {
        let mut gs = GenState::new();
        let mut deps = deps_stack(schema);

        while let Some(s) = deps.pop() {
            match s {
                // Simply generate code
                Schema::Fixed { .. } => {
                    let code = &self.templater.str_fixed(&s)?;
                    output.write_all(code.as_bytes())?
                }
                Schema::Enum { .. } => {
                    let code = &self.templater.str_enum(&s)?;
                    output.write_all(code.as_bytes())?
                }

                // Generate code with potentially nested types
                Schema::Record { .. } => {
                    let code = &self.templater.str_record(&s, &gs)?;
                    output.write_all(code.as_bytes())?
                }

                // Register inner type for it to be used as a nested type later
                Schema::Array(inner) => {
                    let type_str = array_type(inner, &gs)?;
                    gs.put_type(&s, type_str)
                }
                Schema::Map(inner) => {
                    let type_str = map_type(inner, &gs)?;
                    gs.put_type(&s, type_str)
                }
                Schema::Union(union) => {
                    if let [Schema::Null, inner] = union.variants() {
                        let type_str = option_type(inner, &gs)?;
                        gs.put_type(&s, type_str)
                    }
                }

                _ => Err(Error::Schema(format!("Not a valid root schema: {:?}", s)))?,
            }
        }
        Ok(())
    }
}

/// Utility function to find the ordered, nested dependencies of an Avro `schema`.
/// Explores nested `schema`s in a breadth-first fashion, pushing them on a stack
/// at the same time in order to have them ordered.
/// It is similar to traversing the `schema` tree in a post-order fashion.
fn deps_stack(schema: &Schema) -> Vec<&Schema> {
    fn push_unique<'a>(deps: &mut Vec<&'a Schema>, s: &'a Schema) {
        if !deps.contains(&s) {
            deps.push(s)
        };
    }

    let mut deps = Vec::new();
    let mut q = VecDeque::new();

    q.push_back(schema);
    while !q.is_empty() {
        let s = q.pop_front().unwrap();

        match s {
            // No nested schemas, add them to the result stack
            Schema::Fixed { .. } => push_unique(&mut deps, s),
            Schema::Enum { .. } => push_unique(&mut deps, s),

            // Explore the record fields for potentially nested schemas
            Schema::Record { fields, .. } => {
                push_unique(&mut deps, s);

                let by_pos = fields
                    .iter()
                    .map(|f| (f.position, f))
                    .collect::<HashMap<_, _>>();
                let mut i = 0;
                while let Some(RecordField { schema: sr, .. }) = by_pos.get(&i) {
                    match sr {
                        // No nested schemas, add them to the result stack
                        Schema::Fixed { .. } => push_unique(&mut deps, sr),
                        Schema::Enum { .. } => push_unique(&mut deps, sr),

                        // Push to the exploration queue for further checks
                        Schema::Record { .. } => q.push_back(sr),

                        // Push to the exploration queue, depending on the inner schema format
                        Schema::Map(sc) | Schema::Array(sc) => match &**sc {
                            Schema::Fixed { .. }
                            | Schema::Enum { .. }
                            | Schema::Record { .. }
                            | Schema::Map(..)
                            | Schema::Array(..)
                            | Schema::Union(..) => q.push_back(&**sc),
                            _ => (),
                        },
                        Schema::Union(union) => {
                            if let [Schema::Null, sc] = union.variants() {
                                match sc {
                                    Schema::Fixed { .. }
                                    | Schema::Enum { .. }
                                    | Schema::Record { .. }
                                    | Schema::Map(..)
                                    | Schema::Array(..)
                                    | Schema::Union(..) => {
                                        q.push_back(sc);
                                        push_unique(&mut deps, sc);
                                    }
                                    _ => (),
                                }
                            }
                        }
                        _ => (),
                    };
                    i += 1;
                }
            }

            // Depending on the inner schema type ...
            Schema::Map(sc) | Schema::Array(sc) => match &**sc {
                // ... Needs further checks, push to the exploration queue
                Schema::Fixed { .. }
                | Schema::Enum { .. }
                | Schema::Record { .. }
                | Schema::Map(..)
                | Schema::Array(..)
                | Schema::Union(..) => q.push_back(&**sc),
                // ... Not nested, can be pushed to the result stack
                _ => push_unique(&mut deps, s),
            },
            Schema::Union(union) => {
                if let [Schema::Null, sc] = union.variants() {
                    match sc {
                        // ... Needs further checks, push to the exploration queue
                        Schema::Fixed { .. }
                        | Schema::Enum { .. }
                        | Schema::Record { .. }
                        | Schema::Map(..)
                        | Schema::Array(..)
                        | Schema::Union(..) => q.push_back(sc),
                        // ... Not nested, can be pushed to the result stack
                        _ => push_unique(&mut deps, s),
                    }
                }
            }

            // Ignore all other schema formats
            _ => (),
        }
    }

    deps
}

/// A builder class to customize `Generator`.
pub struct GeneratorBuilder {
    precision: usize,
    nullable: bool,
}

impl GeneratorBuilder {
    /// Creates a new `GeneratorBuilder`.
    pub fn new() -> GeneratorBuilder {
        GeneratorBuilder {
            precision: 3,
            nullable: false,
        }
    }

    /// Sets the precision for default values of f32/f64 fields.
    pub fn precision(mut self, precision: usize) -> GeneratorBuilder {
        self.precision = precision;
        self
    }

    /// Puts default value when deserializing `null` field.
    /// Doesn't apply to union fields ["null", "Foo"], which are `Option<Foo>`.
    pub fn nullable(mut self, nullable: bool) -> GeneratorBuilder {
        self.nullable = nullable;
        self
    }

    /// Create a `Generator` with the builder parameters.
    pub fn build(self) -> Result<Generator> {
        let mut templater = Templater::new()?;
        templater.precision = self.precision;
        templater.nullable = self.nullable;
        Ok(Generator { templater })
    }
}

#[cfg(test)]
mod tests {
    use avro_rs::schema::Name;
    use serde::{Deserialize, Serialize};

    use super::*;

    macro_rules! assert_schema_gen (
        ($generator:expr, $expected:expr, $raw_schema:expr) => (
            let schema = Schema::parse_str($raw_schema).unwrap();
            let source = Source::Schema(&schema);

            let mut buf = vec![];
            $generator.gen(&source, &mut buf).unwrap();
            let res = String::from_utf8(buf).unwrap();

            assert_eq!($expected, &res);
        );
    );

    #[test]
    fn simple() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "test",
  "fields": [
    {"name": "a", "type": "long", "default": 42},
    {"name": "b", "type": "string"}
  ]
}
"#;

        let expected = "use serde::{Deserialize, Serialize};

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Test {
    pub a: i64,
    pub b: String,
}

impl Default for Test {
    fn default() -> Test {
        Test {
            a: 42,
            b: String::default(),
        }
    }
}
";

        let g = Generator::new().unwrap();
        assert_schema_gen!(g, expected, raw_schema);
    }

    #[test]
    fn complex() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "User",
  "doc": "Hi there.",
  "fields": [
    {"name": "name", "type": "string", "default": ""},
    {"name": "favorite_number",  "type": "int", "default": 7},
    {"name": "likes_pizza", "type": "boolean", "default": false},
    {"name": "oye", "type": "float", "default": 1.1},
    {"name": "aa-i32",
     "type": {"type": "array", "items": {"type": "array", "items": "int"}},
     "default": [[0], [12, -1]]}
  ]
}
"#;

        let expected = r#"use serde::{Deserialize, Serialize};

/// Hi there.
#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct User {
    pub name: String,
    pub favorite_number: i32,
    pub likes_pizza: bool,
    pub oye: f32,
    #[serde(rename = "aa-i32")]
    pub aa_i32: Vec<Vec<i32>>,
}

impl Default for User {
    fn default() -> User {
        User {
            name: "".to_owned(),
            favorite_number: 7,
            likes_pizza: false,
            oye: 1.100,
            aa_i32: vec![vec![0], vec![12, -1]],
        }
    }
}
"#;

        let g = Generator::new().unwrap();
        assert_schema_gen!(g, expected, raw_schema);
    }

    #[test]
    fn nullable_gen() {
        let raw_schema = r#"
{
  "type": "record",
  "name": "test",
  "fields": [
    {"name": "a", "type": "long", "default": 42},
    {"name": "b-b", "type": "string", "default": "na"},
    {"name": "c", "type": ["null", "int"], "default": null}
  ]
}
"#;

        let expected = r#"use serde::{Deserialize, Deserializer, Serialize};

macro_rules! deser(
    ($name:ident, $rtype:ty, $val:expr) => (
        fn $name<'de, D>(deserializer: D) -> Result<$rtype, D::Error>
        where
            D: Deserializer<'de>,
        {
            let opt = Option::deserialize(deserializer)?;
            Ok(opt.unwrap_or_else(|| $val))
        }
    );
);

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Test {
    #[serde(deserialize_with = "nullable_test_a")]
    pub a: i64,
    #[serde(rename = "b-b", deserialize_with = "nullable_test_b_b")]
    pub b_b: String,
    pub c: Option<i32>,
}
deser!(nullable_test_a, i64, 42);
deser!(nullable_test_b_b, String, "na".to_owned());

impl Default for Test {
    fn default() -> Test {
        Test {
            a: 42,
            b_b: "na".to_owned(),
            c: None,
        }
    }
}
"#;
        let g = Generator::builder().nullable(true).build().unwrap();
        assert_schema_gen!(g, expected, raw_schema);
    }

    #[test]
    fn nullable_array() {
        let raw_schema = r#"
{
  "name": "Snmp",
  "type": "record",
  "fields": [ {
    "name": "v1",
    "type": [ "null", {
      "name": "V1",
      "type": "record",
      "fields": [ {
        "name": "pdu",
        "type": [ "null", {
          "name": "TrapV1",
          "type": "record",
          "fields": [ {
            "name": "var",
            "type": ["null", {
              "type": "array",
              "items": {
                "name": "Variable",
                "type": "record",
                "fields": [ {
                  "name": "oid",
                  "type": ["null", {
                    "type":"array",
                    "items": "long"
                  } ],
                  "default": null
                }, {
                  "name": "val",
                  "type": ["null", "string"],
                  "default": null
                }],
                "default": {}
              }
            } ],
            "default": null
          } ]
        } ],
        "default": null
      } ]
    } ],
    "default": null
  } ],
  "default": {}
}
"#;

        let expected = r#"use serde::{Deserialize, Serialize};

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Variable {
    pub oid: Option<Vec<i64>>,
    pub val: Option<String>,
}

impl Default for Variable {
    fn default() -> Variable {
        Variable {
            oid: None,
            val: None,
        }
    }
}

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct TrapV1 {
    pub var: Option<Vec<Variable>>,
}

impl Default for TrapV1 {
    fn default() -> TrapV1 {
        TrapV1 {
            var: None,
        }
    }
}

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct V1 {
    pub pdu: Option<TrapV1>,
}

impl Default for V1 {
    fn default() -> V1 {
        V1 {
            pdu: None,
        }
    }
}

#[serde(default)]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
pub struct Snmp {
    pub v1: Option<V1>,
}

impl Default for Snmp {
    fn default() -> Snmp {
        Snmp {
            v1: None,
        }
    }
}
"#;

        let g = Generator::new().unwrap();
        assert_schema_gen!(g, expected, raw_schema);
    }

    #[test]
    fn nullable_code() {
        use serde::{Deserialize, Deserializer};

        macro_rules! deser(
            ($name:ident, $rtype:ty, $val:expr) => (
                fn $name<'de, D>(deserializer: D) -> std::result::Result<$rtype, D::Error>
                where
                    D: Deserializer<'de>,
                {
                    let opt = Option::deserialize(deserializer)?;
                    Ok(opt.unwrap_or_else(|| $val))
                }
            );
        );

        #[serde(default)]
        #[derive(Debug, PartialEq, Deserialize, Serialize)]
        pub struct Test {
            #[serde(deserialize_with = "nullable_test_a")]
            pub a: i64,
            #[serde(rename = "b-b", deserialize_with = "nullable_test_b_b")]
            pub b_b: String,
            pub c: Option<i32>,
        }
        deser!(nullable_test_a, i64, 42);
        deser!(nullable_test_b_b, String, "na".to_owned());

        impl Default for Test {
            fn default() -> Test {
                Test {
                    a: 42,
                    b_b: "na".to_owned(),
                    c: None,
                }
            }
        }

        let json = r#"{"a": null, "b-b": null, "c": null}"#;
        let res: Test = serde_json::from_str(json).unwrap();
        assert_eq!(Test::default(), res);
    }

    #[test]
    fn deps() {
        use matches::assert_matches;

        let raw_schema = r#"
{
  "type": "record",
  "name": "User",
  "fields": [
    {"name": "name", "type": "string", "default": "unknown"},
    {"name": "address",
     "type": {
       "type": "record",
       "name": "Address",
       "fields": [
         {"name": "city", "type": "string", "default": "unknown"},
         {"name": "country",
          "type": {"type": "enum", "name": "Country", "symbols": ["FR", "JP"]}
         }
       ]
     }
    }
  ]
}
"#;

        let schema = Schema::parse_str(&raw_schema).unwrap();
        let mut deps = deps_stack(&schema);

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Enum{ name: Name { ref name, ..}, ..} if name == "Country");

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Record{ name: Name { ref name, ..}, ..} if name == "Address");

        let s = deps.pop().unwrap();
        assert_matches!(s, Schema::Record{ name: Name { ref name, ..}, ..} if name == "User");

        let s = deps.pop();
        assert_matches!(s, None);
    }
}