Skip to main content

flow_toolkit/
data.rs

1//! Values converted under the value encoding (`abi.md`, *The value
2//! encoding* and *Decoding*): [`Data`] for every Rust type a Flow data type
3//! maps to, and the pieces generated records and enums are written with.
4//!
5//! Encoding writes what the table says, numbers exactly; decoding is
6//! directed by the type and strict, as the runtime's is: nothing is coerced,
7//! guessed, defaulted or repaired. A record ignores a field it does not
8//! declare, and an `Option` field is left out for `None` and read as `None`
9//! when missing or `null`; anywhere else an `Option` is an ordinary enum.
10//! The scalars whose text has rules of its own — `Int`, `Bytes`,
11//! `Duration` and `Instant` — are read by the runtime's own decoder.
12
13use std::collections::{BTreeMap, BTreeSet};
14use std::convert::Infallible;
15use std::sync::LazyLock;
16
17use flow_abi::{Catalog, Json, Limits, Mode, Type};
18use flow_value::{Constructor, Decimal, Duration, EnumShape, Instant, Int, Payload, Value};
19
20pub use flow_abi::DecodeError;
21
22/// Parses exact JSON syntax with the toolkit's bounded input limits.
23/// A generic Tool value still requires validation through its invocation codec.
24pub fn parse_json(text: &str) -> Result<Json, DecodeError> {
25    flow_abi::parse(text, &LIMITS)
26}
27
28/// A Rust type that a Flow data type maps to, converted under the encoding.
29pub trait Data: Sized {
30    /// Whether this is `Text`, whose dictionaries encode as JSON objects.
31    const TEXT: bool = false;
32
33    /// The value's JSON.
34    fn encode(&self) -> Json;
35
36    /// The value `json` encodes, or why it encodes none.
37    fn decode(json: &Json) -> Result<Self, DecodeError>;
38}
39
40/// `Bytes`: raw bytes, encoded as standard base64 with padding.
41#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
42pub struct Bytes(pub Vec<u8>);
43
44impl From<Vec<u8>> for Bytes {
45    fn from(bytes: Vec<u8>) -> Self {
46        Bytes(bytes)
47    }
48}
49
50impl From<&[u8]> for Bytes {
51    fn from(bytes: &[u8]) -> Self {
52        Bytes(bytes.to_vec())
53    }
54}
55
56/// A decoding failure at the whole value.
57pub fn refused(problem: impl Into<String>) -> DecodeError {
58    DecodeError {
59        path: String::new(),
60        problem: problem.into(),
61        kind: flow_abi::DecodeErrorKind::Invalid,
62    }
63}
64
65/// `error`, found inside the part `step` names: a field or constructor's
66/// name, or `[index]`, or `["key"]`.
67pub fn inside(mut error: DecodeError, step: &str) -> DecodeError {
68    error.path = if error.path.is_empty() {
69        step.to_owned()
70    } else if error.path.starts_with('[') {
71        format!("{step}{}", error.path)
72    } else {
73        format!("{step}.{}", error.path)
74    };
75    error
76}
77
78/// What `read` makes of `json`, any failure located inside `step`.
79pub fn within<T>(
80    json: &Json,
81    step: &str,
82    read: impl FnOnce(&Json) -> Result<T, DecodeError>,
83) -> Result<T, DecodeError> {
84    read(json).map_err(|error| inside(error, step))
85}
86
87fn expected(what: &str, json: &Json) -> DecodeError {
88    refused(format!("should be {what}, not {}", json.kind()))
89}
90
91/// How large a value the toolkit reads: well past what any host sends.
92pub(crate) const LIMITS: Limits = Limits {
93    depth: 1_024,
94    int_bits: 16_777_216,
95    text_bytes: 1_073_741_824,
96};
97
98/// The value of the built-in type `ty` that `json` encodes, read by the
99/// runtime's own decoder.
100fn scalar<T>(ty: &Type, json: &Json, take: fn(Value) -> Option<T>) -> Result<T, DecodeError> {
101    static CATALOG: LazyLock<Catalog> = LazyLock::new(|| {
102        let option = EnumShape::new(
103            "Option",
104            [
105                Constructor::new("None", Payload::None),
106                Constructor::new("Some", Payload::Positional(1)),
107            ],
108        );
109        Catalog::new(Vec::new(), option, None).expect("std's Option has None and Some")
110    });
111    let value = flow_abi::decode(&CATALOG, ty, json, Mode::Reply, &LIMITS)?;
112    Ok(take(value).expect("the decoder builds the type it is asked for"))
113}
114
115impl Data for Int {
116    fn encode(&self) -> Json {
117        Json::Number(Decimal::from(self))
118    }
119
120    fn decode(json: &Json) -> Result<Self, DecodeError> {
121        scalar(&Type::Int, json, |value| match value {
122            Value::Int(int) => Some(int),
123            _ => None,
124        })
125    }
126}
127
128impl Data for Decimal {
129    fn encode(&self) -> Json {
130        Json::Number(self.clone())
131    }
132
133    fn decode(json: &Json) -> Result<Self, DecodeError> {
134        match json {
135            Json::Number(number) => Ok(number.clone()),
136            other => Err(expected("a number", other)),
137        }
138    }
139}
140
141impl Data for bool {
142    fn encode(&self) -> Json {
143        Json::Bool(*self)
144    }
145
146    fn decode(json: &Json) -> Result<Self, DecodeError> {
147        match json {
148            Json::Bool(value) => Ok(*value),
149            other => Err(expected("a boolean", other)),
150        }
151    }
152}
153
154impl Data for String {
155    const TEXT: bool = true;
156
157    fn encode(&self) -> Json {
158        Json::String(self.clone())
159    }
160
161    fn decode(json: &Json) -> Result<Self, DecodeError> {
162        match json {
163            Json::String(text) => Ok(text.clone()),
164            other => Err(expected("a string", other)),
165        }
166    }
167}
168
169impl Data for Bytes {
170    fn encode(&self) -> Json {
171        Json::String(flow_value::Bytes::new(&self.0).to_base64())
172    }
173
174    fn decode(json: &Json) -> Result<Self, DecodeError> {
175        scalar(&Type::Bytes, json, |value| match value {
176            Value::Bytes(bytes) => Some(Bytes(bytes.as_slice().to_vec())),
177            _ => None,
178        })
179    }
180}
181
182impl Data for Duration {
183    fn encode(&self) -> Json {
184        Json::String(self.to_string())
185    }
186
187    fn decode(json: &Json) -> Result<Self, DecodeError> {
188        scalar(&Type::Duration, json, |value| match value {
189            Value::Duration(duration) => Some(duration),
190            _ => None,
191        })
192    }
193}
194
195impl Data for Instant {
196    fn encode(&self) -> Json {
197        Json::String(self.to_string())
198    }
199
200    fn decode(json: &Json) -> Result<Self, DecodeError> {
201        scalar(&Type::Instant, json, |value| match value {
202            Value::Instant(instant) => Some(instant),
203            _ => None,
204        })
205    }
206}
207
208/// `Unit`, the empty array.
209impl Data for () {
210    fn encode(&self) -> Json {
211        Json::Array(Vec::new())
212    }
213
214    fn decode(json: &Json) -> Result<Self, DecodeError> {
215        match json {
216            Json::Array(items) if items.is_empty() => Ok(()),
217            other => Err(expected("the empty array", other)),
218        }
219    }
220}
221
222/// `Never`, which has no values.
223impl Data for Infallible {
224    fn encode(&self) -> Json {
225        match *self {}
226    }
227
228    fn decode(_: &Json) -> Result<Self, DecodeError> {
229        Err(refused("is of `Never`, which has no values"))
230    }
231}
232
233/// `json.Value`, std's enum for raw JSON, with its equality and order
234/// (`data.md`; `types.md`, *Equality, ordering and text*): constructors in
235/// declaration order, `Null` lowest; numbers by value, so `1.0` is `1`;
236/// text by code point; lists element by element; and an object as a
237/// `Dict<Text, json.Value>`, whatever order its members were written in.
238/// It encodes as the JSON value it stands for.
239#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
240pub enum JsonValue {
241    /// `null`.
242    Null,
243    /// `true` or `false`.
244    Bool(bool),
245    /// A number, exactly.
246    Number(Decimal),
247    /// A string.
248    Text(String),
249    /// An array.
250    List(Vec<JsonValue>),
251    /// An object, its members by name.
252    Object(BTreeMap<String, JsonValue>),
253}
254
255impl Data for JsonValue {
256    fn encode(&self) -> Json {
257        match self {
258            JsonValue::Null => Json::Null,
259            JsonValue::Bool(value) => Json::Bool(*value),
260            JsonValue::Number(number) => Json::Number(number.clone()),
261            JsonValue::Text(text) => Json::String(text.clone()),
262            JsonValue::List(items) => Json::Array(items.iter().map(Data::encode).collect()),
263            JsonValue::Object(members) => Json::Object(
264                members
265                    .iter()
266                    .map(|(key, value)| (key.clone(), value.encode()))
267                    .collect(),
268            ),
269        }
270    }
271
272    fn decode(json: &Json) -> Result<Self, DecodeError> {
273        Ok(match json {
274            Json::Null => JsonValue::Null,
275            Json::Bool(value) => JsonValue::Bool(*value),
276            Json::Number(number) => JsonValue::Number(number.clone()),
277            Json::String(text) => JsonValue::Text(text.clone()),
278            Json::Array(_) => JsonValue::List(elements(json)?),
279            Json::Object(members) => {
280                let mut object = BTreeMap::new();
281                for (key, value) in members {
282                    let step = format!("[{}]", Json::String(key.clone()).canonical());
283                    if object
284                        .insert(key.clone(), within(value, &step, JsonValue::decode)?)
285                        .is_some()
286                    {
287                        return Err(inside(refused("repeats a key already given"), &step));
288                    }
289                }
290                JsonValue::Object(object)
291            }
292        })
293    }
294}
295
296/// A Tool's type parameter: the JSON itself, untouched.
297impl Data for Json {
298    fn encode(&self) -> Json {
299        self.clone()
300    }
301
302    fn decode(json: &Json) -> Result<Self, DecodeError> {
303        Ok(json.clone())
304    }
305}
306
307/// A part a recursive type holds directly.
308impl<T: Data> Data for Box<T> {
309    fn encode(&self) -> Json {
310        (**self).encode()
311    }
312
313    fn decode(json: &Json) -> Result<Self, DecodeError> {
314        T::decode(json).map(Box::new)
315    }
316}
317
318/// The elements of the array `json`, each decoded inside its position.
319fn elements<T: Data, C: FromIterator<T>>(json: &Json) -> Result<C, DecodeError> {
320    match json {
321        Json::Array(items) => items
322            .iter()
323            .enumerate()
324            .map(|(index, item)| within(item, &format!("[{index}]"), T::decode))
325            .collect(),
326        other => Err(expected("an array", other)),
327    }
328}
329
330/// `List<T>`.
331impl<T: Data> Data for Vec<T> {
332    fn encode(&self) -> Json {
333        Json::Array(self.iter().map(Data::encode).collect())
334    }
335
336    fn decode(json: &Json) -> Result<Self, DecodeError> {
337        elements(json)
338    }
339}
340
341/// `Set<T>`, in ascending order; repeated elements collapse.
342impl<T: Data + Ord> Data for BTreeSet<T> {
343    fn encode(&self) -> Json {
344        Json::Array(self.iter().map(Data::encode).collect())
345    }
346
347    fn decode(json: &Json) -> Result<Self, DecodeError> {
348        elements(json)
349    }
350}
351
352/// `Dict<K, V>`: an object when the keys are `Text`, and otherwise an array
353/// of `[key, value]` pairs in ascending key order. Two equal keys are
354/// refused.
355impl<K: Data + Ord, V: Data> Data for BTreeMap<K, V> {
356    fn encode(&self) -> Json {
357        if K::TEXT {
358            Json::Object(
359                self.iter()
360                    .map(|(key, value)| match key.encode() {
361                        Json::String(key) => (key, value.encode()),
362                        _ => unreachable!("a key of Text encodes as a string"),
363                    })
364                    .collect(),
365            )
366        } else {
367            Json::Array(
368                self.iter()
369                    .map(|(key, value)| Json::Array(vec![key.encode(), value.encode()]))
370                    .collect(),
371            )
372        }
373    }
374
375    fn decode(json: &Json) -> Result<Self, DecodeError> {
376        let mut dict = BTreeMap::new();
377        match json {
378            Json::Object(members) if K::TEXT => {
379                for (key, value) in members {
380                    let step = format!("[{}]", Json::String(key.clone()).canonical());
381                    let key = K::decode(&Json::String(key.clone()))?;
382                    dict.insert(key, within(value, &step, V::decode)?);
383                }
384            }
385            Json::Array(pairs) if !K::TEXT => {
386                for (index, pair) in pairs.iter().enumerate() {
387                    let (key, value) = within(pair, &format!("[{index}]"), |pair| {
388                        let parts = positional(pair, 2)?;
389                        Ok((part(parts, 0)?, part(parts, 1)?))
390                    })?;
391                    if dict.insert(key, value).is_some() {
392                        return Err(inside(
393                            refused("repeats a key already given"),
394                            &format!("[{index}]"),
395                        ));
396                    }
397                }
398            }
399            other => {
400                return Err(expected(
401                    if K::TEXT { "an object" } else { "an array" },
402                    other,
403                ));
404            }
405        }
406        Ok(dict)
407    }
408}
409
410/// `Option<T>` anywhere but a record field: `"None"` or `{"Some": v}`.
411impl<T: Data> Data for Option<T> {
412    fn encode(&self) -> Json {
413        match self {
414            None => Json::String("None".to_owned()),
415            Some(value) => variant("Some", value.encode()),
416        }
417    }
418
419    fn decode(json: &Json) -> Result<Self, DecodeError> {
420        match constructor(json)? {
421            ("None", None) => Ok(None),
422            ("Some", Some(payload)) => within(payload, "Some", T::decode).map(Some),
423            (name, payload) => Err(mismatch("Option", name, payload)),
424        }
425    }
426}
427
428/// Ordinary nested `Result<T, E>` data; Tool completion is a separate boundary.
429impl<T: Data, E: Data> Data for std::result::Result<T, E> {
430    fn encode(&self) -> Json {
431        match self {
432            Ok(value) => variant("Ok", value.encode()),
433            Err(value) => variant("Err", value.encode()),
434        }
435    }
436    fn decode(json: &Json) -> Result<Self, DecodeError> {
437        match constructor(json)? {
438            ("Ok", Some(payload)) => within(payload, "Ok", T::decode).map(Ok),
439            ("Err", Some(payload)) => within(payload, "Err", E::decode).map(Err),
440            (name, payload) => Err(mismatch("Result", name, payload)),
441        }
442    }
443}
444
445macro_rules! tuple {
446    ($count:literal: $($part:ident $index:tt),+) => {
447        /// A tuple: an array of its elements.
448        impl<$($part: Data),+> Data for ($($part,)+) {
449            fn encode(&self) -> Json {
450                Json::Array(vec![$(self.$index.encode()),+])
451            }
452
453            fn decode(json: &Json) -> Result<Self, DecodeError> {
454                let parts = positional(json, $count)?;
455                Ok(($(part::<$part>(parts, $index)?,)+))
456            }
457        }
458    };
459}
460
461tuple!(2: A 0, B 1);
462tuple!(3: A 0, B 1, C 2);
463tuple!(4: A 0, B 1, C 2, D 3);
464tuple!(5: A 0, B 1, C 2, D 3, E 4);
465tuple!(6: A 0, B 1, C 2, D 3, E 4, F 5);
466tuple!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6);
467tuple!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
468
469/// The named fields of a record or a constructor's named payload, being
470/// written.
471#[derive(Default, Debug)]
472pub struct Fields(Vec<(String, Json)>);
473
474impl Fields {
475    /// No fields yet.
476    pub fn new() -> Self {
477        Fields::default()
478    }
479
480    /// With the field `name` holding `value`.
481    #[must_use]
482    pub fn field<T: Data>(mut self, name: &str, value: &T) -> Self {
483        self.0.push((name.to_owned(), value.encode()));
484        self
485    }
486
487    /// With the `Option` field `name`: left out for `None`, and holding
488    /// the value itself for `Some`.
489    #[must_use]
490    pub fn optional<T: Data>(mut self, name: &str, value: Option<&T>) -> Self {
491        if let Some(value) = value {
492            self.0.push((name.to_owned(), value.encode()));
493        }
494        self
495    }
496
497    /// The object.
498    pub fn build(self) -> Json {
499        Json::Object(self.0)
500    }
501}
502
503/// The named fields of a record or a named payload, being read.
504#[derive(Debug)]
505pub struct Object<'j>(&'j [(String, Json)]);
506
507/// The fields of the object `json`.
508pub fn object(json: &Json) -> Result<Object<'_>, DecodeError> {
509    match json {
510        Json::Object(members) => Ok(Object(members)),
511        other => Err(expected("an object", other)),
512    }
513}
514
515impl Object<'_> {
516    fn get(&self, name: &str) -> Option<&Json> {
517        self.0
518            .iter()
519            .find(|(key, _)| key == name)
520            .map(|(_, value)| value)
521    }
522
523    /// The field `name`, which must be there.
524    pub fn field<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
525        match self.get(name) {
526            Some(value) => within(value, name, T::decode),
527            None => Err(inside(refused("is missing"), name)),
528        }
529    }
530
531    /// The `Option` field `name`: `None` when it is missing or `null`.
532    pub fn optional<T: Data>(&self, name: &str) -> Result<Option<T>, DecodeError> {
533        match self.get(name) {
534            None | Some(Json::Null) => Ok(None),
535            Some(value) => within(value, name, T::decode).map(Some),
536        }
537    }
538}
539
540/// An enum value's constructor name, and its payload when it has one.
541pub fn constructor(json: &Json) -> Result<(&str, Option<&Json>), DecodeError> {
542    match json {
543        Json::String(name) => Ok((name, None)),
544        Json::Object(members) if members.len() == 1 => {
545            Ok((members[0].0.as_str(), Some(&members[0].1)))
546        }
547        other => Err(expected(
548            "a constructor's name or an object of one member",
549            other,
550        )),
551    }
552}
553
554/// The enum value of the constructor `name` with `payload`.
555pub fn variant(name: &str, payload: Json) -> Json {
556    Json::Object(vec![(name.to_owned(), payload)])
557}
558
559/// Why `name`, with or without a payload, is no constructor of the enum
560/// `enum_name`.
561pub fn mismatch(enum_name: &str, name: &str, payload: Option<&Json>) -> DecodeError {
562    let with = if payload.is_some() {
563        "with a payload"
564    } else {
565        "without a payload"
566    };
567    refused(format!(
568        "names no constructor of `{enum_name}`: `{name}` {with}"
569    ))
570}
571
572/// The `count` elements of the array `json`: a tuple, or a constructor's
573/// positional payload of several values.
574pub fn positional(json: &Json, count: usize) -> Result<&[Json], DecodeError> {
575    match json {
576        Json::Array(parts) if parts.len() == count => Ok(parts),
577        Json::Array(parts) => Err(refused(format!(
578            "has {} elements, not {count}",
579            parts.len()
580        ))),
581        other => Err(expected("an array", other)),
582    }
583}
584
585/// The element at `index` of `parts`, decoded inside its position.
586pub fn part<T: Data>(parts: &[Json], index: usize) -> Result<T, DecodeError> {
587    within(&parts[index], &format!("[{index}]"), T::decode)
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    #[test]
595    fn a_path_is_written_as_the_runtime_writes_one() {
596        let error = inside(inside(refused("is wrong"), "[2]"), "steps");
597        assert_eq!(error.path, "steps[2]");
598        let error = inside(inside(refused("is wrong"), "owner"), "[0]");
599        assert_eq!(error.path, "[0].owner");
600        assert_eq!(error.problem, "is wrong");
601    }
602}
603
604/// An owned type-directed codec for one validated concrete call root.
605#[derive(Clone, Debug)]
606pub struct ContextCodec {
607    graph: std::sync::Arc<flow_abi::ValidatedTypes>,
608    ty: Type,
609    mode: Mode,
610}
611
612impl ContextCodec {
613    pub(crate) fn is_text(&self) -> bool {
614        matches!(self.ty, Type::Text)
615    }
616    pub(crate) fn new(
617        graph: std::sync::Arc<flow_abi::ValidatedTypes>,
618        ty: Type,
619        mode: Mode,
620    ) -> Result<Self, DecodeError> {
621        flow_abi::crossable(graph.catalog(), &ty)?;
622        flow_abi::decodable(graph.catalog(), &ty, mode)?;
623        Ok(Self { graph, ty, mode })
624    }
625
626    /// Decodes and normalizes a value using the caller's concrete type.
627    pub fn decode(&self, json: &Json) -> Result<Json, DecodeError> {
628        let value = flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS)?;
629        self.encode_value(&value)
630    }
631
632    fn encode_value(&self, value: &flow_value::Value) -> Result<Json, DecodeError> {
633        flow_abi::encode(self.graph.catalog(), &self.ty, value)
634            .map_err(|error| refused(error.to_string()))
635    }
636
637    /// Validates an author's JSON at this root and writes its canonical value.
638    pub fn encode(&self, json: &Json) -> Result<Json, DecodeError> {
639        self.decode(json)
640    }
641
642    /// Flow's comparison, directed by this root rather than JSON key order.
643    pub fn compare(&self, left: &Json, right: &Json) -> Result<std::cmp::Ordering, DecodeError> {
644        let decode =
645            |json| flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS);
646        flow_value::compare(&decode(left)?, &decode(right)?)
647            .map_err(|error| refused(error.to_string()))
648    }
649
650    fn child(&self, ty: Type) -> Result<Self, DecodeError> {
651        Self::new(self.graph.clone(), ty, self.mode)
652    }
653
654    /// The element of a list, set or option.
655    pub fn element(&self) -> Result<Self, DecodeError> {
656        match &self.ty {
657            Type::List(ty) | Type::Set(ty) | Type::Option(ty) => self.child((**ty).clone()),
658            _ => Err(refused("type has no element codec")),
659        }
660    }
661    /// The key of a dictionary.
662    pub fn key(&self) -> Result<Self, DecodeError> {
663        match &self.ty {
664            Type::Dict(key, _) => self.child((**key).clone()),
665            _ => Err(refused("type is not a dictionary")),
666        }
667    }
668    /// The value of a dictionary.
669    pub fn value(&self) -> Result<Self, DecodeError> {
670        match &self.ty {
671            Type::Dict(_, value) => self.child((**value).clone()),
672            _ => Err(refused("type is not a dictionary")),
673        }
674    }
675    /// A tuple's part at its declaration position.
676    pub fn positional(&self, index: usize) -> Result<Self, DecodeError> {
677        match &self.ty {
678            Type::Tuple(parts) => parts
679                .get(index)
680                .cloned()
681                .ok_or_else(|| refused("tuple index is out of range"))
682                .and_then(|ty| self.child(ty)),
683            _ => Err(refused("type is not a tuple")),
684        }
685    }
686    /// A record field after substituting the caller's type arguments.
687    pub fn field(&self, name: &str) -> Result<Self, DecodeError> {
688        if let Type::Named(id, args) = &self.ty
689            && let flow_abi::Body::Record(shape, fields) = &self.graph.catalog().decl(*id).body
690            && let Some(index) = shape.fields().position(|field| field == name)
691        {
692            return self.child(fields[index].subst(args));
693        }
694        Err(refused(format!("type has no field {name}")))
695    }
696    /// Reads a record field, resolving Option presence after substitution.
697    pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
698        self.field(name)?.read_field(parent, name)
699    }
700    /// Encodes a record field, omitting None after substitution.
701    pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
702        self.field(name)?.write_field(value)
703    }
704    fn read_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
705        let value = parent.get(name);
706        if let Type::Option(_) = self.ty {
707            return match value {
708                None | Some(Json::Null) => Ok(Json::String("None".into())),
709                Some(value) => self.decode(&variant("Some", value.clone())),
710            };
711        }
712        self.decode(value.ok_or_else(|| inside(refused("is missing"), name))?)
713    }
714    fn write_field(&self, value: &Json) -> Result<Option<Json>, DecodeError> {
715        let normalized = self.encode(value)?;
716        if let Type::Option(_) = self.ty {
717            return match constructor(&normalized)? {
718                ("None", None) => Ok(None),
719                ("Some", Some(value)) => Ok(Some(value.clone())),
720                _ => Err(refused("invalid normalized Option")),
721            };
722        }
723        Ok(Some(normalized))
724    }
725    /// Selects one enum constructor before looking up its payload members.
726    pub fn variant(&self, name: &str) -> Result<PayloadView, DecodeError> {
727        if let Type::Named(id, args) = &self.ty
728            && let flow_abi::Body::Enum(shape, parts) = &self.graph.catalog().decl(*id).body
729        {
730            for (index, fields) in parts.iter().enumerate() {
731                let ctor = shape.constructor(index).expect("validated enum shape");
732                if ctor.name() == name {
733                    return Ok(PayloadView {
734                        parent: self.clone(),
735                        kind: ctor.payload().clone(),
736                        parts: fields.iter().map(|ty| ty.subst(args)).collect(),
737                    });
738                }
739            }
740        }
741        Err(refused(format!("type has no constructor {name}")))
742    }
743}
744
745/// A payload view belonging to one explicitly selected constructor.
746#[derive(Clone, Debug)]
747pub struct PayloadView {
748    parent: ContextCodec,
749    kind: Payload,
750    parts: Vec<Type>,
751}
752impl PayloadView {
753    /// A positional payload member.
754    pub fn positional(&self, index: usize) -> Result<ContextCodec, DecodeError> {
755        if !matches!(self.kind, Payload::Positional(_)) {
756            return Err(refused("payload is not positional"));
757        }
758        self.parts
759            .get(index)
760            .cloned()
761            .ok_or_else(|| refused("payload index is out of range"))
762            .and_then(|ty| self.parent.child(ty))
763    }
764    /// A named payload field.
765    pub fn field(&self, name: &str) -> Result<ContextCodec, DecodeError> {
766        if let Payload::Named(names) = &self.kind
767            && let Some(index) = names.iter().position(|field| field.as_ref() == name)
768        {
769            return self.parent.child(self.parts[index].clone());
770        }
771        Err(refused(format!("payload has no field {name}")))
772    }
773    /// Reads a named member with substituted Option presence.
774    pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
775        self.field(name)?.read_field(parent, name)
776    }
777    /// Writes a named member with substituted Option presence.
778    pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
779        self.field(name)?.write_field(value)
780    }
781}
782
783/// A set whose elements use one owned concrete Flow codec.
784#[derive(Clone, Debug)]
785pub struct ContextSet {
786    codec: ContextCodec,
787    values: Vec<Json>,
788}
789impl ContextSet {
790    /// Normalizes, orders and collapses equal elements without a JSON comparator.
791    pub fn new(codec: ContextCodec, values: Vec<Json>) -> Result<Self, DecodeError> {
792        // Decode once; the runtime collection sorts typed values in O(n log n)
793        // comparisons instead of decoding the sorted prefix at every insertion.
794        let decoded = values
795            .into_iter()
796            .map(|json| {
797                flow_abi::decode(codec.graph.catalog(), &codec.ty, &json, codec.mode, &LIMITS)
798            })
799            .collect::<Result<Vec<_>, _>>()?;
800        let ordered =
801            flow_value::Set::from_items(decoded).map_err(|error| refused(error.to_string()))?;
802        let values = ordered
803            .iter()
804            .map(|value| codec.encode_value(value))
805            .collect::<Result<_, _>>()?;
806        Ok(Self { codec, values })
807    }
808    /// The owned element codec.
809    pub fn codec(&self) -> &ContextCodec {
810        &self.codec
811    }
812    /// Elements in Flow order.
813    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Json> {
814        self.values.iter()
815    }
816    /// Canonical array, revalidated at the output root by generated code.
817    pub fn canonical_json(&self) -> Json {
818        Json::Array(self.values.clone())
819    }
820}
821
822/// A dictionary whose keys and values use owned concrete Flow codecs.
823#[derive(Clone, Debug)]
824pub struct ContextDict {
825    key: ContextCodec,
826    value: ContextCodec,
827    values: Vec<(Json, Json)>,
828    text: bool,
829}
830impl ContextDict {
831    /// Normalizes and orders entries, refusing duplicate typed keys.
832    pub fn new(
833        key: ContextCodec,
834        value: ContextCodec,
835        entries: Vec<(Json, Json)>,
836    ) -> Result<Self, DecodeError> {
837        let text = key.ty == Type::Text;
838        let count = entries.len();
839        let decoded = entries
840            .into_iter()
841            .map(|(k, v)| {
842                Ok((
843                    flow_abi::decode(key.graph.catalog(), &key.ty, &k, key.mode, &LIMITS)?,
844                    flow_abi::decode(value.graph.catalog(), &value.ty, &v, value.mode, &LIMITS)?,
845                ))
846            })
847            .collect::<Result<Vec<_>, DecodeError>>()?;
848        // Runtime dictionaries sort in O(n log n) comparisons and collapse equal
849        // keys. This constructor refuses duplicates rather than keeping a value.
850        let ordered =
851            flow_value::Dict::from_entries(decoded).map_err(|error| refused(error.to_string()))?;
852        if ordered.len() != count {
853            return Err(refused("dictionary has a duplicate key"));
854        }
855        let values = ordered
856            .iter()
857            .map(|(k, v)| Ok((key.encode_value(k)?, value.encode_value(v)?)))
858            .collect::<Result<_, DecodeError>>()?;
859        Ok(Self {
860            key,
861            value,
862            values,
863            text,
864        })
865    }
866    /// The owned key codec.
867    pub fn key_codec(&self) -> &ContextCodec {
868        &self.key
869    }
870    /// The owned value codec.
871    pub fn value_codec(&self) -> &ContextCodec {
872        &self.value
873    }
874    /// Entries in Flow key order.
875    pub fn iter(&self) -> impl ExactSizeIterator<Item = &(Json, Json)> {
876        self.values.iter()
877    }
878    /// Text keys form an object; other keys form pairs.
879    pub fn canonical_json(&self) -> Json {
880        if self.text {
881            Json::Object(
882                self.values
883                    .iter()
884                    .map(|(key, value)| match key {
885                        Json::String(key) => (key.clone(), value.clone()),
886                        _ => unreachable!("validated Text key"),
887                    })
888                    .collect(),
889            )
890        } else {
891            Json::Array(
892                self.values
893                    .iter()
894                    .map(|(key, value)| Json::Array(vec![key.clone(), value.clone()]))
895                    .collect(),
896            )
897        }
898    }
899}
900
901/// Reads a dynamic set using the caller's normalized element order.
902pub fn read_context_set(codec: &ContextCodec, json: &Json) -> Result<ContextSet, DecodeError> {
903    if !matches!(codec.ty, Type::Set(_)) {
904        return Err(refused("type is not a set"));
905    }
906    let Json::Array(values) = codec.decode(json)? else {
907        return Err(refused("set must be an array"));
908    };
909    Ok(ContextSet {
910        codec: codec.element()?,
911        values,
912    })
913}
914/// Reads a dynamic dictionary from its concrete object or pair form.
915pub fn read_context_dict(codec: &ContextCodec, json: &Json) -> Result<ContextDict, DecodeError> {
916    let values = match codec.decode(json)? {
917        Json::Object(fields) => fields
918            .into_iter()
919            .map(|(key, value)| (Json::String(key), value))
920            .collect(),
921        Json::Array(pairs) => pairs
922            .into_iter()
923            .map(|pair| match pair {
924                Json::Array(mut pair) if pair.len() == 2 => {
925                    let value = pair.pop().expect("pair value");
926                    let key = pair.pop().expect("pair key");
927                    Ok((key, value))
928                }
929                _ => Err(refused("dictionary entry must be a pair")),
930            })
931            .collect::<Result<_, _>>()?,
932        _ => return Err(refused("dictionary must be an object or pairs")),
933    };
934    let key = codec.key()?;
935    let text = key.ty == Type::Text;
936    Ok(ContextDict {
937        key,
938        value: codec.value()?,
939        values,
940        text,
941    })
942}
943/// Composes an owned contextual list codec with native element factories.
944pub fn read_context_list<T>(
945    codec: &ContextCodec,
946    json: &Json,
947    read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
948) -> Result<Vec<T>, DecodeError> {
949    let Json::Array(values) = codec.decode(json)? else {
950        return Err(refused("list must be an array"));
951    };
952    let child = codec.element()?;
953    values
954        .iter()
955        .enumerate()
956        .map(|(at, value)| read(&child, value).map_err(|error| inside(error, &format!("[{at}]"))))
957        .collect()
958}
959/// Composes a contextual list encoder with native element factories.
960pub fn write_context_list<T>(
961    codec: &ContextCodec,
962    values: &[T],
963    write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
964) -> Result<Json, DecodeError> {
965    let child = codec.element()?;
966    codec.encode(&Json::Array(
967        values
968            .iter()
969            .map(|value| write(&child, value))
970            .collect::<Result<_, _>>()?,
971    ))
972}
973/// Reads standalone Option's canonical enum representation.
974pub fn read_context_option<T>(
975    codec: &ContextCodec,
976    json: &Json,
977    read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
978) -> Result<Option<T>, DecodeError> {
979    let normalized = codec.decode(json)?;
980    match constructor(&normalized)? {
981        ("None", None) => Ok(None),
982        ("Some", Some(value)) => read(&codec.element()?, value).map(Some),
983        _ => Err(refused("invalid Option")),
984    }
985}
986/// Writes standalone Option's canonical enum representation.
987pub fn write_context_option<T>(
988    codec: &ContextCodec,
989    value: &Option<T>,
990    write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
991) -> Result<Json, DecodeError> {
992    let json = match value {
993        None => Json::String("None".into()),
994        Some(value) => variant("Some", write(&codec.element()?, value)?),
995    };
996    codec.encode(&json)
997}