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
//! Holding a call and answering it later (`abi.md`, *Toolkits*; `history.md`,
//! *A hold is a promise*): a call's key, `reply`, the testing helper, and a
//! held call under a real `flow run`, answered by toolkit `reply`, and asked
//! again at its `retry_at`.

mod common;

use flow_start::Spawn as _;
use flow_testing::{Rerun, rerun};
use std::path::{Path, PathBuf};
use std::process::Command;

use common::own;
use flow_toolkit::testing::{self, Sent};
use flow_toolkit::{
    Ack, CallKey, Context, Hold, Json, KeyError, NoAnswer, NoType, PlaceKind, ReplyError,
    ToolProblem, Untyped, reply, reply_at,
};
use tempfile::TempDir;

const RUN: &str = "7f3a91c04be2d5e6f708192a3b4c5d6e";

fn vectors() -> Json {
    let text = std::fs::read_to_string(own("../conformance/hold.json")).expect("the vectors");
    flow_toolkit::parse_json(&text).expect("JSON")
}

fn text(json: Option<&Json>) -> &str {
    match json {
        Some(Json::String(text)) => text,
        other => panic!("expected text, found {other:?}"),
    }
}

#[test]
fn a_keys_text_form_is_read_and_refused_as_the_shared_vectors_say() {
    let vectors = vectors();
    let Some(Json::Array(keys)) = vectors.get("keys") else {
        panic!()
    };
    for key in keys {
        let parsed: CallKey = text(key.get("text")).parse().expect("a key");
        assert_eq!(parsed.run().as_str(), text(key.get("run")));
        assert_eq!(parsed.call().to_string(), text(key.get("call")));
        assert_eq!(parsed.to_string(), text(key.get("text")));
    }
    let Some(Json::Array(refused)) = vectors.get("refused_keys") else {
        panic!()
    };
    for bad in refused {
        let written = text(bad.get("text"));
        let error = written.parse::<CallKey>().expect_err(written);
        let part = match &error {
            KeyError::NoSlash { text } => {
                assert_eq!(text, written);
                "slash"
            }
            KeyError::Run(place) => {
                assert_eq!(place.kind(), PlaceKind::Run);
                "run"
            }
            KeyError::Call(place) => {
                assert_eq!(place.kind(), PlaceKind::Call);
                "call"
            }
        };
        assert_eq!(part, text(bad.get("refused")), "{written:?}: {error}");
    }
}

/// A Tool that asks a person and holds until the answer comes back.
fn approve(context: &Context, order: &str) -> Result<bool, NoAnswer> {
    if context.cancelled() {
        return Ok(false);
    }
    if order.is_empty() {
        return Err(ToolProblem::NotStarted("no order".into()).into());
    }
    Err(Hold::new().into())
}

#[test]
fn a_test_drives_a_held_call_and_the_reply_that_answers_it_without_a_host() {
    let key = CallKey::new(
        flow_span::RunId::parse(RUN).unwrap(),
        flow_span::CallRef::parse("root#1").unwrap(),
    );
    assert_eq!(
        approve(&Context::for_test(key.clone()), "o-17"),
        Err(Hold::new().into())
    );
    let replies = testing::replies();
    assert_eq!(
        reply(&key, Ok(true)).unwrap(),
        Ack::Ok,
        "the first reply is recorded"
    );
    assert_eq!(
        reply(&key.to_string(), Ok(true)).unwrap(),
        Ack::AlreadyAnswered { same: true },
        "a key's text form names the same call"
    );
    assert_eq!(
        reply(
            &key,
            Err::<bool, _>(ToolProblem::Interrupted("lost".into()))
        )
        .unwrap(),
        Ack::AlreadyAnswered { same: false }
    );
    let other = CallKey::new(
        flow_span::RunId::parse(RUN).unwrap(),
        flow_span::CallRef::parse("root#2").unwrap(),
    );
    assert_eq!(
        reply(&other, Ok::<bool, ToolProblem>(false)).unwrap(),
        Ack::Ok
    );
    let sent: Vec<Sent> = replies.sent();
    assert_eq!(sent.len(), 4);
    assert_eq!(
        (&sent[0].key, &sent[0].answer),
        (&key, &Ok("true".to_owned()))
    );
    assert_eq!(sent[2].answer, Err(ToolProblem::Interrupted("lost".into())));
    assert_eq!(sent[3].key, other);
    drop(replies);
    let withdrawn = Context::for_test(key);
    withdrawn.cancel();
    assert_eq!(
        approve(&withdrawn, "o-17"),
        Ok(false),
        "a withdrawal takes the question back"
    );
}

