Skip to main content

relate_core/value/
json.rs

1//! JSON encode/decode for [`Value`]: the tagged `{"t":..., "v":...}` form
2//! (WAL/checkpoint bytes) and the plain FFI form, plus the `Tagged*Ref` serde
3//! impls behind the canonical tagged encoder.
4
5use super::*;
6
7impl Value {
8    /// The tagged `{"t":..., "v":...}` JSON form. Built from the canonical
9    /// [`serde::Serialize`] impl (via [`TaggedRef`]), so the tree here and the
10    /// direct WAL/checkpoint bytes cannot diverge. Graph entities are not
11    /// persistence properties: the encoder rejects them (see [`TaggedRef`]),
12    /// and that internal error maps to `Null` here.
13    pub fn to_json_tagged(&self) -> serde_json::Value {
14        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
15    }
16
17    pub fn from_json_tagged(v: &serde_json::Value) -> crate::Result<Value> {
18        Self::from_json_tagged_at(v, 0)
19    }
20
21    /// [`Value::from_json_tagged`] with the ADR-0462 `depth` (the number of
22    /// tagged containers enclosing `v`): an untrusted persistence input
23    /// nested past [`MAX_VALUE_DEPTH`] is rejected with a typed storage
24    /// error instead of driving the recursive decoder off the stack.
25    fn from_json_tagged_at(v: &serde_json::Value, depth: u32) -> crate::Result<Value> {
26        fn malformed(expected: &str) -> crate::Error {
27            crate::Error::storage(format!("malformed tagged value: expected {expected}"))
28        }
29        fn too_deep() -> crate::Error {
30            crate::Error::storage(value_depth_exceeded("tagged value"))
31        }
32        let obj = v
33            .as_object()
34            .ok_or_else(|| crate::Error::storage("property JSON must be an object"))?;
35        let t = obj
36            .get("t")
37            .and_then(|x| x.as_str())
38            .ok_or_else(|| crate::Error::storage("missing type tag"))?;
39        Ok(match t {
40            "null" => Value::Null,
41            "bool" => Value::Bool(
42                obj.get("v")
43                    .and_then(|x| x.as_bool())
44                    .ok_or_else(|| malformed("\"bool\" with a boolean \"v\""))?,
45            ),
46            "int" => Value::Int(
47                obj.get("v")
48                    .and_then(|x| x.as_i64())
49                    .ok_or_else(|| malformed("\"int\" with an integer \"v\""))?,
50            ),
51            "float" => Value::Float(match obj.get("v") {
52                Some(serde_json::Value::String(s)) if s == "NaN" => f64::NAN,
53                Some(serde_json::Value::String(s)) if s == "Infinity" => f64::INFINITY,
54                Some(serde_json::Value::String(s)) if s == "-Infinity" => f64::NEG_INFINITY,
55                other => other
56                    .and_then(|x| x.as_f64())
57                    .ok_or_else(|| malformed("\"float\" with a number \"v\""))?,
58            }),
59            "string" => Value::String(
60                obj.get("v")
61                    .and_then(|x| x.as_str())
62                    .ok_or_else(|| malformed("\"string\" with a string \"v\""))?
63                    .into(),
64            ),
65            "uuid" => {
66                let s = obj
67                    .get("v")
68                    .and_then(|x| x.as_str())
69                    .ok_or_else(|| malformed("\"uuid\" with a string \"v\""))?;
70                Value::Uuid(
71                    uuid_parse(s)
72                        .ok_or_else(|| malformed("\"uuid\" with a canonical hyphenated \"v\""))?,
73                )
74            }
75            "list" => {
76                let Some(next) = next_depth(depth) else {
77                    return Err(too_deep());
78                };
79                let arr = obj
80                    .get("v")
81                    .and_then(|x| x.as_array())
82                    .ok_or_else(|| malformed("\"list\" with an array \"v\""))?;
83                Value::List(
84                    arr.iter()
85                        .map(|x| Value::from_json_tagged_at(x, next))
86                        .collect::<crate::Result<Vec<_>>>()?
87                        .into(),
88                )
89            }
90            "map" => {
91                let Some(next) = next_depth(depth) else {
92                    return Err(too_deep());
93                };
94                let mut map = BTreeMap::new();
95                let o = obj
96                    .get("v")
97                    .and_then(|x| x.as_object())
98                    .ok_or_else(|| malformed("\"map\" with an object \"v\""))?;
99                for (k, val) in o {
100                    map.insert(k.clone(), Value::from_json_tagged_at(val, next)?);
101                }
102                Value::Map(map.into())
103            }
104            "date" | "time" | "localtime" | "datetime" | "localdatetime" | "duration" => {
105                let s = obj
106                    .get("v")
107                    .and_then(|x| x.as_str())
108                    .ok_or_else(|| crate::Error::storage("missing temporal value"))?;
109                Value::Temporal(crate::temporal::parse_iso(t, s)?)
110            }
111            "point" => {
112                let p = obj
113                    .get("v")
114                    .and_then(|x| x.as_object())
115                    .ok_or_else(|| malformed("\"point\" with an object \"v\""))?;
116                Value::Point(PointValue {
117                    srid: p
118                        .get("srid")
119                        .and_then(|x| x.as_i64())
120                        .and_then(|x| i32::try_from(x).ok())
121                        .ok_or_else(|| malformed("\"point\" with an integer \"srid\""))?,
122                    x: p.get("x")
123                        .and_then(|x| x.as_f64())
124                        .ok_or_else(|| malformed("\"point\" with a number \"x\""))?,
125                    y: p.get("y")
126                        .and_then(|x| x.as_f64())
127                        .ok_or_else(|| malformed("\"point\" with a number \"y\""))?,
128                    z: p.get("z").and_then(|x| x.as_f64()),
129                })
130            }
131            "vector" => {
132                let Some(next) = next_depth(depth) else {
133                    return Err(too_deep());
134                };
135                let coord = obj
136                    .get("coord")
137                    .and_then(|x| x.as_str())
138                    .and_then(VectorCoordKind::from_canonical_name)
139                    .ok_or_else(|| crate::Error::storage("invalid vector coordinate type"))?;
140                let xs = obj
141                    .get("v")
142                    .and_then(|x| x.as_array())
143                    .ok_or_else(|| malformed("\"vector\" with an array \"v\""))?;
144                let values = xs
145                    .iter()
146                    .map(|x| Value::from_json_tagged_at(x, next))
147                    .collect::<crate::Result<Vec<_>>>()?;
148                Value::Vector {
149                    coord,
150                    values: values.into(),
151                }
152            }
153            other => return Err(crate::Error::storage(format!("unknown type tag {other:?}"))),
154        })
155    }
156
157    /// Best-effort Python/JSON-ish value for FFI clients.
158    pub fn to_json_plain(&self) -> serde_json::Value {
159        self.to_json_plain_at(0)
160    }
161
162    /// [`Value::to_json_plain`] with the ADR-0462 `depth` guard: a container
163    /// past [`MAX_VALUE_DEPTH`] encodes as JSON `null` instead of recursing.
164    /// Unreachable behind the checked constructors.
165    fn to_json_plain_at(&self, depth: u32) -> serde_json::Value {
166        use serde_json::json;
167        match self {
168            Value::Null => serde_json::Value::Null,
169            Value::Bool(b) => json!(b),
170            Value::Int(i) => json!(i),
171            Value::Float(f) => json!(f),
172            Value::String(s) => json!(&**s),
173            Value::Uuid(u) => json!(uuid_hyphenated(*u)),
174            // The byte values 0-255, the `value_to_cypher` shape (ADR-0327).
175            Value::Bytes(b) => json!(&**b),
176            Value::List(xs) => {
177                let Some(next) = next_depth(depth) else {
178                    return serde_json::Value::Null;
179                };
180                json!(xs
181                    .iter()
182                    .map(|v| v.to_json_plain_at(next))
183                    .collect::<Vec<_>>())
184            }
185            Value::Map(m) => {
186                let Some(next) = next_depth(depth) else {
187                    return serde_json::Value::Null;
188                };
189                map_to_json_plain(m.iter(), next)
190            }
191            Value::Node(n) => node_json(n, depth),
192            Value::Relationship(r) => rel_json(r, depth),
193            Value::Path(p) => {
194                if next_depth(depth).is_none() {
195                    return serde_json::Value::Null;
196                }
197                // A path's embedded entities are not an extra container
198                // level (ADR-0462 depth accounting); they share the path's.
199                json!({
200                    "_type": "path",
201                    "nodes": p.nodes.iter().map(|n| node_json(n, depth)).collect::<Vec<_>>(),
202                    "relationships": p.rels.iter().map(|r| rel_json(r, depth)).collect::<Vec<_>>(),
203                })
204            }
205            Value::Temporal(t) => json!({
206                "_type": t.kind_name(),
207                "value": t.iso_string(),
208            }),
209            Value::Point(p) => json!({
210                "_type": "point", "srid": p.srid, "x": p.x, "y": p.y, "z": p.z
211            }),
212            Value::Vector { coord, values } => {
213                let Some(next) = next_depth(depth) else {
214                    return serde_json::Value::Null;
215                };
216                json!({
217                    "_type": "vector",
218                    "coordinateType": coord.canonical_name(),
219                    "values": values.iter().map(|v| v.to_json_plain_at(next)).collect::<Vec<_>>()
220                })
221            }
222        }
223    }
224
225    pub fn from_json_plain(v: &serde_json::Value) -> Value {
226        match v {
227            serde_json::Value::Null => Value::Null,
228            serde_json::Value::Bool(b) => Value::Bool(*b),
229            serde_json::Value::Number(n) => {
230                if let Some(i) = n.as_i64() {
231                    Value::Int(i)
232                } else if let Some(f) = n.as_f64() {
233                    Value::Float(f)
234                } else {
235                    Value::Null
236                }
237            }
238            serde_json::Value::String(s) => Value::String(s.as_str().into()),
239            serde_json::Value::Array(a) => Value::List(
240                a.iter()
241                    .map(Value::from_json_plain)
242                    .collect::<Vec<_>>()
243                    .into(),
244            ),
245            serde_json::Value::Object(o) => {
246                // Probe the `_type` tag exactly once: the handled set
247                // ("node", "point", "vector") and the fall-through to a
248                // plain map are explicit in one place.
249                match o.get("_type").and_then(|t| t.as_str()) {
250                    Some("node") => {
251                        return Value::Node(Arc::new(Node {
252                            id: o.get("id").and_then(|x| x.as_i64()).unwrap_or(0),
253                            labels: Arc::new(
254                                o.get("labels")
255                                    .and_then(|x| x.as_array())
256                                    .map(|a| {
257                                        a.iter()
258                                            .filter_map(|x| x.as_str().map(|s| s.to_string()))
259                                            .collect::<Vec<_>>()
260                                    })
261                                    .unwrap_or_default(),
262                            ),
263                            properties: match o.get("properties") {
264                                Some(p) => match Value::from_json_plain(p) {
265                                    Value::Map(m) => PropertyMap::share(Arc::unwrap_or_clone(m)),
266                                    _ => PropertyMap::share(PropertyMap::new()),
267                                },
268                                None => PropertyMap::share(PropertyMap::new()),
269                            },
270                        }));
271                    }
272                    Some("point") => {
273                        return Value::Point(PointValue {
274                            srid: o
275                                .get("srid")
276                                .and_then(|x| x.as_i64())
277                                .and_then(|x| i32::try_from(x).ok())
278                                .unwrap_or(7203),
279                            x: o.get("x").and_then(|x| x.as_f64()).unwrap_or(0.0),
280                            y: o.get("y").and_then(|x| x.as_f64()).unwrap_or(0.0),
281                            z: o.get("z").and_then(|x| x.as_f64()),
282                        });
283                    }
284                    Some("vector") => {
285                        if let Some(coord) = o
286                            .get("coordinateType")
287                            .and_then(|x| x.as_str())
288                            .and_then(VectorCoordKind::from_canonical_name)
289                        {
290                            let values: Vec<Value> = o
291                                .get("values")
292                                .and_then(|x| x.as_array())
293                                .map(|xs| xs.iter().map(Value::from_json_plain).collect())
294                                .unwrap_or_default();
295                            return Value::Vector {
296                                coord,
297                                values: values.into(),
298                            };
299                        }
300                    }
301                    _ => {}
302                }
303                let mut m = BTreeMap::new();
304                for (k, val) in o {
305                    m.insert(k.clone(), Value::from_json_plain(val));
306                }
307                Value::Map(m.into())
308            }
309        }
310    }
311
312    /// Decode JSON whose objects are always maps. A `_type` of `node`,
313    /// `point`, or `vector` stays a string property. This is the decoder for
314    /// untrusted property documents. [`from_json_plain`] is the inverse of
315    /// [`to_json_plain`] and still recognizes those tags.
316    pub fn from_json_scalars(v: &serde_json::Value) -> Value {
317        match v {
318            serde_json::Value::Null => Value::Null,
319            serde_json::Value::Bool(b) => Value::Bool(*b),
320            serde_json::Value::Number(n) => {
321                if let Some(i) = n.as_i64() {
322                    Value::Int(i)
323                } else if let Some(f) = n.as_f64() {
324                    Value::Float(f)
325                } else {
326                    Value::Null
327                }
328            }
329            serde_json::Value::String(s) => Value::String(s.as_str().into()),
330            serde_json::Value::Array(a) => Value::List(
331                a.iter()
332                    .map(Value::from_json_scalars)
333                    .collect::<Vec<_>>()
334                    .into(),
335            ),
336            serde_json::Value::Object(o) => {
337                let mut m = BTreeMap::new();
338                for (k, val) in o {
339                    m.insert(k.clone(), Value::from_json_scalars(val));
340                }
341                Value::Map(m.into())
342            }
343        }
344    }
345}
346
347/// Borrowing encoder of the tagged string `{"t":"string","v":...}`.
348/// Construct it with [`tagged_str`]. [`Value`]'s tagged encoder writes the
349/// same two entries.
350pub struct TaggedStr<'a>(&'a str);
351
352fn write_tagged_str<M: serde::ser::SerializeMap>(m: &mut M, s: &str) -> Result<(), M::Error> {
353    m.serialize_entry("t", "string")?;
354    m.serialize_entry("v", s)?;
355    Ok(())
356}
357
358impl serde::Serialize for TaggedStr<'_> {
359    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
360        use serde::ser::SerializeMap;
361        let mut m = serializer.serialize_map(Some(2))?;
362        write_tagged_str(&mut m, self.0)?;
363        m.end()
364    }
365}
366
367/// The tagged string [`TaggedRef`] writes for [`Value::String`].
368pub fn tagged_str(s: &str) -> TaggedStr<'_> {
369    TaggedStr(s)
370}
371
372/// Serializes a [`Value`] as the tagged `{"t":..., ...}` JSON that both the
373/// WAL and the Parquet checkpoint codec record — directly, without building an
374/// intermediate `serde_json::Value` tree. This is the single canonical tagged
375/// encoder; [`Value::to_json_tagged`] produces its `serde_json::Value` from it,
376/// so the two cannot drift.
377///
378/// Graph entities ([`Value::Node`], [`Value::Relationship`],
379/// [`Value::Path`]) are not persistence properties: encoding one is a
380/// serialization error, mirroring the v2 persistence codec's "graph entity
381/// is not a persistence property" rejection. Byte arrays are the second
382/// not-a-persistence-property rejection class (ADR-0327: statement-scoped,
383/// and the executor's property check rejects them with a typed `TypeError`
384/// before persistence), with their own "byte array is not a persistence
385/// property" error.
386struct TaggedRef<'a>(&'a Value);
387
388impl serde::Serialize for TaggedRef<'_> {
389    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
390        use serde::ser::SerializeMap;
391        let mut m = serializer.serialize_map(Some(2))?;
392        match self.0 {
393            Value::Null => m.serialize_entry("t", "null")?,
394            Value::Bool(b) => {
395                m.serialize_entry("t", "bool")?;
396                m.serialize_entry("v", b)?;
397            }
398            Value::Int(i) => {
399                m.serialize_entry("t", "int")?;
400                m.serialize_entry("v", i)?;
401            }
402            Value::Float(f) => {
403                m.serialize_entry("t", "float")?;
404                if f.is_nan() {
405                    m.serialize_entry("v", "NaN")?;
406                } else if *f == f64::INFINITY {
407                    m.serialize_entry("v", "Infinity")?;
408                } else if *f == f64::NEG_INFINITY {
409                    m.serialize_entry("v", "-Infinity")?;
410                } else {
411                    m.serialize_entry("v", f)?;
412                }
413            }
414            Value::String(s) => write_tagged_str(&mut m, s)?,
415            Value::Uuid(u) => {
416                m.serialize_entry("t", "uuid")?;
417                m.serialize_entry("v", &uuid_hyphenated(*u))?;
418            }
419            Value::List(xs) => {
420                m.serialize_entry("t", "list")?;
421                m.serialize_entry("v", &TaggedListRef(xs))?;
422            }
423            Value::Map(map) => {
424                m.serialize_entry("t", "map")?;
425                m.serialize_entry("v", &TaggedMapRef(map))?;
426            }
427            // Invariant: this encoder records graph *property* values only,
428            // and a property is never a graph entity -- `sanitize_props`
429            // (relate-executor) rejects Node/Relationship/Path before
430            // persistence, and the documented v2 persistence codec
431            // (relate-model `serde_value`) errors with "graph entity is
432            // not a persistence property". Fail loudly instead of silently
433            // writing the entity as a null tag.
434            Value::Node(_) | Value::Relationship(_) | Value::Path(_) => {
435                return Err(serde::ser::Error::custom(
436                    "graph entity is not a persistence property",
437                ));
438            }
439            // Invariant, as for graph entities: a byte array is
440            // statement-scoped (ADR-0327) and the executor's property check
441            // rejects it with a typed TypeError before persistence. The
442            // tagged codec has no byte-array tag; fail loudly instead.
443            Value::Bytes(_) => {
444                return Err(serde::ser::Error::custom(
445                    "byte array is not a persistence property",
446                ));
447            }
448            Value::Temporal(t) => {
449                m.serialize_entry("t", t.kind_name())?;
450                m.serialize_entry("v", &t.iso_string())?;
451            }
452            Value::Point(p) => {
453                m.serialize_entry("t", "point")?;
454                m.serialize_entry("v", &TaggedPointRef(p))?;
455            }
456            Value::Vector { coord, values } => {
457                // serde_json's Map is a BTreeMap: keys serialize sorted, so
458                // "coord" precedes "t". Match the historical bytes.
459                m.serialize_entry("coord", coord.canonical_name())?;
460                m.serialize_entry("t", "vector")?;
461                m.serialize_entry("v", &TaggedListRef(values))?;
462            }
463        }
464        m.end()
465    }
466}
467
468struct TaggedListRef<'a>(&'a [Value]);
469impl serde::Serialize for TaggedListRef<'_> {
470    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
471        use serde::ser::SerializeSeq;
472        let mut seq = s.serialize_seq(Some(self.0.len()))?;
473        for v in self.0 {
474            seq.serialize_element(&TaggedRef(v))?;
475        }
476        seq.end()
477    }
478}
479
480struct TaggedMapRef<'a>(&'a BTreeMap<String, Value>);
481impl serde::Serialize for TaggedMapRef<'_> {
482    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
483        use serde::ser::SerializeMap;
484        let mut m = s.serialize_map(Some(self.0.len()))?;
485        for (k, v) in self.0 {
486            m.serialize_entry(k, &TaggedRef(v))?;
487        }
488        m.end()
489    }
490}
491
492struct TaggedPointRef<'a>(&'a PointValue);
493impl serde::Serialize for TaggedPointRef<'_> {
494    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
495        use serde::ser::SerializeMap;
496        let p = self.0;
497        let mut m = s.serialize_map(Some(4))?;
498        m.serialize_entry("srid", &p.srid)?;
499        m.serialize_entry("x", &p.x)?;
500        m.serialize_entry("y", &p.y)?;
501        m.serialize_entry("z", &p.z)?;
502        m.end()
503    }
504}
505
506impl serde::Serialize for Value {
507    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
508        // ADR-0462: one bounded pre-walk at the public entry keeps the
509        // recursive `TaggedRef` encoder inside the depth cap. Unreachable
510        // behind the checked constructors — a graph property cannot nest
511        // past the cap without a typed error at construction.
512        if !self.depth_within(MAX_VALUE_DEPTH) {
513            return Err(serde::ser::Error::custom(value_depth_exceeded("value")));
514        }
515        TaggedRef(self).serialize(serializer)
516    }
517}
518
519impl<'de> serde::Deserialize<'de> for Value {
520    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
521        let json = serde_json::Value::deserialize(deserializer)?;
522        Value::from_json_tagged(&json).map_err(serde::de::Error::custom)
523    }
524}
525
526fn map_to_json_plain<'a>(
527    m: impl IntoIterator<Item = (&'a String, &'a Value)>,
528    depth: u32,
529) -> serde_json::Value {
530    let mut o = serde_json::Map::new();
531    for (k, v) in m {
532        o.insert(k.clone(), v.to_json_plain_at(depth));
533    }
534    serde_json::Value::Object(o)
535}
536
537/// Plain-JSON form of a node, shared by the [`Value::Node`] arm and the
538/// [`Value::Path`] arm of [`Value::to_json_plain`], which renders each path
539/// element directly instead of cloning it into a [`Value`] and re-entering
540/// the dispatcher one arm down.
541fn node_json(n: &Node, depth: u32) -> serde_json::Value {
542    // `depth` is the node's ancestor-container count; the property values sit
543    // one container deeper. The guard matches the sibling container arms and
544    // returns the null form (ADR-0462).
545    let Some(next) = next_depth(depth) else {
546        return serde_json::Value::Null;
547    };
548    serde_json::json!({
549        "_type": "node",
550        "id": n.id,
551        "labels": n.labels,
552        "properties": map_to_json_plain(n.properties.iter(), next),
553    })
554}
555
556/// Plain-JSON form of a relationship (see [`node_json`]).
557fn rel_json(r: &Relationship, depth: u32) -> serde_json::Value {
558    let Some(next) = next_depth(depth) else {
559        return serde_json::Value::Null;
560    };
561    serde_json::json!({
562        "_type": "relationship",
563        "id": r.id,
564        "start": r.start,
565        "end": r.end,
566        "type": r.rel_type,
567        "properties": map_to_json_plain(r.properties.iter(), next),
568    })
569}