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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Automatic adapter contract rejection tests at the private binding seam.
#![expect(
    unreachable_pub,
    clippy::unnecessary_wraps,
    reason = "#[tool] requires public native functions, and these declare Results to show they cross whole"
)]
use crate::test_common as common;
use flow_abi::wire::Rest;
use flow_abi::{ToolDecl, TypeSpec, description};
use flow_start::Spawn as _;
use flow_toolkit::{Flow, Int, JsonValue, Resource, lifespan, tool};
use flow_types::{LibraryLayout, Placement, Segments};
use std::sync::atomic::{AtomicUsize, Ordering};
static EXACT_CALLS: AtomicUsize = AtomicUsize::new(0);
static CONTEXTUAL_CALLS: AtomicUsize = AtomicUsize::new(0);
static STARTS: AtomicUsize = AtomicUsize::new(0);
static CLOSES: AtomicUsize = AtomicUsize::new(0);
#[derive(Flow)]
pub struct Record {
    pub amount: Int,
}
#[tool]
pub fn exact(amount: Int) -> Record {
    EXACT_CALLS.fetch_add(1, Ordering::SeqCst);
    Record { amount }
}
#[tool]
pub fn contextual(value: String) -> String {
    CONTEXTUAL_CALLS.fetch_add(1, Ordering::SeqCst);
    value
}
/// A generated function placed in this module, as a launcher places it.
fn placed(function: crate::__bridge::Function) -> crate::__bridge::Function {
    crate::__bridge::at("test_contract", "src/test_contract.rs", 1, function)
}

/// The listing the host hands the library whose contract `functions`
/// extract to, for `program`, which reaches its Tools.
fn staged_listing(functions: &[crate::__bridge::Function], program: &str) -> Vec<u8> {
    let contracts = common::extract("flow_toolkit", None, functions).unwrap();
    common::listing(&contracts, program)
}

/// A program calling `exact`.
const EXACT: &str = "pub flow main() -> Result<Int, ToolProblem> = {
    let record = test_contract.exact(1)?
    Ok(record.amount)
}
";

/// Each Tool the `--contract` file `listing` lists, in its order.
fn tools(listing: &[u8]) -> Vec<(description::Identity, TypeSpec)> {
    flow_abi::read_listing(listing)
        .unwrap()
        .into_iter()
        .flat_map(|program| program.tools)
        .collect()
}

/// The `--contract` file listing `tools`, in this order, as one program.
fn relisted(tools: &[(description::Identity, TypeSpec)]) -> Vec<u8> {
    let (_, first) = &tools[0];
    let decls: Vec<ToolDecl> = tools
        .iter()
        .map(|(identity, spec)| ToolDecl {
            identity: identity.identity().unwrap(),
            signature: spec.signature().clone(),
        })
        .collect();
    flow_abi::write_listing("", first.catalog(), &decls.iter().collect::<Vec<_>>()).unwrap()
}

#[test]
fn canonical_inventory_mismatches_refuse_before_starting_protocol_or_implementation() {
    let listing = staged_listing(&[placed(__flow_tool_exact())], EXACT);
    let functions = [placed(__flow_tool_exact())];
    let mut other_version = listing.clone();
    other_version[0] = other_version[0].wrapping_add(1);
    let mut left_over = listing.clone();
    left_over.push(0);
    // The data version's two numbers, then no program.
    let empty = [&listing[..2], &[0]].concat();
    for (document, expected) in [
        (Vec::new(), "the contract file is invalid"),
        (other_version, "data version"),
        (left_over, "left over"),
        (empty, "lists no Tool"),
    ] {
        let refused = crate::function::serve(&functions, &document, Some(__flow_lifespan_resource))
            .unwrap_err();
        assert!(refused.contains(expected), "{refused}");
    }
    assert!(
        crate::function::serve(
            &[placed(__flow_tool_contextual())],
            &listing,
            Some(__flow_lifespan_resource)
        )
        .unwrap_err()
        .contains("no Rust function implements")
    );
    let mut listed = tools(&listing);
    listed.push(listed[0].clone());
    assert!(
        crate::function::serve(
            &functions,
            &relisted(&listed),
            Some(__flow_lifespan_resource)
        )
        .unwrap_err()
        .contains("ambiguous Tool")
    );
    let mut elsewhere = tools(&listing);
    elsewhere[0].0.module = "elsewhere".into();
    assert!(
        crate::function::serve(
            &[
                placed(__flow_tool_exact()),
                crate::__bridge::at("other", "src/other.rs", 1, __flow_tool_exact()),
            ],
            &relisted(&elsewhere),
            Some(__flow_lifespan_resource)
        )
        .unwrap_err()
        .contains("names no module, and Rust functions of that name are in several")
    );
    assert_eq!(EXACT_CALLS.load(Ordering::SeqCst), 0);
    assert_eq!(CONTEXTUAL_CALLS.load(Ordering::SeqCst), 0);
    assert_eq!(STARTS.load(Ordering::SeqCst), 0);
    assert_eq!(CLOSES.load(Ordering::SeqCst), 0);
}