#[test]
fn reply_refuses_text_that_is_no_key_before_sending_anything() {
    let replies = testing::replies();
    assert!(matches!(
        reply("not a key", Ok(true)),
        Err(ReplyError::Key(_))
    ));
    assert!(replies.sent().is_empty(), "nothing was sent");
    for error in [
        ReplyError::NoSocket,
        ReplyError::Untyped(Untyped {
            reason: NoType::UnknownRun,
            said: "no such run".into(),
        }),
    ] {
        assert_ne!(error.to_string(), "", "{error:?} says what happened");
    }
}

#[test]
fn a_reply_no_host_answers_carries_the_sockets_own_error() {
    let directory = TempDir::new().expect("a directory");
    let socket = directory.path().join("absent.sock");
    let refused = reply_at(&socket, &format!("{RUN}/root#1"), Ok(true));
    let Err(ReplyError::Socket { socket: at, error }) = &refused else {
        panic!("{refused:?}")
    };
    assert_eq!(at, &socket);
    assert_eq!(error.kind(), std::io::ErrorKind::NotFound, "{error}");
}

/// `flow`, built from this workspace, reaching nothing outside the test,
/// its Flow home `home` ([`flow_testing::Outside::command`]).
fn flow_command(home: &Path) -> Command {
    flow_testing::workspace_flow(flow_testing::outside!(), &own("")).command(home)
}

/// A Rust library at `<project>/tools` whose `ask` and `pay` hold until a
/// reply, and whose `poll` holds a second the first time it is asked and answers when
/// asked again.
fn library(project: &Path) {
    let tools = project.join("tools");
    std::fs::create_dir_all(tools.join("src")).expect("the library directory");
    std::fs::write(
        tools.join("flow.toml"),
        common::flow_toml(common::rust_toolkit()),
    )
    .expect("flow.toml");
    std::fs::write(
        tools.join("src/lib.rs"),
        r#"use flow_toolkit::{CallKey, Context, Hold, NoAnswer, tool};
use std::collections::BTreeSet;
use std::sync::Mutex;

static ASKED: Mutex<BTreeSet<CallKey>> = Mutex::new(BTreeSet::new());

/// Asks a person; the answer comes back as a reply.
#[tool]
pub fn ask(context: &Context) -> Result<String, NoAnswer> {
    let _ = context.key();
    Err(Hold::new().into())
}

/// Charges a card once the processor calls back: a receipt, or why it was
/// declined.
#[tool]
pub fn pay(context: &Context) -> Result<Result<String, String>, NoAnswer> {
    let _ = context.key();
    Err(Hold::new().into())
}

/// Holds a moment the first time, and answers when asked again.
#[tool]
pub fn poll(context: &Context) -> Result<String, NoAnswer> {
    if ASKED.lock().unwrap().insert(context.key()) {
        let soon = std::time::SystemTime::now() + std::time::Duration::from_millis(300);
        return Err(Hold::until(soon).into());
    }
    Ok(format!("asked again: {}", context.call()))
}
"#,
    )
    .expect("lib.rs");
    common::toolkit_consumer(&tools, "held", "");
}

fn program(project: &Path, tool: &str) -> String {
    let path = project.join(format!("{tool}.flow"));
    std::fs::write(
        &path,
        format!(
            "use \"./tools\"\npub flow main() -> Text = match tools.{tool}() {{ Ok(value) => value, Err(_) => \"failed\" }}\n"
        ),
    )
    .expect("the program");
    path.to_str().expect("a UTF-8 path").to_owned()
}

/// The exit code and the JSON document `flow` printed
/// for `args`, run as a process of its own, whose `FLOW_HOME` is `home`.
fn flow(home: &Path, args: &[&str]) -> (Option<i32>, Json) {
    let output = flow_command(home)
        .args(args)
        .arg("--json")
        .locked_output()
        .expect("flow runs");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json = flow_toolkit::parse_json(&stdout)
        .unwrap_or_else(|_| panic!("{stdout}\n{}", String::from_utf8_lossy(&output.stderr)));
    (output.status.code(), json)
}

