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
//! A one-field tuple struct that derives `Flow` is a newtype, and
//! `std::time::SystemTime` and `std::time::Duration` are `time.Instant` and
//! `duration.Duration` (`abi.md`, *Extracting a contract*).
//!
//! A newtype is declared on one line, `pub type UserId(pub Text)`, a
//! `PhantomData` field is skipped as a phantom parameter, and its encoding
//! is its field's. A native time converts exactly or not at
//! all.
#![expect(
    missing_docs,
    reason = "the test binary's tool fixtures are public by the derive's rule"
)]
mod common;

use std::marker::PhantomData;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use flow_abi_testing::crossing::{bytes, crossed, read};
use flow_toolkit::{Flow, Int, Shaped, tool};

/// Who a user is.
#[derive(Flow, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct UserId(pub String);

#[derive(Flow, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Labeled<T: Shaped>(pub Vec<T>);

#[derive(Flow, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Id<T: Shaped>(pub String, pub PhantomData<T>);

#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Point {
    pub z: Int,
    pub a: Int,
}

#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Located(pub Point);

#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Maybe(pub Option<String>);

#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Holder {
    pub maybe: Maybe,
    pub user: UserId,
}

#[tool]
pub fn rename(user: UserId, names: Labeled<String>, point: Id<Point>) -> Located {
    let _ = (user, names, point);
    Located(Point {
        z: Int::from(1),
        a: Int::from(2),
    })
}

#[tool]
pub fn page(
    #[flow(default = UserId("root"))] owner: UserId,
    #[flow(default = Some(UserId("guest")))] viewer: Option<UserId>,
) -> Vec<UserId> {
    vec![owner, viewer.unwrap_or(UserId(String::new()))]
}

#[tool]
pub fn later(at: SystemTime, wait: Duration) -> SystemTime {
    at + wait
}

/// Every contract module `functions` extract to, placed in this crate's
/// root module, one after another.
fn extract(functions: Vec<flow_toolkit::__bridge::Function>) -> String {
    let placed = functions
        .into_iter()
        .map(|function| flow_toolkit::__bridge::at("", "tests/newtypes.rs", 1, function))
        .collect::<Vec<_>>();
    common::extract("newtypes", None, &placed)
        .expect("the contract is written")
        .into_values()
        .collect::<Vec<_>>()
        .join("\n")
}

#[test]
fn a_one_field_tuple_struct_is_a_newtype_declared_on_one_line() {
    let source = extract(vec![__flow_tool_rename()]);
    for line in [
        "/// Who a user is.\n// from toolkits/rust/tests/newtypes.rs: UserId\npub type UserId(pub Text)\n",
        "pub type Labeled<T>(pub List<T>)\n",
        "pub type Id<T>(pub Text)\n",
        "pub type Located(pub Point)\n",
        "pub flow rename(user: UserId, names: Labeled<Text>, point: Id<Point>) -> Located\n",
    ] {
        assert!(source.contains(line), "{line} in\n{source}");
    }
}

#[test]
fn a_newtype_default_is_its_constructor_applied_to_a_literal() {
    let source = extract(vec![__flow_tool_page()]);
    assert!(
        source.contains(
            r#"pub flow page(owner: UserId = UserId("root"), viewer: Option<UserId> = Some(UserId("guest"))) -> List<UserId>"#
        ),
        "{source}"
    );
}

#[test]
fn std_time_types_are_instant_and_duration() {
    let source = extract(vec![__flow_tool_later()]);
    assert!(
        source.contains("use \"std@v1/duration\"\nuse \"std@v1/time\"\n"),
        "{source}"
    );
    assert!(
        source.contains(
            "pub flow later(at: time.Instant, wait: duration.Duration) -> time.Instant\n"
        ),
        "{source}"
    );
}

#[test]
fn the_generated_contract_is_one_the_checker_accepts() {
    let placed = [
        __flow_tool_rename(),
        __flow_tool_page(),
        __flow_tool_later(),
    ]
    .map(|function| flow_toolkit::__bridge::at("", "tests/newtypes.rs", 1, function));
    let contracts = common::extract("newtypes", None, &placed).expect("the contract is written");
    let listed = common::listed(
        &contracts,
        &common::referring(&["lib.rename", "lib.page", "lib.later"]),
    );
    assert_eq!(common::tool_names(&listed), ["later", "page", "rename"]);
    assert!(
        listed.iter().any(|(_, spec)| spec
            .catalog()
            .decls()
            .any(|(_, decl)| matches!(decl.body, flow_types::Body::Newtype(_)))),
        "the listing describes the newtypes"
    );
}

#[test]
fn a_newtype_is_written_as_its_field() {
    let user = UserId("u-17".to_owned());
    assert_eq!(crossed(&user), (user.clone(), bytes(&"u-17".to_owned())));
    let id: Id<Point> = Id("p-1".to_owned(), PhantomData);
    assert_eq!(crossed(&id), (id.clone(), bytes(&"p-1".to_owned())));
    let labeled = Labeled(vec![Int::from(1), Int::from(2)]);
    assert_eq!(crossed(&labeled).0, labeled);
}

