Skip to main content

flow_toolkit/
data.rs

1//! The values the toolkit names itself: [`Bytes`] and [`JsonValue`], each
2//! mapped to its Flow type by [`Shaped`] (`abi.md`, *The value encoding*),
3//! and JSON text from outside a run, read within the toolkit's limits.
4
5use std::collections::BTreeMap;
6
7use flow_abi::wire::{Shaped, Type, ValueReader, ValueWriter, WireForm};
8use flow_abi::{Catalog, EncodeError, Json, Limits, Step};
9use flow_types::{JsonValueCtor, StdEnum};
10use flow_value::Decimal;
11
12pub use flow_abi::DecodeError;
13
14/// Parses JSON text from outside a run, such as an API's response, within
15/// the toolkit's bounded input limits.
16///
17/// # Errors
18///
19/// Refuses text that is not JSON, and JSON nested or sized past the toolkit's limits.
20pub fn parse_json(text: &str) -> Result<Json, DecodeError> {
21    flow_abi::parse(text, &LIMITS)
22}
23
24/// How large a value the toolkit reads: well past what any host sends.
25pub(crate) const LIMITS: Limits = Limits {
26    depth: 1_024,
27    int_bits: 16_777_216,
28    text_bytes: 1_073_741_824,
29};
30
31/// A failure at the whole value.
32pub(crate) fn refused(problem: impl Into<String>) -> DecodeError {
33    DecodeError {
34        path: flow_abi::Place::default(),
35        problem: problem.into(),
36        kind: flow_abi::DecodeErrorKind::Mismatch,
37    }
38}
39
40/// `error`, found inside the parameter `name`.
41pub(crate) fn inside(mut error: DecodeError, name: &str) -> DecodeError {
42    error.path = error.path.within([Step::Field(name.to_owned())]);
43    error
44}
45
46/// `Bytes`: raw bytes.
47#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
48pub struct Bytes(pub Vec<u8>);
49
50impl From<Vec<u8>> for Bytes {
51    fn from(bytes: Vec<u8>) -> Self {
52        Bytes(bytes)
53    }
54}
55
56impl From<&[u8]> for Bytes {
57    fn from(bytes: &[u8]) -> Self {
58        Bytes(bytes.to_vec())
59    }
60}
61
62impl Shaped for Bytes {
63    const FORM: WireForm = WireForm::Bytes;
64
65    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
66        out.bytes(ty, &self.0)
67    }
68
69    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
70        input.bytes(ty).map(|bytes| Bytes(bytes.to_vec()))
71    }
72}
73
74/// `json.Value`, std's enum for raw JSON: its constructors `Null`, `Bool`,
75/// `Number`, `Text`, `List` and `Object` in std's order, an object a
76/// `Dict<Text, json.Value>`.
77#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
78#[expect(
79    clippy::exhaustive_enums,
80    reason = "mirrors std's `json.Value` and JSON itself, whose six kinds authors match on"
81)]
82pub enum JsonValue {
83    /// `null`.
84    Null,
85    /// `true` or `false`.
86    Bool(bool),
87    /// A number, exactly.
88    Number(Decimal),
89    /// A string.
90    Text(String),
91    /// An array.
92    List(Vec<JsonValue>),
93    /// An object, its members by name.
94    Object(BTreeMap<String, JsonValue>),
95}
96
97impl Shaped for JsonValue {
98    const FORM: WireForm = WireForm::Std {
99        module: "json",
100        name: "Value",
101        args: &[],
102    };
103
104    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
105        let ctors = json_ctors(out.catalog(), ty).ok_or_else(|| out.refuse(ty))?;
106        let at = |ctor| ctors.index(ctor);
107        match self {
108            JsonValue::Null => out.variant(ty, at(JsonValueCtor::Null), &[]),
109            JsonValue::Bool(flag) => out.variant(ty, at(JsonValueCtor::Bool), &[flag]),
110            JsonValue::Number(number) => out.variant(ty, at(JsonValueCtor::Number), &[number]),
111            JsonValue::Text(text) => out.variant(ty, at(JsonValueCtor::Text), &[text]),
112            JsonValue::List(items) => out.variant(ty, at(JsonValueCtor::List), &[items]),
113            JsonValue::Object(members) => out.variant(ty, at(JsonValueCtor::Object), &[members]),
114        }
115    }
116
117    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
118        let ctors = json_ctors(input.catalog(), ty).ok_or_else(|| input.mismatch(ty))?;
119        input.variant(ty, |input, index, parts| match ctors.which(index) {
120            Some(JsonValueCtor::Null) => Ok(JsonValue::Null),
121            Some(JsonValueCtor::Bool) => parts.read(input).map(JsonValue::Bool),
122            Some(JsonValueCtor::Number) => parts.read(input).map(JsonValue::Number),
123            Some(JsonValueCtor::Text) => parts.read(input).map(JsonValue::Text),
124            Some(JsonValueCtor::List) => parts.read(input).map(JsonValue::List),
125            Some(JsonValueCtor::Object) => parts.read(input).map(JsonValue::Object),
126            None => Err(input.mismatch(ty)),
127        })
128    }
129}
130
131/// The constructors of `ty`, std's `json.Value` in `catalog`, found by name.
132fn json_ctors(catalog: &Catalog, ty: &Type) -> Option<StdEnum<JsonValueCtor>> {
133    StdEnum::of(flow_abi::form(catalog, ty).enumeration()?.shape).ok()
134}