/// The run's id, after `flow run` left its one call held.
fn held(home: &Path, file: &str) -> String {
    let (code, document) = flow(home, &["run", file]);
    assert_eq!(code, Some(3), "{document:?}");
    let data = document.get("data").expect("a data member");
    assert_eq!(text(data.get("state")), "waiting", "the run waits");
    assert_eq!(
        data.get("open"),
        Some(&Json::Array(vec![Json::String("root#1".into())])),
        "its one call is open"
    );
    text(data.get("run")).to_owned()
}

fn resumed(home: &Path, run: &str) -> String {
    let (code, document) = flow(home, &["resume", run]);
    assert_eq!(code, Some(0), "{document:?}");
    text(document.get("data").and_then(|data| data.get("value"))).to_owned()
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the webhook it runs as its own child, then the round trips that webhook answers"
)]
fn a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at() {
    if let Rerun::Child =
        rerun(a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at)
    {
        let key: CallKey = std::env::var("FLOW_TOOLKIT_TEST_KEY")
            .unwrap()
            .parse()
            .unwrap();
        let mode = std::env::var("FLOW_TOOLKIT_TEST_MODE").unwrap_or_default();
        if mode == "ok" || mode == "err" {
            let answer: Result<String, String> = if mode == "ok" {
                Ok("r-1".to_owned())
            } else {
                Err("insufficient funds".to_owned())
            };
            let acks = [reply(&key, Ok(answer.clone())), reply(&key, Ok(answer))];
            let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
            println!("acks: {acks:?}");
            return;
        }
        if mode == "problem" {
            let timeout = || ToolProblem::Interrupted("--timeout".into());
            let acks = [
                reply(&key, Err::<String, _>(timeout())),
                reply(&key, Err::<String, _>(timeout())),
                reply(
                    &key,
                    Err::<String, _>(ToolProblem::Interrupted("timeout".into())),
                ),
            ];
            let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
            println!("acks: {acks:?}");
            return;
        }
        // The call answers Text: an Int does not have its type, so no reply is
        // sent, and the call stays open.
        println!(
            "an Int is not sent: {}",
            matches!(
                reply(&key, Ok(flow_toolkit::Int::from(7))),
                Err(ReplyError::Mistyped(_))
            )
        );
        let acks = [
            reply(&key, Ok("by the toolkit".to_owned())),
            reply(&key, Ok("by the toolkit".to_owned())),
            reply(
                &key,
                Err::<String, _>(ToolProblem::NotStarted("too late".into())),
            ),
        ];
        let acks: Vec<Ack> = acks.into_iter().map(Result::unwrap).collect();
        println!("acks: {acks:?}");
        // A call the run never made has no type: an error, and nothing recorded.
        let unknown = reply(&format!("{}/root#9", key.run()), Ok("x".to_owned()));
        println!(
            "unknown call refused: {}",
            matches!(
                unknown,
                Err(ReplyError::Untyped(Untyped {
                    reason: NoType::NoSuchCall,
                    said,
                })) if said.contains("root#9")
            )
        );
        return;
    }
    let project = TempDir::with_prefix("flow-rust-hold").unwrap();
    let root = project.path();
    library(root);
    // A private home: its daemon takes the toolkit's replies, for the runs
    // the home keeps.
    let home = root.join("home");
    owner_only(&home);
    let _daemon = Daemon(home.clone());

    // flow run -> held -> toolkit reply, from another process, over the
    // daemon's socket -> flow resume.
    let ask = program(root, "ask");
    let run = held(&home, &ask);
    let (code, document) = flow(&home, &["stop", &run]);
    assert_eq!(code, Some(0), "{document:?}");
    let said = webhook(&home, &run, "value");
    assert!(
        said.contains("an Int is not sent: true")
            && said.contains(
                "acks: [Ok, AlreadyAnswered { same: true }, AlreadyAnswered { same: false }]"
            ),
        "{said}"
    );
    assert!(said.contains("unknown call refused: true"), "{said}");
    assert_eq!(resumed(&home, &run), "by the toolkit");

    // A problem's reason that looks like an option is the reason, not an
    // option: the repeat with the same reason is the same answer.
    let run = held(&home, &ask);
    let (code, document) = flow(&home, &["stop", &run]);
    assert_eq!(code, Some(0), "{document:?}");
    let said = webhook(&home, &run, "problem");
    assert!(
        said.contains(
            "acks: [Ok, AlreadyAnswered { same: true }, AlreadyAnswered { same: false }]"
        ),
        "{said}"
    );
    assert_eq!(resumed(&home, &run), "failed");

    let run = held(&home, &ask);
    let _ = webhook(&home, &run, "value");
    let followed = flow_command(&home)
        .args(["logs", "-f", &run])
        .locked_output()
        .expect("the log follows the run to completion");
    assert!(followed.status.success(), "{followed:?}");
    let (code, document) = flow(&home, &["show", &run, "--kind", "End"]);
    assert_eq!(code, Some(0), "{document:?}");
    let data = document.get("data").expect("the completed run");
    assert_eq!(text(data.get("state")), "completed");
    assert!(
        data.canonical()
            .contains(r#""values":{"value":"by the toolkit"}"#),
        "{data:?}"
    );

    // A call whose result is a Result is answered Ok or Err at that type.
    let pay = root.join("pay.flow");
    std::fs::write(
        &pay,
        "use \"./tools\"\npub flow main() -> Text = match tools.pay() { Ok(Ok(receipt)) => receipt, Ok(Err(declined)) => declined, Err(_) => \"failed\" }\n",
    )
    .expect("the program");
    let pay = pay.to_str().expect("a UTF-8 path");
    for (mode, ended) in [("ok", "r-1"), ("err", "insufficient funds")] {
        let run = held(&home, pay);
        let (code, document) = flow(&home, &["stop", &run]);
        assert_eq!(code, Some(0), "{document:?}");
        let said = webhook(&home, &run, mode);
        assert!(
            said.contains("acks: [Ok, AlreadyAnswered { same: true }]"),
            "{said}"
        );
        assert_eq!(resumed(&home, &run), ended);
    }

    // retry_at: the run stays to ask again, and the second ask answers.
    let poll = program(root, "poll");
    let (code, document) = flow(&home, &["run", &poll]);
    assert_eq!(code, Some(0), "{document:?}");
    assert_eq!(
        text(document.get("data").and_then(|data| data.get("value"))),
        "asked again: root#1"
    );
}

/// Creates `dir` as a home the daemon accepts: only its owner may write to
/// it, whatever the umask.
fn owner_only(dir: &Path) {
    std::fs::create_dir(dir).expect("the home");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).expect("chmod");
    }
}