#[test]
fn a_dictionary_keyed_by_a_newtype_crosses_as_its_entries() {
    let by_user = std::collections::BTreeMap::from([
        (UserId("b".to_owned()), Int::from(2)),
        (UserId("a".to_owned()), Int::from(1)),
    ]);
    assert_eq!(crossed(&by_user).0, by_user);
    let by_list = std::collections::BTreeMap::from([(Labeled(vec![Int::from(1)]), Int::from(3))]);
    assert_eq!(crossed(&by_list).0, by_list);
}

#[test]
fn a_record_field_whose_type_erases_to_an_option_crosses_either_way() {
    for maybe in [None, Some("m".to_owned())] {
        let holder = Holder {
            maybe: Maybe(maybe),
            user: UserId("u".to_owned()),
        };
        assert_eq!(crossed(&holder).0, holder);
    }
}

#[test]
fn a_generic_position_bound_to_a_newtype_reads_and_writes_as_its_base() {
    use flow_types::{Body, DeclId, Type};
    let user = common::bound_call(
        Type::Named(DeclId(0), vec![]),
        vec![common::local("UserId", &[], Body::Newtype(Type::Text))],
    );
    let read = user.decode::<UserId>(r#""u-17""#).unwrap();
    assert_eq!(read, UserId("u-17".to_owned()));
    assert_eq!(user.to_json(&read).unwrap(), r#""u-17""#);
    let located = common::bound_call(
        Type::Named(DeclId(0), vec![]),
        vec![
            common::local(
                "Located",
                &[],
                Body::Newtype(Type::Named(DeclId(1), vec![])),
            ),
            common::local(
                "Point",
                &[],
                Body::Record(
                    flow_types::RecordShape::new("Point", ["z", "a"]),
                    vec![Type::Int, Type::Int],
                ),
            ),
        ],
    );
    let point = located.decode::<Located>(r#"{"a":2,"z":1}"#).unwrap();
    assert_eq!(point.0.z, Int::from(1));
}

/// The runtime's `Instant` `seconds` after the epoch.
fn instant(seconds: &str) -> flow_toolkit::Instant {
    flow_toolkit::Instant::from_unix_seconds(
        flow_toolkit::Decimal::parse(seconds).expect("decimal seconds"),
    )
}

/// The runtime's `Duration` of `seconds`.
fn length(seconds: &str) -> flow_toolkit::Duration {
    flow_toolkit::Duration::from_seconds(
        flow_toolkit::Decimal::parse(seconds).expect("decimal seconds"),
    )
}

#[test]
fn a_system_time_is_its_exact_instant_before_or_after_the_epoch() {
    let noon = UNIX_EPOCH + Duration::from_millis(1_774_085_400_250);
    assert_eq!(
        read::<flow_toolkit::Instant>(&bytes(&noon)),
        instant("1774085400.25")
    );
    assert_eq!(read::<SystemTime>(&bytes(&instant("1774085400.25"))), noon);
    let before = UNIX_EPOCH - Duration::new(1, 500_000_000);
    assert_eq!(crossed(&before), (before, bytes(&instant("-1.5"))));
    let nano = UNIX_EPOCH + Duration::from_nanos(1);
    assert_eq!(bytes(&nano), bytes(&instant("0.000000001")));
}

#[test]
fn a_std_duration_is_its_exact_length() {
    let wait = Duration::new(90, 500_000_000);
    assert_eq!(crossed(&wait), (wait, bytes(&length("90.5"))));
    assert_eq!(
        bytes(&Duration::from_nanos(1)),
        bytes(&length("0.000000001"))
    );
}

#[test]
fn a_time_std_cannot_hold_exactly_is_no_value_of_it() {
    let catalog = flow_abi_testing::catalog::std_catalog();
    let duration = |seconds: &str| {
        flow_abi::of_shaped_value::<Duration>(
            &flow_value::Value::Duration(length(seconds)),
            &catalog,
            &flow_types::Type::Duration,
        )
    };
    let time = |seconds: &str| {
        flow_abi::of_shaped_value::<SystemTime>(
            &flow_value::Value::Instant(instant(seconds)),
            &catalog,
            &flow_types::Type::Instant,
        )
    };
    // Negative, finer than a nanosecond, and past every `i128` of
    // nanoseconds: by its exponent alone, and by its coefficient at an
    // exponent that would otherwise fit.
    for seconds in [
        "-5".to_owned(),
        "0.0000000001".to_owned(),
        format!("1{}", "0".repeat(40)),
        format!("2{}", "0".repeat(29)),
    ] {
        assert!(duration(&seconds).is_err(), "{seconds}");
    }
    assert!(
        time("1774085400.0000000001").is_err(),
        "finer than a nanosecond"
    );
    // Past what the clock itself can hold, though short enough for a
    // `std::time::Duration` from the epoch.
    assert!(
        time("12622780800000000000").is_err(),
        "past the clock's range"
    );
}