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
use serde::de::Error;
use serde_yaml::Mapping;
use serde_yaml::Value;

use crate::dsl::schema::compiler::CompilationError;
use crate::dsl::schema::DocumentRoot;
use crate::dsl::schema::NamedSchema;
use crate::dsl::schema::object_types::deserialization::deserialize_object_type;
use crate::dsl::schema::object_types::ObjectType;
use crate::dsl::schema::object_types::RawObjectType;
use crate::dsl::schema::Schema;
use crate::dsl::schema::SchemaList;
use crate::dsl::schema::when::dependencies_for_schema_list;
use crate::dsl::schema::when::DependencyGraph;
use crate::dsl::schema::Annotations;
use crate::dsl::schema::Widget;
use crate::dsl::schema::object_types::ObjectTypeData;
use balena_temen::ast::Expression;

pub fn deserialize_root(schema: &Value) -> Result<DocumentRoot, CompilationError> {
    let maybe_root = schema.as_mapping();
    const DEFAULT_VERSION: u64 = 1;
    let version = match maybe_root {
        Some(mapping) => Ok({
            let version = mapping.get(&Value::from("version"));

            match version {
                Some(version) => Some(
                    version
                        .as_u64()
                        .ok_or_else(|| CompilationError::with_message("version must be a positive integer"))?,
                ),
                None => None,
            }
        }),
        None => Err(CompilationError::with_message(
            "root level schema needs to be a yaml mapping",
        )),
    }?
    .unwrap_or(DEFAULT_VERSION);

    if version != DEFAULT_VERSION {
        return Err(CompilationError::with_message(&format!(
            "invalid version number '{}' specified",
            version
        )));
    }

    let schema = deserialize_schema::<serde_yaml::Error>(&schema)?;

    // this is recursive already, should get the whole tree for all children schemas
    let dependencies = dependencies_for_schema_list(schema.children.as_ref(), DependencyGraph::empty())?;

    Ok(DocumentRoot {
        version,
        schema: Some(schema),
        dependencies: Some(dependencies),
    })
}

pub fn deserialize_schema<E>(value: &Value) -> Result<Schema, E>
where
    E: Error,
{
    let yaml_mapping = value
        .as_mapping()
        .ok_or_else(|| Error::custom(format!("schema is not a yaml mapping - {:#?}", value)))?;
    let type_information = type_information(&yaml_mapping)?;

    let annotations = annotations(value)?;
    let annotations = annotations_from_type(annotations, &type_information);
    let properties = properties(yaml_mapping)?;
    let mapping = mapping(yaml_mapping)?;
    let when = when(yaml_mapping)?;
    let formula = formula(yaml_mapping)?;

    Ok(Schema {
        types: type_information,
        children: properties,
        mapping: mapping.cloned(),
        annotations,
        when,
        formula,
    })
}

fn formula<E>(yaml_mapping: &Mapping) -> Result<Option<String>, E>
where
    E: Error,
{
    let value = yaml_mapping.get(&Value::from("formula"));
    match value {
        None => Ok(None),
        Some(value) => match value {
            Value::String(string) => Ok(Some(string.to_string())),
            _ => {
                let string = serde_json::to_string(value)
                    .map_err(|e| Error::custom(format!("error parsing formula value expression: {}", e)))?;
                Ok(Some(string))
            }
        },
    }
}

fn when<E>(yaml_mapping: &Mapping) -> Result<Option<Expression>, E>
where
    E: Error,
{
    let when = yaml_mapping.get(&Value::from("when"));
    match when {
        None => Ok(None),
        Some(mapping) => match mapping {
            Value::String(string) => {
                Ok(Some(string.parse().map_err(|e| {
                    Error::custom(format!("error parsing when expression: {}", e))
                })?))
            }
            _ => Err(Error::custom(format!("unknown shape of `when`: {:#?}", mapping))),
        },
    }
}

