flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! The values the toolkit names itself: [`Bytes`] and [`JsonValue`], each
//! mapped to its Flow type by [`Shaped`] (`abi.md`, *The value encoding*),
//! and JSON text from outside a run, read within the toolkit's limits.

use std::collections::BTreeMap;

use flow_abi::wire::{Shaped, Type, ValueReader, ValueWriter, WireForm};
use flow_abi::{Catalog, EncodeError, Json, Limits, Step};
use flow_types::{JsonValueCtor, StdEnum};
use flow_value::Decimal;

pub use flow_abi::DecodeError;

/// Parses JSON text from outside a run, such as an API's response, within
/// the toolkit's bounded input limits.
///
/// # Errors
///
/// Refuses text that is not JSON, and JSON nested or sized past the toolkit's limits.
pub fn parse_json(text: &str) -> Result<Json, DecodeError> {
    flow_abi::parse(text, &LIMITS)
}

/// How large a value the toolkit reads: well past what any host sends.
pub(crate) const LIMITS: Limits = Limits {
    depth: 1_024,
    int_bits: 16_777_216,
    text_bytes: 1_073_741_824,
};

/// A failure at the whole value.
pub(crate) fn refused(problem: impl Into<String>) -> DecodeError {
    DecodeError {
        path: flow_abi::Place::default(),
        problem: problem.into(),
        kind: flow_abi::DecodeErrorKind::Mismatch,
    }
}

/// `error`, found inside the parameter `name`.
pub(crate) fn inside(mut error: DecodeError, name: &str) -> DecodeError {
    error.path = error.path.within([Step::Field(name.to_owned())]);
    error
}

/// `Bytes`: raw bytes.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub struct Bytes(pub Vec<u8>);

impl From<Vec<u8>> for Bytes {
    fn from(bytes: Vec<u8>) -> Self {
        Bytes(bytes)
    }
}

impl From<&[u8]> for Bytes {
    fn from(bytes: &[u8]) -> Self {
        Bytes(bytes.to_vec())
    }
}

impl Shaped for Bytes {
    const FORM: WireForm = WireForm::Bytes;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.bytes(ty, &self.0)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.bytes(ty).map(|bytes| Bytes(bytes.to_vec()))
    }
}

/// `json.Value`, std's enum for raw JSON: its constructors `Null`, `Bool`,
/// `Number`, `Text`, `List` and `Object` in std's order, an object a
/// `Dict<Text, json.Value>`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "mirrors std's `json.Value` and JSON itself, whose six kinds authors match on"
)]
pub enum JsonValue {
    /// `null`.
    Null,
    /// `true` or `false`.
    Bool(bool),
    /// A number, exactly.
    Number(Decimal),
    /// A string.
    Text(String),
    /// An array.
    List(Vec<JsonValue>),
    /// An object, its members by name.
    Object(BTreeMap<String, JsonValue>),
}

impl Shaped for JsonValue {
    const FORM: WireForm = WireForm::Std {
        module: "json",
        name: "Value",
        args: &[],
    };

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let ctors = json_ctors(out.catalog(), ty).ok_or_else(|| out.refuse(ty))?;
        let at = |ctor| ctors.index(ctor);
        match self {
            JsonValue::Null => out.variant(ty, at(JsonValueCtor::Null), &[]),
            JsonValue::Bool(flag) => out.variant(ty, at(JsonValueCtor::Bool), &[flag]),
            JsonValue::Number(number) => out.variant(ty, at(JsonValueCtor::Number), &[number]),
            JsonValue::Text(text) => out.variant(ty, at(JsonValueCtor::Text), &[text]),
            JsonValue::List(items) => out.variant(ty, at(JsonValueCtor::List), &[items]),
            JsonValue::Object(members) => out.variant(ty, at(JsonValueCtor::Object), &[members]),
        }
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        let ctors = json_ctors(input.catalog(), ty).ok_or_else(|| input.mismatch(ty))?;
        input.variant(ty, |input, index, parts| match ctors.which(index) {
            Some(JsonValueCtor::Null) => Ok(JsonValue::Null),
            Some(JsonValueCtor::Bool) => parts.read(input).map(JsonValue::Bool),
            Some(JsonValueCtor::Number) => parts.read(input).map(JsonValue::Number),
            Some(JsonValueCtor::Text) => parts.read(input).map(JsonValue::Text),
            Some(JsonValueCtor::List) => parts.read(input).map(JsonValue::List),
            Some(JsonValueCtor::Object) => parts.read(input).map(JsonValue::Object),
            None => Err(input.mismatch(ty)),
        })
    }
}

/// The constructors of `ty`, std's `json.Value` in `catalog`, found by name.
fn json_ctors(catalog: &Catalog, ty: &Type) -> Option<StdEnum<JsonValueCtor>> {
    StdEnum::of(flow_abi::form(catalog, ty).enumeration()?.shape).ok()
}