oa_gateway_uci/
json.rs

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
//! OMS JSON → instance tree → OMS JSON.
//!
//! The root is a single-key object whose key is a global element.
//! `$type` selects a concrete type. An undeclared field is carried as
//! `xs:string` rather than refused — validation is where that is named.
//! `null` is refused. Nesting past [`crate::MAX_DEPTH`] is
//! [`crate::UciError::TooDeep`].

use serde_json::{json, Map, Number, Value};

use crate::instance::{Complex, Field, Message, Node, Simple};
use crate::schema::Schema;
use crate::{UciError, MAX_DEPTH};

/// Parses OMS JSON into a [`Message`].
///
/// # Errors
///
/// Returns [`UciError::Json`] if the text is not a single-key object,
/// [`UciError::UnknownElement`] if the key is not a global element,
/// [`UciError::UnknownType`] if `$type` names nothing, or
/// [`UciError::TooDeep`] / [`UciError::At`] while walking the tree.
pub fn from_json(text: &str, schema: &Schema) -> Result<Message, UciError> {
    let value: Value = serde_json::from_str(text).map_err(|e| UciError::Json(e.to_string()))?;
    let obj = value
        .as_object()
        .ok_or_else(|| UciError::Json("root must be an object".into()))?;
    if obj.len() != 1 {
        return Err(UciError::Json(
            "root object must have exactly one member".into(),
        ));
    }
    let (name, body) = obj.iter().next().expect("len == 1");
    let declared = schema
        .global_type(name)
        .ok_or_else(|| UciError::UnknownElement(name.clone()))?;
    let node = read_node(body, schema, declared, name, 0)?;
    Ok(Message {
        name: name.clone(),
        body: node,
    })
}

/// Serializes `message` as a single-key OMS JSON object.
///
/// A missing global element still uses [`Message::name`] as the type
/// name, so a hand-built tree can be written.
///
/// # Errors
///
/// Returns [`UciError`] if flattening a type fails or nesting exceeds
/// [`MAX_DEPTH`].
pub fn to_json(message: &Message, schema: &Schema) -> Result<String, UciError> {
    let declared = schema
        .global_type(&message.name)
        .unwrap_or(message.name.as_str());
    let body = write_node(&message.body, schema, declared, &message.name, 0)?;
    serde_json::to_string(&json!({ &message.name: body }))
        .map_err(|e| UciError::Json(e.to_string()))
}

/// Walks one JSON value as `type_name`. `$type` overrides the declared
/// type. An undeclared key is treated as `xs:string`.
fn read_node(
    value: &Value,
    schema: &Schema,
    type_name: &str,
    path: &str,
    depth: usize,
) -> Result<Node, UciError> {
    if depth > MAX_DEPTH {
        return Err(UciError::too_deep(path));
    }
    if schema.is_simple(type_name) || !schema.is_complex(type_name) {
        return Ok(Node::Simple(read_simple(
            value,
            schema.primitive(type_name),
            path,
        )?));
    }

    let obj = value.as_object().ok_or_else(|| {
        UciError::at(
            path,
            format!("expected object for complex type {type_name}"),
        )
    })?;

    let actual = obj
        .get("$type")
        .and_then(Value::as_str)
        .unwrap_or(type_name);
    if !schema.is_complex(actual) {
        return Err(UciError::UnknownType(actual.to_owned()));
    }

    let decls: Vec<_> = schema.flatten(actual)?;
    let mut fields = Vec::new();
    for (key, val) in obj {
        if key == "$type" {
            continue;
        }
        let decl = decls.iter().copied().find(|e| e.name == *key);
        let child_type = decl.map_or("xs:string", |e| e.type_name.as_str());
        let array = decl.is_some_and(|e| e.max_occurs.is_array());
        let child_path = format!("{path}.{key}");
        if array {
            let items = match val {
                Value::Array(arr) => arr
                    .iter()
                    .enumerate()
                    .map(|(i, v)| {
                        read_node(
                            v,
                            schema,
                            child_type,
                            &format!("{child_path}[{i}]"),
                            depth + 1,
                        )
                    })
                    .collect::<Result<Vec<_>, _>>()?,
                other => vec![read_node(
                    other,
                    schema,
                    child_type,
                    &child_path,
                    depth + 1,
                )?],
            };
            fields.push((key.clone(), Field::Many(items)));
        } else {
            fields.push((
                key.clone(),
                Field::One(read_node(val, schema, child_type, &child_path, depth + 1)?),
            ));
        }
    }

    let type_name = if actual == type_name {
        None
    } else {
        Some(actual.to_owned())
    };
    Ok(Node::Complex(Complex { type_name, fields }))
}