/// Starts the daemon of `home`, and gives the socket it takes replies on, as
/// `flow daemon status` says it.
fn started(home: &Path) -> PathBuf {
    let daemon = |command: &str| {
        let output = flow_command(home)
            .args(["daemon", command, "--json"])
            .locked_output()
            .expect("flow daemon runs");
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        output
    };
    daemon("start");
    let status = daemon("status");
    let status = flow_toolkit::parse_json(&String::from_utf8_lossy(&status.stdout))
        .expect("flow daemon status prints one JSON document");
    PathBuf::from(text(status.get("data").and_then(|data| data.get("socket"))))
}

/// Stops the daemon of its home when dropped.
struct Daemon(PathBuf);

impl Drop for Daemon {
    fn drop(&mut self) {
        let _ = flow_command(&self.0)
            .args(["daemon", "stop"])
            .locked_output();
    }
}

/// What the webhook below printed, answering `run`'s call `root#1` as `mode`
/// says, from a process of its own whose `FLOW_REPLY_SOCKET` is the socket of
/// `home`'s daemon, started for it, since an idle one exits.
fn webhook(home: &Path, run: &str, mode: &str) -> String {
    let socket = started(home);
    let Rerun::Parent(mut command) =
        rerun(a_held_call_is_answered_by_toolkit_reply_and_asked_again_at_retry_at)
    else {
        unreachable!("only the parent starts the webhook");
    };
    let webhook = command
        .env("FLOW_REPLY_SOCKET", &socket)
        .env("FLOW_TOOLKIT_TEST_KEY", format!("{run}/root#1"))
        .env("FLOW_TOOLKIT_TEST_MODE", mode)
        .locked_output()
        .expect("the webhook runs");
    let said = String::from_utf8_lossy(&webhook.stdout).into_owned();
    assert!(
        webhook.status.success(),
        "{said}\n{}",
        String::from_utf8_lossy(&webhook.stderr)
    );
    said
}