Skip to main content

relate_model/
serde_value.rs

1//! Serialization/deserialization support for CypherValue.
2//!
3//! Converts CypherValue to/from serde_json::Value for JSON persistence.
4//! Designed for Go JSON format compatibility.
5
6use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
7use indexmap::IndexMap;
8use serde_json::{Map as JsonMap, Value as JsonValue};
9
10use crate::value::{Coord2D, CypherValue, GeometryValue, IsoDuration, PointValue, VectorCoordKind};
11use crate::vector::coords::{Coord, VectorCoords};
12
13/// Invalid persistence value, with a JSON path to the offending member.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct EncodeError {
16    pub path: String,
17    pub message: String,
18}
19
20impl std::fmt::Display for EncodeError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        write!(f, "{}: {}", self.path, self.message)
23    }
24}
25
26impl std::error::Error for EncodeError {}
27
28fn encode_error(path: &str, message: impl Into<String>) -> EncodeError {
29    EncodeError {
30        path: path.into(),
31        message: message.into(),
32    }
33}
34
35/// A finite f64 is exactly representable as f32 only if its signed bits survive.
36pub fn float32_exact(f: f64) -> bool {
37    VectorCoordKind::Float32.is_exact(f)
38}
39
40fn finite_number(f: f64, path: &str) -> Result<JsonValue, EncodeError> {
41    serde_json::Number::from_f64(f)
42        .map(JsonValue::Number)
43        .ok_or_else(|| encode_error(path, "expected finite number"))
44}
45
46fn require_minute_offset(offset: &FixedOffset, path: &str) -> Result<(), EncodeError> {
47    if offset.local_minus_utc() % 60 != 0 {
48        return Err(encode_error(
49            path,
50            "offset must be a whole number of minutes",
51        ));
52    }
53    Ok(())
54}
55
56/// Encode a persistence value as v2 JSON, rejecting values that cannot round-trip.
57/// Temporal, spatial, duration and vector values use `__type` tags, while user
58/// maps containing `__type` use the versioned `map` escape.
59/// A `DateTime` also requires a minute-aligned fixed offset whose UTC instant
60/// plus offset fits chrono's local `NaiveDateTime` range. Otherwise this returns
61/// an [`EncodeError`] with the nested value path before RFC3339 formatting;
62/// `serde::Serialize` reports the same error.
63///
64/// ```
65/// use relate_model::{CypherValue, serde_value::{
66///     cypher_value_to_json, props_to_json, try_json_to_cypher_value_v2,
67/// }};
68/// use relate_model::value::PointValue;
69/// use indexmap::IndexMap;
70///
71/// let point = CypherValue::Point(PointValue::cartesian_3d(1.5, -2.25, 3.0));
72/// let value = CypherValue::Map(IndexMap::from([
73///     ("__type".into(), CypherValue::Str("user data".into())),
74///     ("place".into(), point),
75/// ]));
76/// let json = cypher_value_to_json(&value)?;
77/// assert_eq!(json["__type"], "map");
78/// assert_eq!(json["value"]["place"]["__type"], "point");
79/// assert_eq!(try_json_to_cypher_value_v2(&json)?, value);
80///
81/// let invalid = CypherValue::Point(PointValue::cartesian_3d(1.5, f64::INFINITY, 3.0));
82/// assert_eq!(cypher_value_to_json(&invalid).unwrap_err().path, "$.y");
83/// let props = IndexMap::from([("place".into(), invalid)]);
84/// assert_eq!(props_to_json(&props).unwrap_err().path, "$.place.y");
85/// # Ok::<(), Box<dyn std::error::Error>>(())
86/// ```
87///
88/// A fixed offset can be valid even when its local time lies outside chrono's
89/// range. Canonical expanded-year values *inside* the range still round-trip:
90///
91/// ```
92/// use chrono::{Duration, FixedOffset, NaiveDateTime, TimeZone};
93/// use relate_model::{CypherValue, serde_value::{
94///     cypher_value_to_json, props_to_json, try_json_to_cypher_value_v2,
95/// }};
96/// use indexmap::IndexMap;
97///
98/// let plus_one = FixedOffset::east_opt(3600).unwrap();
99/// let invalid = CypherValue::DateTime(plus_one.from_utc_datetime(&NaiveDateTime::MAX), None);
100/// let error = cypher_value_to_json(&invalid).unwrap_err();
101/// assert_eq!(error.path, "$");
102/// assert_eq!(error.message, "DateTime local time out of range");
103/// let nested = CypherValue::Map(IndexMap::from([("items".into(), CypherValue::List(vec![invalid]))]));
104/// let props = IndexMap::from([("payload".into(), nested)]);
105/// assert_eq!(props_to_json(&props).unwrap_err().path, "$.payload.items[0]");
106/// assert!(serde_json::to_value(&CypherValue::Map(props)).unwrap_err()
107///     .to_string().contains("$.payload.items[0]"));
108///
109/// for (utc, offset, expected) in [
110///     (NaiveDateTime::MAX - Duration::hours(1), 3600,
111///      "+262142-12-31T23:59:59.999999999+01:00"),
112///     (NaiveDateTime::MIN + Duration::hours(1), -3600,
113///      "-262143-01-01T00:00:00-01:00"),
114/// ] {
115///     let fixed = FixedOffset::east_opt(offset).unwrap();
116///     let value = CypherValue::DateTime(fixed.from_utc_datetime(&utc), None);
117///     let json = cypher_value_to_json(&value)?;
118///     assert_eq!(json["value"], expected);
119///     assert_eq!(try_json_to_cypher_value_v2(&json)?, value);
120///     assert_eq!(serde_json::from_value::<CypherValue>(serde_json::to_value(&value)?)?, value);
121/// }
122/// # Ok::<(), Box<dyn std::error::Error>>(())
123/// ```
124pub fn cypher_value_to_json(val: &CypherValue) -> Result<JsonValue, EncodeError> {
125    encode(val, "$")
126}
127
128fn encode(val: &CypherValue, path: &str) -> Result<JsonValue, EncodeError> {
129    Ok(match val {
130        CypherValue::Null => JsonValue::Null,
131        CypherValue::Bool(b) => JsonValue::Bool(*b),
132        CypherValue::Int(i) => JsonValue::Number((*i).into()),
133        CypherValue::Float(f) => finite_number(*f, path)?,
134        CypherValue::Str(s) => JsonValue::String(s.clone()),
135        CypherValue::List(items) => JsonValue::Array(
136            items
137                .iter()
138                .enumerate()
139                .map(|(i, item)| encode(item, &format!("{path}[{i}]")))
140                .collect::<Result<_, _>>()?,
141        ),
142        CypherValue::Map(map) => {
143            let obj = encode_map(map, path)?;
144            if map.contains_key("__type") {
145                serde_json::json!({"__type": "map", "value": obj})
146            } else {
147                JsonValue::Object(obj)
148            }
149        }
150        CypherValue::Date(d) => serde_json::json!({"__type": "date", "value": d.to_string()}),
151        CypherValue::Time(t, tz) => {
152            let mut obj = serde_json::json!({
153                "__type": "time", "value": t.format("%H:%M:%S%.f").to_string(),
154            });
155            if let Some(offset) = tz {
156                require_minute_offset(offset, path)?;
157                let secs = offset.local_minus_utc();
158                let h = secs.abs() / 3600;
159                let m = (secs.abs() % 3600) / 60;
160                obj["offset"] =
161                    JsonValue::String(format!("{}{h:02}:{m:02}", if secs < 0 { '-' } else { '+' }));
162            }
163            obj
164        }
165        CypherValue::DateTime(dt, tz_name) => {
166            require_minute_offset(dt.offset(), path)?;
167            if dt
168                .naive_utc()
169                .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
170                .is_none()
171            {
172                return Err(encode_error(path, "DateTime local time out of range"));
173            }
174            let mut obj = serde_json::json!({"__type": "datetime", "value": dt.to_rfc3339()});
175            if let Some(name) = tz_name {
176                obj["timezone"] = JsonValue::String(name.clone());
177            }
178            obj
179        }
180        CypherValue::LocalDateTime(ldt) => serde_json::json!({
181            "__type": "localdatetime", "value": ldt.format("%Y-%m-%dT%H:%M:%S%.f").to_string(),
182        }),
183        CypherValue::Duration(d) => serde_json::json!({
184            "__type": "duration", "months": d.months, "days": d.days,
185            "seconds": d.seconds, "nanoseconds": d.nanoseconds,
186        }),
187        CypherValue::Point(p) => {
188            let mut obj = serde_json::json!({"__type": "point", "srid": p.srid});
189            obj["x"] = finite_number(p.x, &format!("{path}.x"))?;
190            obj["y"] = finite_number(p.y, &format!("{path}.y"))?;
191            if let Some(z) = p.z {
192                obj["z"] = finite_number(z, &format!("{path}.z"))?;
193            }
194            obj
195        }
196        CypherValue::Geometry(g) => encode_geometry(g, path)?,
197        CypherValue::Vector { coord, coords } => {
198            // The canonical constructor owns the whole exactness invariant
199            // (ADR-0706): family/kind pairing, widths, precision,
200            // finiteness, and `dim == coords.len()`. A `Vector` that
201            // reaches here is encodable by construction — the per-
202            // coordinate checks and the dim check this arm used to carry
203            // were that invariant's second spelling, now deleted. One
204            // walk over `iter()`'s two coordinate forms.
205            // The error path is one string, built once (not per
206            // coordinate) — a finite coordinate cannot use it.
207            let values_path = format!("{path}.values");
208            let encoded = coords
209                .iter()
210                .map(|c| match c {
211                    Coord::I(n) => Ok(JsonValue::Number(n.into())),
212                    Coord::F(f) => finite_number(f, &values_path),
213                })
214                .collect::<Result<Vec<_>, _>>()?;
215            serde_json::json!({"__type": "vector", "coord": coord.canonical_name(), "dim": coords.len(), "values": encoded})
216        }
217        CypherValue::Node { .. } | CypherValue::Relationship { .. } | CypherValue::Path { .. } => {
218            return Err(encode_error(
219                path,
220                "graph entity is not a persistence property",
221            ));
222        }
223    })
224}
225
226fn encode_map(
227    map: &IndexMap<String, CypherValue>,
228    path: &str,
229) -> Result<JsonMap<String, JsonValue>, EncodeError> {
230    map.iter()
231        .map(|(key, value)| Ok((key.clone(), encode(value, &format!("{path}.{key}"))?)))
232        .collect()
233}
234
235fn encode_coords(coords: &[Coord2D], path: &str) -> Result<JsonValue, EncodeError> {
236    Ok(JsonValue::Array(
237        coords
238            .iter()
239            .enumerate()
240            .map(|(i, c)| {
241                Ok(JsonValue::Array(vec![
242                    finite_number(c[0], &format!("{path}[{i}][0]"))?,
243                    finite_number(c[1], &format!("{path}[{i}][1]"))?,
244                ]))
245            })
246            .collect::<Result<_, EncodeError>>()?,
247    ))
248}
249
250fn encode_nested_coords(groups: &[Vec<Coord2D>], path: &str) -> Result<JsonValue, EncodeError> {
251    Ok(JsonValue::Array(
252        groups
253            .iter()
254            .enumerate()
255            .map(|(i, coords)| encode_coords(coords, &format!("{path}[{i}]")))
256            .collect::<Result<_, _>>()?,
257    ))
258}
259
260fn encode_geometry(g: &GeometryValue, path: &str) -> Result<JsonValue, EncodeError> {
261    let mut obj = serde_json::json!({
262        "__type": "geometry", "geometry_type": g.type_name(), "srid": g.srid(),
263    });
264    let at = format!("{path}.coordinates");
265    match g {
266        GeometryValue::LineString { coordinates, .. } => {
267            obj["coordinates"] = encode_coords(coordinates, &at)?
268        }
269        GeometryValue::Polygon { rings, .. } => {
270            obj["coordinates"] = encode_nested_coords(rings, &at)?
271        }
272        GeometryValue::MultiPoint { points, .. } => {
273            obj["coordinates"] = encode_coords(points, &at)?
274        }
275        GeometryValue::MultiLineString { lines, .. } => {
276            obj["coordinates"] = encode_nested_coords(lines, &at)?
277        }
278        GeometryValue::MultiPolygon { polygons, .. } => {
279            obj["coordinates"] = JsonValue::Array(
280                polygons
281                    .iter()
282                    .enumerate()
283                    .map(|(i, polygon)| encode_nested_coords(polygon, &format!("{at}[{i}]")))
284                    .collect::<Result<_, _>>()?,
285            );
286        }
287        GeometryValue::GeometryCollection { geometries, .. } => {
288            obj["geometries"] = JsonValue::Array(
289                geometries
290                    .iter()
291                    .enumerate()
292                    .map(|(i, geometry)| {
293                        encode_geometry(geometry, &format!("{path}.geometries[{i}]"))
294                    })
295                    .collect::<Result<_, _>>()?,
296            );
297        }
298    }
299    Ok(obj)
300}
301
302/// An invalid persistence value, with a JSON path to the offending field.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct DecodeError {
305    pub path: String,
306    pub message: String,
307}
308
309impl std::fmt::Display for DecodeError {
310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        write!(f, "{}: {}", self.path, self.message)
312    }
313}
314
315impl std::error::Error for DecodeError {}
316
317fn invalid(path: &str, message: impl Into<String>) -> DecodeError {
318    DecodeError {
319        path: path.into(),
320        message: message.into(),
321    }
322}
323
324fn field<'a>(
325    obj: &'a JsonMap<String, JsonValue>,
326    name: &str,
327    path: &str,
328) -> Result<&'a JsonValue, DecodeError> {
329    obj.get(name)
330        .ok_or_else(|| invalid(&format!("{path}.{name}"), "missing required field"))
331}
332
333fn string<'a>(val: &'a JsonValue, path: &str) -> Result<&'a str, DecodeError> {
334    val.as_str().ok_or_else(|| invalid(path, "expected string"))
335}
336
337fn integer(val: &JsonValue, path: &str) -> Result<i64, DecodeError> {
338    val.as_i64()
339        .ok_or_else(|| invalid(path, "expected signed 64-bit integer"))
340}
341
342fn number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
343    val.as_f64()
344        .filter(|n| n.is_finite())
345        .ok_or_else(|| invalid(path, "expected finite number"))
346}
347
348fn array<'a>(val: &'a JsonValue, path: &str) -> Result<&'a [JsonValue], DecodeError> {
349    val.as_array()
350        .map(Vec::as_slice)
351        .ok_or_else(|| invalid(path, "expected array"))
352}
353
354fn keys(obj: &JsonMap<String, JsonValue>, allowed: &[&str], path: &str) -> Result<(), DecodeError> {
355    if let Some(key) = obj.keys().find(|key| !allowed.contains(&key.as_str())) {
356        return Err(invalid(&format!("{path}.{key}"), "unrecognized field"));
357    }
358    Ok(())
359}
360
361/// Decode standalone persistence JSON (which follows version-2 tag rules).
362pub fn try_json_to_cypher_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
363    try_json_to_cypher_value_v2(val)
364}
365
366/// Decode version-2 snapshot values. Known tags are strict; the exact
367/// `{"__type":"map","value":{...}}` form escapes ordinary maps.
368///
369/// ```
370/// use relate_model::{CypherValue, serde_value::{
371///     cypher_value_to_json, try_json_to_cypher_value_v2,
372///     try_json_to_cypher_value_legacy, try_json_to_param_value,
373/// }};
374/// use serde_json::json;
375///
376/// let point = json!({"__type":"point", "srid":4326, "x":1.5, "y":-2.25});
377/// assert!(matches!(try_json_to_cypher_value_v2(&point)?, CypherValue::Point(_)));
378/// // A v2 escaped map cannot be mistaken for a point.
379/// let escaped = json!({"__type":"map", "value":{"__type":"point", "x":1}});
380/// let map = try_json_to_cypher_value_v2(&escaped)?;
381/// assert!(matches!(map, CypherValue::Map(_)));
382/// assert_eq!(cypher_value_to_json(&map)?, escaped);
383/// // In v1, __type=map is ordinary data; its nested values still use v1 rules.
384/// let legacy_map = json!({"__type":"map", "value":{"x":1}});
385/// let legacy = try_json_to_cypher_value_legacy(&legacy_map)?;
386/// assert!(matches!(&legacy, CypherValue::Map(m) if m.contains_key("value")));
387/// assert!(try_json_to_cypher_value_legacy(&escaped).is_err());
388/// // User parameters never infer typed values from __type.
389/// assert!(matches!(try_json_to_param_value(&point)?, CypherValue::Map(_)));
390///
391/// let invalid = json!({"__type":"point", "srid":4326, "x":1.5});
392/// assert_eq!(try_json_to_cypher_value_v2(&invalid).unwrap_err().path, "$.y");
393/// assert!(serde_json::from_value::<CypherValue>(invalid).is_err());
394/// # Ok::<(), Box<dyn std::error::Error>>(())
395/// ```
396pub fn try_json_to_cypher_value_v2(val: &JsonValue) -> Result<CypherValue, DecodeError> {
397    decode(val, "$", DecodeMode::V2)
398}
399
400/// Decode version-1 snapshots. `__type=map` is ordinary map data in v1;
401/// valid historical typed tags still have their original interpretation.
402pub fn try_json_to_cypher_value_legacy(val: &JsonValue) -> Result<CypherValue, DecodeError> {
403    decode(val, "$", DecodeMode::Legacy)
404}
405
406/// Decode user-supplied JSON parameters. Objects are always ordinary maps,
407/// including those with `__type`; typed values require explicit query constructors.
408pub fn try_json_to_param_value(val: &JsonValue) -> Result<CypherValue, DecodeError> {
409    decode(val, "$", DecodeMode::Parameter)
410}
411
412/// Selects whether `__type` is interpreted as a persistence tag and whether
413/// the v2 map envelope is recognized. Parameters treat every object as a map.
414#[derive(Clone, Copy, PartialEq, Eq)]
415enum DecodeMode {
416    Legacy,
417    V2,
418    Parameter,
419}
420
421fn decode_map(
422    obj: &JsonMap<String, JsonValue>,
423    path: &str,
424    mode: DecodeMode,
425) -> Result<CypherValue, DecodeError> {
426    let mut result = IndexMap::new();
427    for (key, value) in obj {
428        let child = format!("{path}.{key}");
429        result.insert(key.clone(), decode(value, &child, mode)?);
430    }
431    Ok(CypherValue::Map(result))
432}
433
434fn decode(val: &JsonValue, path: &str, mode: DecodeMode) -> Result<CypherValue, DecodeError> {
435    match val {
436        JsonValue::Null => Ok(CypherValue::Null),
437        JsonValue::Bool(b) => Ok(CypherValue::Bool(*b)),
438        JsonValue::Number(n) => {
439            if let Some(i) = n.as_i64() {
440                Ok(CypherValue::Int(i))
441            } else if n.is_u64() {
442                Err(invalid(path, "integer exceeds i64 range"))
443            } else {
444                Ok(CypherValue::Float(number(val, path)?))
445            }
446        }
447        JsonValue::String(s) => Ok(CypherValue::Str(s.clone())),
448        JsonValue::Array(items) => items
449            .iter()
450            .enumerate()
451            .map(|(i, item)| decode(item, &format!("{path}[{i}]"), mode))
452            .collect::<Result<Vec<_>, _>>()
453            .map(CypherValue::List),
454        JsonValue::Object(obj) => {
455            if mode == DecodeMode::Parameter {
456                return decode_map(obj, path, mode);
457            }
458            let Some(tag) = obj.get("__type").and_then(JsonValue::as_str) else {
459                return decode_map(obj, path, mode);
460            };
461            if tag == "map" && mode == DecodeMode::V2 {
462                keys(obj, &["__type", "value"], path)?;
463                let contents = field(obj, "value", path)?
464                    .as_object()
465                    .ok_or_else(|| invalid(&format!("{path}.value"), "expected object"))?;
466                return decode_map(contents, path, mode);
467            }
468            let value = match tag {
469                "date" => {
470                    keys(obj, &["__type", "value"], path)?;
471                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
472                    CypherValue::Date(
473                        s.parse::<NaiveDate>()
474                            .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
475                    )
476                }
477                "time" => {
478                    keys(obj, &["__type", "value", "offset"], path)?;
479                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
480                    let t = NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
481                        .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
482                    let offset =
483                        obj.get("offset")
484                            .map(|o| {
485                                parse_numeric_offset(string(o, &format!("{path}.offset"))?)
486                                    .ok_or_else(|| {
487                                        invalid(
488                                            &format!("{path}.offset"),
489                                            "expected ASCII ±HH:MM offset within 24 hours",
490                                        )
491                                    })
492                            })
493                            .transpose()?;
494                    CypherValue::Time(t, offset)
495                }
496                "datetime" => {
497                    keys(obj, &["__type", "value", "timezone"], path)?;
498                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
499                    let dt = parse_persistence_datetime(s)
500                        .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?;
501                    let tz = obj
502                        .get("timezone")
503                        .map(|v| string(v, &format!("{path}.timezone")).map(str::to_owned))
504                        .transpose()?;
505                    CypherValue::DateTime(dt, tz)
506                }
507                "localdatetime" => {
508                    keys(obj, &["__type", "value"], path)?;
509                    let s = string(field(obj, "value", path)?, &format!("{path}.value"))?;
510                    CypherValue::LocalDateTime(
511                        NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
512                            .map_err(|e| invalid(&format!("{path}.value"), e.to_string()))?,
513                    )
514                }
515                "duration" => {
516                    keys(
517                        obj,
518                        &["__type", "months", "days", "seconds", "nanoseconds"],
519                        path,
520                    )?;
521                    let component =
522                        |name: &str| integer(field(obj, name, path)?, &format!("{path}.{name}"));
523                    CypherValue::Duration(IsoDuration::new(
524                        component("months")?,
525                        component("days")?,
526                        component("seconds")?,
527                        component("nanoseconds")?,
528                    ))
529                }
530                "point" => {
531                    keys(obj, &["__type", "srid", "x", "y", "z"], path)?;
532                    let srid =
533                        i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
534                            .map_err(|_| {
535                                invalid(&format!("{path}.srid"), "SRID exceeds i32 range")
536                            })?;
537                    let coordinate =
538                        |name: &str| number(field(obj, name, path)?, &format!("{path}.{name}"));
539                    let z = obj
540                        .get("z")
541                        .map(|v| number(v, &format!("{path}.z")))
542                        .transpose()?;
543                    CypherValue::Point(PointValue {
544                        srid,
545                        x: coordinate("x")?,
546                        y: coordinate("y")?,
547                        z,
548                    })
549                }
550                "geometry" => CypherValue::Geometry(decode_geometry(obj, path, mode)?),
551                "vector" => decode_vector(obj, path)?,
552                _ => return decode_map(obj, path, mode),
553            };
554            Ok(value)
555        }
556    }
557}
558
559fn decode_vector(obj: &JsonMap<String, JsonValue>, path: &str) -> Result<CypherValue, DecodeError> {
560    keys(obj, &["__type", "coord", "dim", "values"], path)?;
561    let coord_path = format!("{path}.coord");
562    let coord =
563        VectorCoordKind::from_canonical_name(string(field(obj, "coord", path)?, &coord_path)?)
564            .ok_or_else(|| invalid(&coord_path, "unknown vector coordinate type"))?;
565    let dim_path = format!("{path}.dim");
566    let dim = usize::try_from(
567        field(obj, "dim", path)?
568            .as_u64()
569            .ok_or_else(|| invalid(&dim_path, "expected nonnegative integer dimension"))?,
570    )
571    .map_err(|_| invalid(&dim_path, "dimension exceeds usize range"))?;
572    let values_path = format!("{path}.values");
573    let items = array(field(obj, "values", path)?, &values_path)?;
574    if dim != items.len() {
575        return Err(invalid(&dim_path, "dimension does not match values length"));
576    }
577    // The decode-side classification (fail-closed with this codec's own
578    // error detail), landing in the ONE family-selection policy
579    // (ADR-0706's `VectorCoords::from_coords`). An integer JSON number
580    // under a float kind decodes into the `Int` family — the very shape
581    // the encoder writes for one, so a checkpoint round-trips; its
582    // equality with the float spelling is the exact numeric rule.
583    let mut tokens = Vec::with_capacity(items.len());
584    if coord.is_integer() {
585        for (i, item) in items.iter().enumerate() {
586            let at = format!("{values_path}[{i}]");
587            let n = integer(item, &at)?;
588            if !coord.holds_int(n) {
589                return Err(invalid(
590                    &at,
591                    format!("{} out of range", coord.canonical_name()),
592                ));
593            }
594            tokens.push(Coord::I(n));
595        }
596    } else {
597        for (i, item) in items.iter().enumerate() {
598            let at = format!("{values_path}[{i}]");
599            match item {
600                JsonValue::Number(n) if n.is_i64() || n.is_u64() => {
601                    tokens.push(Coord::I(integer(item, &at)?));
602                }
603                _ => {
604                    let f = float_number(item, &at)?;
605                    if !coord.is_exact(f) {
606                        return Err(invalid(
607                            &at,
608                            format!("{} out of range or loses precision", coord.canonical_name()),
609                        ));
610                    }
611                    tokens.push(Coord::F(f));
612                }
613            }
614        }
615    }
616    let coords = VectorCoords::from_coords(coord, tokens.into_iter())
617        .ok_or_else(|| invalid(&values_path, "coordinates mix integer and float families"))?;
618    Ok(CypherValue::vector(coord, coords))
619}
620
621fn float_number(val: &JsonValue, path: &str) -> Result<f64, DecodeError> {
622    if !val.is_f64() {
623        return Err(invalid(path, "expected floating-point number"));
624    }
625    number(val, path)
626}
627
628fn decode_geometry(
629    obj: &JsonMap<String, JsonValue>,
630    path: &str,
631    mode: DecodeMode,
632) -> Result<GeometryValue, DecodeError> {
633    let srid = i32::try_from(integer(field(obj, "srid", path)?, &format!("{path}.srid"))?)
634        .map_err(|_| invalid(&format!("{path}.srid"), "SRID exceeds i32 range"))?;
635    let kind = string(
636        field(obj, "geometry_type", path)?,
637        &format!("{path}.geometry_type"),
638    )?;
639    let coords_path = format!("{path}.coordinates");
640    let geometry = match kind {
641        "LineString" | "MultiPoint" => {
642            keys(
643                obj,
644                &["__type", "geometry_type", "srid", "coordinates"],
645                path,
646            )?;
647            let coords = decode_coords(field(obj, "coordinates", path)?, &coords_path)?;
648            if kind == "LineString" {
649                GeometryValue::LineString {
650                    coordinates: coords,
651                    srid,
652                }
653            } else {
654                GeometryValue::MultiPoint {
655                    points: coords,
656                    srid,
657                }
658            }
659        }
660        "Polygon" | "MultiLineString" => {
661            keys(
662                obj,
663                &["__type", "geometry_type", "srid", "coordinates"],
664                path,
665            )?;
666            let rings = decode_nested_coords(field(obj, "coordinates", path)?, &coords_path)?;
667            if kind == "Polygon" {
668                GeometryValue::Polygon { rings, srid }
669            } else {
670                GeometryValue::MultiLineString { lines: rings, srid }
671            }
672        }
673        "MultiPolygon" => {
674            keys(
675                obj,
676                &["__type", "geometry_type", "srid", "coordinates"],
677                path,
678            )?;
679            let polygons = array(field(obj, "coordinates", path)?, &coords_path)?
680                .iter()
681                .enumerate()
682                .map(|(i, v)| decode_nested_coords(v, &format!("{coords_path}[{i}]")))
683                .collect::<Result<_, _>>()?;
684            GeometryValue::MultiPolygon { polygons, srid }
685        }
686        "GeometryCollection" => {
687            keys(
688                obj,
689                &["__type", "geometry_type", "srid", "geometries"],
690                path,
691            )?;
692            let geometries = array(
693                field(obj, "geometries", path)?,
694                &format!("{path}.geometries"),
695            )?
696            .iter()
697            .enumerate()
698            .map(|(i, item)| {
699                let at = format!("{path}.geometries[{i}]");
700                match decode(item, &at, mode)? {
701                    CypherValue::Geometry(g) => Ok(g),
702                    _ => Err(invalid(&at, "expected tagged geometry")),
703                }
704            })
705            .collect::<Result<_, _>>()?;
706            GeometryValue::GeometryCollection { geometries, srid }
707        }
708        _ => {
709            return Err(invalid(
710                &format!("{path}.geometry_type"),
711                "unknown geometry type",
712            ))
713        }
714    };
715    Ok(geometry)
716}
717
718fn decode_nested_coords(val: &JsonValue, path: &str) -> Result<Vec<Vec<Coord2D>>, DecodeError> {
719    array(val, path)?
720        .iter()
721        .enumerate()
722        .map(|(i, v)| decode_coords(v, &format!("{path}[{i}]")))
723        .collect()
724}
725
726fn decode_coords(val: &JsonValue, path: &str) -> Result<Vec<Coord2D>, DecodeError> {
727    array(val, path)?
728        .iter()
729        .enumerate()
730        .map(|(i, v)| {
731            let at = format!("{path}[{i}]");
732            let pair = array(v, &at)?;
733            if pair.len() != 2 {
734                return Err(invalid(&at, "expected exactly two coordinates"));
735            }
736            Ok([
737                number(&pair[0], &format!("{at}[0]"))?,
738                number(&pair[1], &format!("{at}[1]"))?,
739            ])
740        })
741        .collect()
742}
743
744/// Convert a CypherValue property map to a serde_json::Map, retaining key paths.
745pub fn props_to_json(
746    props: &IndexMap<String, CypherValue>,
747) -> Result<JsonMap<String, JsonValue>, EncodeError> {
748    encode_map(props, "$")
749}
750
751/// Decode standalone property values following version-2 tag rules.
752pub fn try_json_to_props(
753    obj: &JsonMap<String, JsonValue>,
754) -> Result<IndexMap<String, CypherValue>, DecodeError> {
755    try_json_to_props_v2(obj)
756}
757
758/// Decode version-2 snapshot properties, retaining property-key error paths.
759pub fn try_json_to_props_v2(
760    obj: &JsonMap<String, JsonValue>,
761) -> Result<IndexMap<String, CypherValue>, DecodeError> {
762    decode_props(obj, DecodeMode::V2)
763}
764
765/// Decode version-1 snapshot properties (where `__type=map` was ordinary data).
766pub fn try_json_to_props_legacy(
767    obj: &JsonMap<String, JsonValue>,
768) -> Result<IndexMap<String, CypherValue>, DecodeError> {
769    decode_props(obj, DecodeMode::Legacy)
770}
771
772/// Decode version-2 properties from borrowed `(key, value)` entries, so a
773/// caller holding any keyed collection decodes without rebuilding a map.
774pub fn try_json_entries_to_props_v2<'a>(
775    entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
776) -> Result<IndexMap<String, CypherValue>, DecodeError> {
777    decode_props(entries, DecodeMode::V2)
778}
779
780/// [`try_json_entries_to_props_v2`] for version-1 properties.
781pub fn try_json_entries_to_props_legacy<'a>(
782    entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
783) -> Result<IndexMap<String, CypherValue>, DecodeError> {
784    decode_props(entries, DecodeMode::Legacy)
785}
786
787fn decode_props<'a>(
788    entries: impl IntoIterator<Item = (&'a String, &'a JsonValue)>,
789    mode: DecodeMode,
790) -> Result<IndexMap<String, CypherValue>, DecodeError> {
791    entries
792        .into_iter()
793        .map(|(key, value)| Ok((key.clone(), decode(value, &format!("$.{key}"), mode)?)))
794        .collect()
795}
796
797// ---- serde::Serialize / Deserialize impls for CypherValue ----
798
799impl serde::Serialize for CypherValue {
800    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
801    where
802        S: serde::Serializer,
803    {
804        let json = cypher_value_to_json(self).map_err(serde::ser::Error::custom)?;
805        json.serialize(serializer)
806    }
807}
808
809impl<'de> serde::Deserialize<'de> for CypherValue {
810    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
811    where
812        D: serde::Deserializer<'de>,
813    {
814        let json = JsonValue::deserialize(deserializer)?;
815        try_json_to_cypher_value(&json).map_err(serde::de::Error::custom)
816    }
817}
818
819// chrono's RFC 3339 parser rejects expanded years (e.g. +262142) that its
820// to_rfc3339 writer emits. Accept only that exact canonical writer form.
821fn parse_persistence_datetime(s: &str) -> Result<DateTime<FixedOffset>, chrono::ParseError> {
822    match DateTime::parse_from_rfc3339(s) {
823        Ok(dt) => Ok(dt),
824        Err(original) => {
825            let bytes = s.as_bytes();
826            let year_end = 1 + bytes
827                .iter()
828                .skip(1)
829                .take_while(|b| b.is_ascii_digit())
830                .count();
831            if !matches!(bytes.first(), Some(b'+' | b'-'))
832                || year_end < 6
833                || bytes.get(year_end) != Some(&b'-')
834            {
835                return Err(original);
836            }
837            let dt = DateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f%:z")?;
838            if dt
839                .naive_utc()
840                .checked_add_signed(Duration::seconds(i64::from(dt.offset().local_minus_utc())))
841                .is_some()
842                && dt.to_rfc3339() == s
843            {
844                Ok(dt)
845            } else {
846                Err(original)
847            }
848        }
849    }
850}
851
852/// Parse exactly six ASCII bytes in signed `±HH:MM` form into a fixed offset.
853///
854/// The sign, two hour digits, colon, and two minute digits are required. Minutes
855/// must be at most 59, and the resulting offset must fit chrono's `FixedOffset`
856/// range. Returns `None` for malformed or out-of-range input, including
857/// non-ASCII text, without panicking.
858///
859/// ```
860/// use relate_model::serde_value::parse_numeric_offset;
861///
862/// assert_eq!(parse_numeric_offset("+02:30").unwrap().local_minus_utc(), 9_000);
863/// assert_eq!(parse_numeric_offset("-05:45").unwrap().local_minus_utc(), -20_700);
864/// assert!(parse_numeric_offset("+00:60").is_none());
865/// assert!(parse_numeric_offset("é+02:30").is_none());
866/// ```
867pub fn parse_numeric_offset(s: &str) -> Option<FixedOffset> {
868    let bytes = s.as_bytes();
869    if bytes.len() != 6 || !bytes.is_ascii() || bytes[3] != b':' {
870        return None;
871    }
872    let sign: i32 = match bytes[0] {
873        b'+' => 1,
874        b'-' => -1,
875        _ => return None,
876    };
877    let digit = |b: u8| -> Option<i32> { b.is_ascii_digit().then(|| i32::from(b - b'0')) };
878    let h = digit(bytes[1])?
879        .checked_mul(10)?
880        .checked_add(digit(bytes[2])?)?;
881    let m = digit(bytes[4])?
882        .checked_mul(10)?
883        .checked_add(digit(bytes[5])?)?;
884    if m > 59 {
885        return None;
886    }
887    let seconds = h
888        .checked_mul(3600)?
889        .checked_add(m.checked_mul(60)?)?
890        .checked_mul(sign)?;
891    FixedOffset::east_opt(seconds)
892}
893
894#[cfg(test)]
895mod tests;