/// Maps a JSON scalar onto [`Simple`]. `null` is refused. A numeric
/// string is parsed when the declared primitive is numeric.
fn read_simple(value: &Value, type_name: &str, path: &str) -> Result<Simple, UciError> {
    match (type_name, value) {
        ("xs:boolean", Value::Bool(b)) => Ok(Simple::Bool(*b)),
        ("xs:boolean", Value::String(s)) if s == "true" || s == "1" => Ok(Simple::Bool(true)),
        ("xs:boolean", Value::String(s)) if s == "false" || s == "0" => Ok(Simple::Bool(false)),
        (_, Value::Bool(b)) => Ok(Simple::Bool(*b)),
        (_, Value::Number(n)) => Ok(Simple::Number(n.clone())),
        (_, Value::String(s)) => {
            Ok(parse_numeric_string(type_name, s).unwrap_or_else(|_| Simple::String(s.clone())))
        }
        (_, Value::Null) => Err(UciError::at(path, "null is not allowed")),
        _ => Err(UciError::at(
            path,
            format!("cannot map JSON {value} to {type_name}"),
        )),
    }
}

/// Parses `s` as a number when `type_name` is an XSD numeric primitive.
fn parse_numeric_string(type_name: &str, s: &str) -> Result<Simple, UciError> {
    if matches!(
        type_name,
        "xs:int"
            | "xs:integer"
            | "xs:long"
            | "xs:short"
            | "xs:byte"
            | "xs:decimal"
            | "xs:double"
            | "xs:float"
    ) {
        if let Ok(n) = s.parse::<i64>() {
            return Ok(Simple::Number(n.into()));
        }
        if let Ok(f) = s.parse::<f64>() {
            if let Some(n) = Number::from_f64(f) {
                return Ok(Simple::Number(n));
            }
        }
    }
    Err(UciError::Json("not numeric".into()))
}

/// Writes one node. `$type` is emitted when [`Complex::type_name`] is
/// set. [`Field::Many`] becomes a JSON array.
fn write_node(
    node: &Node,
    schema: &Schema,
    type_name: &str,
    path: &str,
    depth: usize,
) -> Result<Value, UciError> {
    if depth > MAX_DEPTH {
        return Err(UciError::too_deep(path));
    }
    match node {
        Node::Simple(s) => Ok(write_simple(s)),
        Node::Complex(c) => {
            let actual = c.type_name.as_deref().unwrap_or(type_name);
            let decls = if schema.is_complex(actual) {
                schema.flatten(actual)?
            } else {
                Vec::new()
            };
            let mut map = Map::new();
            if let Some(tn) = &c.type_name {
                map.insert("$type".into(), Value::String(tn.clone()));
            }
            for (name, field) in &c.fields {
                let decl = decls.iter().copied().find(|e| e.name == *name);
                let child_type = decl.map_or("xs:string", |e| e.type_name.as_str());
                let child_path = format!("{path}.{name}");
                let value = match field {
                    Field::One(n) => write_node(n, schema, child_type, &child_path, depth + 1)?,
                    Field::Many(items) => Value::Array(
                        items
                            .iter()
                            .enumerate()
                            .map(|(i, n)| {
                                write_node(
                                    n,
                                    schema,
                                    child_type,
                                    &format!("{child_path}[{i}]"),
                                    depth + 1,
                                )
                            })
                            .collect::<Result<Vec<_>, _>>()?,
                    ),
                };
                map.insert(name.clone(), value);
            }
            Ok(Value::Object(map))
        }
    }
}

fn write_simple(s: &Simple) -> Value {
    match s {
        Simple::String(v) => Value::String(v.clone()),
        Simple::Bool(b) => Value::Bool(*b),
        Simple::Number(n) => Value::Number(n.clone()),
    }
}