fn mapping<E>(yaml_mapping: &Mapping) -> Result<Option<&Mapping>, E>
where
    E: Error,
{
    let mapping = yaml_mapping.get(&Value::from("mapping"));
    let mapping = match mapping {
        None => Ok(None),
        Some(mapping) => match mapping {
            Value::Mapping(mapping) => Ok(Some(mapping)),
            _ => Err(Error::custom(format!("cannot deserialize mapping {:#?}", mapping))),
        },
    }?;
    Ok(mapping)
}

fn properties<E>(yaml_mapping: &Mapping) -> Result<Option<SchemaList>, E>
where
    E: Error,
{
    let properties = yaml_mapping.get(&Value::from("properties"));
    let properties = match properties {
        None => None,
        Some(properties) => match properties {
            Value::Sequence(sequence) => Some(sequence_to_schema_list(&sequence.to_vec())?),
            _ => return Err(Error::custom("`properties` is not a yaml sequence")),
        },
    };
    Ok(properties)
}

fn annotations<E>(value: &Value) -> Result<Annotations, E>
where
    E: Error,
{
    let annotations = serde_yaml::from_value(value.clone())
        .map_err(|e| Error::custom(format!("cannot deserialize schema annotations - {}", e)))?;
    Ok(annotations)
}

fn type_information<E>(yaml_mapping: &Mapping) -> Result<Option<Vec<ObjectType>>, E>
where
    E: Error,
{
    let mut type_information = deserialize_object_type(&yaml_mapping)?;
    if type_information.is_none() {
        let raw_type = RawObjectType::Object;
        let type_data = ObjectTypeData::with_raw_type(raw_type);
        type_information = Some(vec![ObjectType::Required(type_data)]);
    }
    Ok(type_information)
}

fn annotations_from_type(old_annotations: Annotations, type_information: &Option<Vec<ObjectType>>) -> Annotations {
    let mut widget = old_annotations.widget;
    if let Some(type_info) = type_information {
        for object_type in type_info {
            if let RawObjectType::Text(_) = object_type.inner_raw() {
                widget = Some(Widget::Textarea)
            }
        }
    }
    Annotations {
        widget,
        ..old_annotations
    }
}

fn sequence_to_schema_list<E>(sequence: &[Value]) -> Result<SchemaList, E>
where
    E: Error,
{
    let list_of_maybe_entries = sequence.iter().map(|value| {
        let mapping = value
            .as_mapping()
            .ok_or_else(|| Error::custom(format!("cannot deserialize schema {:#?} as mapping", value)))?;
        Ok(mapping_to_named_schema(mapping)?)
    });

    let list: Result<Vec<_>, E> = list_of_maybe_entries.collect();
    let list = list?;

    Ok(SchemaList { entries: list })
}

fn mapping_to_named_schema<E>(mapping: &Mapping) -> Result<NamedSchema, E>
where
    E: Error,
{
    let (key, value) = mapping
        .into_iter()
        .next()
        .ok_or_else(|| Error::custom("cannot get first element of the sequence"))?;
    let key: String = serde_yaml::from_value(key.clone())
        .map_err(|e| Error::custom(format!("cannot deserialize named schema name - {}", e)))?;
    let value = deserialize_schema(&value)?;
    Ok(NamedSchema {
        name: key,
        schema: value,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fails_on_unknown_version_number() {
        let schema = serde_yaml::from_str(
            r#"
        version: 2
        "#,
        )
        .unwrap();

        let deserialized: Result<DocumentRoot, CompilationError> = deserialize_root(&schema);

        assert!(deserialized.err().is_some());
    }

    #[test]
    fn passes_on_known_version_number() {
        let schema = serde_yaml::from_str(
            r#"
        version: 1
        "#,
        )
        .unwrap();

        let deserialized: Result<DocumentRoot, CompilationError> = deserialize_root(&schema);
        assert!(deserialized.ok().is_some());
    }
}