#[lifespan]
pub fn resource() -> Result<Resource<()>, String> {
    STARTS.fetch_add(1, Ordering::SeqCst);
    Ok(Resource::sync((), |_| {
        CLOSES.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }))
}

/// Runs the actual managed binding seam in a child: it owns stdin/stdout and
/// redirects implementation output, which must never affect the parent tests.
#[cfg(unix)]
#[test]
fn the_same_contract_fixtures_decode_invoke_and_encode_through_the_managed_adapter() {
    use flow_testing::{Rerun, rerun};
    use flow_tool_protocol::{Message, Served, served};
    use std::io::Write as _;
    use std::process::Stdio;
    const CONTRACT: &str = "FLOW_TEST_NATIVE_CONTRACT";
    let Rerun::Parent(mut command) =
        rerun(the_same_contract_fixtures_decode_invoke_and_encode_through_the_managed_adapter)
    else {
        let contract = std::fs::read(std::env::var_os(CONTRACT).unwrap()).unwrap();
        crate::function::serve(
            &[
                placed(__flow_tool_exact()),
                placed(__flow_tool_contextual()),
            ],
            &contract,
            Some(__flow_lifespan_resource),
        )
        .unwrap();
        assert_eq!(EXACT_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(CONTEXTUAL_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(STARTS.load(Ordering::SeqCst), 1);
        assert_eq!(CLOSES.load(Ordering::SeqCst), 1);
        return;
    };
    let files = tempfile::TempDir::with_prefix("flow-native-contract-positive-pair").unwrap();
    let listing = staged_listing(
        &[
            placed(__flow_tool_exact()),
            placed(__flow_tool_contextual()),
        ],
        "pub flow main() -> Result<Text, ToolProblem> = {
    let _ = test_contract.exact(1)?
    test_contract.contextual(\"text\")
}
",
    );
    let contract = files.path().join("contract");
    std::fs::write(&contract, &listing).unwrap();
    let amount = "12345678901234567890123456789012345678901234567890";
    let requests = requests(&tools(&listing), amount);
    let mut child = command
        .env(CONTRACT, contract)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .locked_spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(&requests).unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    // libtest's text before the test runs precedes serving on standard
    // output; the managed server's frames are all that follows it.
    let replies = (0..output.stdout.len())
        .find_map(|start| frames(&output.stdout[start..]))
        .expect("the server's frames");
    assert_eq!(replies.len(), 4);
    assert!(matches!(
        &replies[0],
        Message::Described(described) if described.version == flow_abi::DATA_VERSION
            && matches!(served(described), Ok(Served::Tools(tools)) if tools.len() == 2)
    ));
    let reply = |name: &str| {
        replies
            .iter()
            .find_map(|message| match message {
                Message::Reply(reply) if reply.call.to_string() == id(name) => Some(&reply.outcome),
                _ => None,
            })
            .unwrap()
    };
    let (native, encoded) = flow_abi_testing::crossing::crossed(&Record {
        amount: Int::parse(amount).unwrap(),
    });
    assert_eq!(reply("exact"), &flow_abi::Outcome::Ok(Rest(encoded)));
    assert_eq!(native.amount.to_string(), amount);
    assert_eq!(
        reply("contextual"),
        &flow_abi::Outcome::Ok(Rest(crate::test_types::bytes(
            &"한국 text".to_owned(),
            &flow_types::Type::Text
        )))
    );
    assert!(
        replies.iter().any(|message| matches!(
            message,
            Message::NoAnswer { call, reason, .. }
                if call.to_string() == id("bad-argument")
                    && reason.starts_with("the arguments do not decode: `amount`")
        )),
        "an argument that does not decode gets no answer: {replies:?}"
    );
}

/// The frames of a `describe`, then calls of `exact` with `amount`, of
/// `contextual`, and of `exact` with no arguments, each naming its Tool by
/// its place in the listed `tools`.
fn requests(tools: &[(description::Identity, TypeSpec)], amount: &str) -> Vec<u8> {
    use crate::test_types::bytes;
    use flow_types::Type;
    let index = |name: &str| {
        tools
            .iter()
            .position(|(identity, _)| identity.name == name)
            .and_then(|at| u64::try_from(at).ok())
            .expect("the listing has the Tool")
    };
    let call = |id: &str, tool: &str, args: Vec<u8>| {
        flow_tool_protocol::Message::Call(flow_tool_protocol::Call::new(
            flow_span::RunId::parse("7f3a91c04be2d5e6f708192a3b4c5d6e").unwrap(),
            flow_span::CallRef::parse(id).unwrap(),
            index(tool),
            None,
            &args,
        ))
    };
    [
        flow_tool_protocol::Message::Describe {
            version: flow_abi::DATA_VERSION,
            reply_limit: 16 << 20,
        },
        call(
            "root#1",
            "exact",
            bytes(&Int::parse(amount).unwrap(), &Type::Int),
        ),
        call(
            "root#2",
            "contextual",
            bytes(&"한국 text".to_owned(), &Type::Text),
        ),
        call("root#3", "exact", Vec::new()),
    ]
    .iter()
    .flat_map(flow_tool_protocol::Message::frame)
    .collect()
}

/// The id of the call [`requests`] names `name`: each call is named for
/// what it asks.
fn id(name: &str) -> &'static str {
    match name {
        "exact" => "root#1",
        "contextual" => "root#2",
        _ => "root#3",
    }
}

/// The messages `bytes` hold, when they are whole frames to the end.
fn frames(bytes: &[u8]) -> Option<Vec<flow_tool_protocol::Message>> {
    let mut input = flow_abi::primitives::Reader::new(bytes);
    let mut messages = Vec::new();
    while !input.is_empty() {
        let length = input.count().ok()?;
        messages.push(
            flow_tool_protocol::Message::parse(
                flow_tool_protocol::Route::Process,
                input.take(length).ok()?,
            )
            .ok()?,
        );
    }
    (!messages.is_empty()).then_some(messages)
}

/// Types of their own module, which the contract of this module imports.
pub mod models {
    use flow_toolkit::{Flow, Int};

    /// A refund.
    ///
    /// Its second paragraph.
    #[derive(Flow)]
    pub struct Refund {
        /// The amount, in cents.
        pub cents: Int,
        pub reason: Reason,
    }

    /// Why a refund was made.
    #[derive(Flow)]
    pub enum Reason {
        /// The customer asked.
        Asked,
        Damaged(String, Int),
        Other {
            /// What happened.
            note: String,
        },
    }
}

/// Refunds `cents` of `order`.
#[tool]
pub fn refund(order: String, cents: Int, raw: JsonValue) -> Result<models::Refund, Record> {
    let _ = (order, raw);
    Err(Record { amount: cents })
}

#[test]
fn contract_modules_import_each_others_types_and_keep_native_order_docs_and_names() {
    let contracts = common::extract(
        "flow_toolkit",
        Some(std::path::Path::new(env!("CARGO_MANIFEST_DIR"))),
        &[
            crate::__bridge::at(
                "test_contract",
                "src/test_contract.rs",
                900,
                __flow_tool_refund(),
            ),
            crate::__bridge::at(
                "test_contract",
                "src/test_contract.rs",
                20,
                __flow_tool_exact(),
            ),
        ],
    )
    .unwrap();
    assert_eq!(
        contracts.keys().map(Segments::as_str).collect::<Vec<_>>(),
        ["test_contract", "test_contract/models"]
    );
    let root = &contracts["test_contract"];
    assert!(
        root.starts_with(
            "// Generated by flow build from rust module flow_toolkit::test_contract. Do not edit.\nuse \"std@v1/json\"\nuse \"./test_contract/models\"\n\n"
        ),
        "{root}"
    );
    let record = root.find("pub type Record").unwrap();
    let exact = root.find("pub flow exact").unwrap();
    let refund = root.find("/// Refunds `cents` of `order`.\n// from src/test_contract.rs: refund\npub flow refund(order: Text, cents: Int, raw: json.Value) -> Result<models.Refund, Record>\n").unwrap();
    assert!(
        record < exact && exact < refund,
        "native source order: {root}"
    );
    let models = &contracts["test_contract/models"];
    assert!(
        models.starts_with("// Generated by flow build from rust module flow_toolkit::test_contract::models. Do not edit.\n\n/// A refund.\n///\n/// Its second paragraph.\n// from src/test_contract.rs: Refund\n"),
        "{models}"
    );
    assert!(
        models.contains(": Refund\npub type Refund {\n    /// The amount, in cents.\n    pub cents: Int,\n    pub reason: Reason,\n}\n\n/// Why a refund was made.\n"),
        "{models}"
    );
    assert!(
        models.ends_with(": Reason\npub type Reason {\n    /// The customer asked.\n    Asked,\n    Damaged(Text, Int),\n    Other {\n        /// What happened.\n        note: Text,\n    },\n}\n"),
        "{models}"
    );
    let foreign =
        common::extract("another_crate", None, &[placed(__flow_tool_exact())]).unwrap_err();
    assert!(
        foreign.to_string().contains(": Record is defined in flow_toolkit::test_contract, of a crate this library does not depend on"),
        "{foreign}"
    );
    let duplicate = common::extract(
        "flow_toolkit",
        None,
        &[placed(__flow_tool_exact()), placed(__flow_tool_exact())],
    )
    .unwrap_err();
    assert_eq!(
        duplicate.to_string(),
        "src/test_contract.rs:1:1: duplicate Tool name exact"
    );
    let misplaced = common::extract(
        "flow_toolkit",
        None,
        &[crate::__bridge::at(
            "Tools",
            "src/test_contract.rs",
            3,
            __flow_tool_contextual(),
        )],
    )
    .unwrap_err();
    assert!(
        misplaced
            .to_string()
            .starts_with("src/test_contract.rs:3:1: the module `Tools`"),
        "{misplaced}"
    );
}

#[test]
fn the_contract_macro_places_tools_where_they_are_defined_as_the_launcher_does() {
    let contract = crate::contract!(refund, exact).unwrap();
    let launcher = common::extract(
        "flow_toolkit",
        Some(std::path::Path::new(env!("CARGO_MANIFEST_DIR"))),
        &[
            crate::__bridge::at(
                "test_contract",
                "src/test_contract.rs",
                19,
                __flow_tool_exact(),
            ),
            crate::__bridge::at(
                "test_contract",
                "src/test_contract.rs",
                306,
                __flow_tool_refund(),
            ),
        ],
    )
    .unwrap();
    assert_eq!(
        contract
            .modules()
            .iter()
            .map(|(module, text)| (module.as_str(), text.as_str()))
            .collect::<Vec<_>>(),
        launcher
            .iter()
            .map(|(module, text)| (module.as_str(), text.as_str()))
            .collect::<Vec<_>>(),
    );
    let models = contract.modules().keys().nth(1).unwrap();
    assert_eq!(
        LibraryLayout::file(LibraryLayout::module_file(models, Placement::Contract).as_str()),
        "contract/test_contract/models.flow"
    );
    assert_eq!(
        contract.committed(models).unwrap_err().kind(),
        std::io::ErrorKind::NotFound
    );
}

#[test]
fn a_contract_is_canonical_flow_and_forms_with_its_imports() {
    let contracts = common::extract(
        "flow_toolkit",
        None,
        &[placed(__flow_tool_refund()), placed(__flow_tool_exact())],
    )
    .unwrap();
    let tools = common::listed(
        &contracts,
        &format!(
            "use \"std@v1/json\"
{EXACT}
pub flow every(raw: json.Value) -> Result<Unit, ToolProblem> = {{
    let _ = test_contract.refund(\"order\", 1, raw)?
    Ok(())
}}
"
        ),
    );
    assert_eq!(tools.len(), 2, "{tools:?}");
    for text in contracts.values() {
        let formatted = common::flow_fmt(text);
        assert_eq!(&formatted, text, "the contract is already canonical");
    }
}

/// Opens a session from a refund's raw details.
#[tool]
pub fn open_session(models: models::Refund, json: JsonValue) -> Result<models::Reason, String> {
    let _ = (models, json);
    Err(String::new())
}

#[test]
fn an_import_keeps_its_name_beside_a_parameter_of_that_name() {
    let contracts =
        common::extract("flow_toolkit", None, &[placed(__flow_tool_open_session())]).unwrap();
    let root = &contracts["test_contract"];
    assert!(
        root.contains("use \"std@v1/json\"\nuse \"./test_contract/models\"\n"),
        "{root}"
    );
    assert!(
        root.contains(
            "open_session(models: models.Refund, json: json.Value) -> Result<models.Reason, Text>"
        ),
        "{root}"
    );
}