flow-toolkit 0.1.0

Ordinary typed Rust functions and exact native data for Flow Tools, automatically prepared from direct native imports.
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! Native boundary code that needs care in Rust — keywords as names, types that
//! hold themselves, generic types applied to arguments, types with no
//! order, a generic Tool — compiled, converting values under the encoding,
//! and served over the Tool process protocol (`abi.md`, *The value
//! encoding*, *The Tool process protocol*, *Toolkits*).

use flow_abi::TypeSpec;

use crate::test_common as common;
#[path = "../tests/fixture/edge.rs"]
mod edge;

#[path = "../tests/fixture/phantom.rs"]
mod phantom;

use std::collections::BTreeMap;
use std::io::{Cursor, Write as _};
use std::sync::Arc;
use std::sync::mpsc::{Sender, channel};
use std::time::Duration;

use crate::server::{Declaration, Server};
use common::{listing, own};
use edge::{BoxBoxInt, BoxInt, BoxT, BoxText, Chain, Keywords, Loose, Shape, Tools2, Tree};
use flow_toolkit::{Context, Data, FlowType, Int, Json, JsonValue, Problem};

fn int(value: i64) -> Int {
    Int::from(value)
}

fn json(text: &str) -> Json {
    flow_abi::parse(text, &flow_abi::Limits::default()).expect("JSON")
}

fn raw(text: &str) -> JsonValue {
    JsonValue::decode(&json(text)).expect("a json.Value")
}

/// `value`'s canonical encoding, after checking it decodes back to itself.
fn round_trip<T: Data + PartialEq + std::fmt::Debug>(value: &T) -> String {
    let encoded = value.encode();
    assert_eq!(&T::decode(&encoded).expect("it decodes"), value);
    encoded.canonical()
}

fn refusal<T: Data + std::fmt::Debug>(text: &str) -> String {
    T::decode(&json(text))
        .expect_err("it does not decode")
        .to_string()
}

#[test]
fn a_type_that_holds_itself_is_boxed_and_encodes_as_its_declaration_says() {
    let chain = Chain {
        head: int(1),
        next: Some(Box::new(Chain {
            head: int(2),
            next: None,
            branches: vec![],
        })),
        branches: vec![Chain {
            head: int(3),
            next: None,
            branches: vec![],
        }],
    };
    assert_eq!(
        round_trip(&chain),
        r#"{"branches":[{"branches":[],"head":3}],"head":1,"next":{"branches":[],"head":2}}"#
    );
    let tree = Tree::Node(
        Box::new(Tree::Leaf(int(1))),
        Box::new(Tree::Forest(vec![Tree::Leaf(int(2))])),
    );
    assert_eq!(
        round_trip(&tree),
        r#"{"Node":[{"Leaf":1},{"Forest":[{"Leaf":2}]}]}"#
    );
}

#[test]
fn a_rust_keyword_is_a_name_on_the_rust_side_only() {
    let keywords = Keywords {
        r#impl: int(1),
        r#ref: "r".to_owned(),
        self_: true,
        r#mod: Some(int(4)),
    };
    assert_eq!(
        round_trip(&keywords),
        r#"{"impl":1,"mod":4,"ref":"r","self":true}"#
    );
    let unset = Keywords {
        r#mod: None,
        ..keywords
    };
    assert_eq!(round_trip(&unset), r#"{"impl":1,"ref":"r","self":true}"#);
}

#[test]
fn every_constructor_form_encodes_as_the_table_says() {
    assert_eq!(round_trip(&Shape::Dot), r#""Dot""#);
    assert_eq!(
        round_trip(&Shape::Labelled {
            label: Some("x".to_owned()),
            size: int(2)
        }),
        r#"{"Labelled":{"label":"x","size":2}}"#
    );
    assert_eq!(
        round_trip(&Shape::Labelled {
            label: None,
            size: int(2)
        }),
        r#"{"Labelled":{"size":2}}"#
    );
    assert_eq!(
        round_trip(&Shape::Pair((int(1), "one".to_owned()))),
        r#"{"Pair":[1,"one"]}"#
    );
    assert_eq!(round_trip(&Tools2::Tools(int(5))), r#"{"Tools":5}"#);
}

#[test]
fn a_generic_type_applied_to_arguments_is_a_type_of_its_own() {
    let nested = BoxBoxInt {
        value: BoxInt { value: int(7) },
    };
    assert_eq!(round_trip(&nested), r#"{"value":{"value":7}}"#);
    let text = BoxText {
        value: "t".to_owned(),
    };
    assert_eq!(round_trip(&text), r#"{"value":"t"}"#);
    let loose = Loose {
        raw: raw(r#"[1, 2.50, {"a": null}]"#),
        nested: edge::BoxJson { value: raw("true") },
    };
    assert_eq!(
        round_trip(&loose),
        r#"{"nested":{"value":true},"raw":[1,2.5,{"a":null}]}"#
    );
}

#[test]
fn a_type_holding_a_json_value_is_ordered_by_flows_order() {
    let loose = |text: &str| Loose {
        raw: raw(text),
        nested: edge::BoxJson { value: raw("null") },
    };
    assert_eq!(loose("1.0"), loose("1"));
    assert_eq!(loose(r#"{"b": 1, "a": 2}"#), loose(r#"{"a": 2, "b": 1}"#));
    let ordered: Vec<String> = ["[10]", "[9]", "true", "1", "null"]
        .map(loose)
        .into_iter()
        .collect::<std::collections::BTreeSet<_>>()
        .iter()
        .map(|value| value.raw.encode().canonical())
        .collect();
    assert_eq!(ordered, ["null", "true", "1", "[9]", "[10]"]);
}

#[test]
fn a_value_that_does_not_decode_is_refused_saying_where() {
    assert_eq!(
        refusal::<Chain>(r#"{"head": 1, "branches": [], "next": {"head": "x", "branches": []}}"#),
        "`next.head` should be an integer, not a string"
    );
    assert_eq!(refusal::<Chain>(r#"{"head": 1}"#), "`branches` is missing");
    assert_eq!(
        refusal::<Shape>(r#"{"Labelled": {"size": "big"}}"#),
        "`Labelled.size` should be an integer, not a string"
    );
    assert_eq!(
        refusal::<Tree>(r#"{"Node": [{"Leaf": 1}]}"#),
        "`Node` has 1 elements, not 2"
    );
    assert_eq!(
        refusal::<Tree>(r#"{"Node": [{"Leaf": 1}, {"Leaf": true}]}"#),
        "`Node[1].Leaf` should be an integer, not a boolean"
    );
    assert_eq!(
        refusal::<Shape>(r#"{"Dot": 1}"#),
        "the value names no constructor of `Shape`: `Dot` with a payload"
    );
    assert_eq!(
        refusal::<Shape>(r#""Square""#),
        "the value names no constructor of `Shape`: `Square` without a payload"
    );
    assert_eq!(
        refusal::<Shape>(r#"{"Labelled": 3}"#),
        "`Labelled` should be an object, not a number"
    );
    assert_eq!(
        refusal::<Keywords>("[]"),
        "the value should be an object, not an array"
    );
}

/// The edge declarations, each answering as the tests need; `started`
/// hears of each call that reached its method.
struct Edge {
    started: std::sync::Mutex<Sender<String>>,
}

impl Edge {
    fn started(&self, what: &str) {
        let _ = self
            .started
            .lock()
            .expect("no holder panics")
            .send(what.to_owned());
    }
}

impl Edge {
    fn walk(
        &self,
        context: &Context,
        chain: Chain,
        _: Tree,
    ) -> Result<Int, Problem<std::convert::Infallible>> {
        self.started(context.call());
        if chain.head != int(0) {
            return Ok(chain.head);
        }
        // Waits for its cancellation, which proves nothing either way.
        for _ in 0..100 {
            if context.cancelled() {
                return Err(Problem::Unknown("cancelled".to_owned()));
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        Ok(chain.head)
    }

    fn wrap(
        _: &Context,
        boxed: BoxInt,
        _: BoxText,
        keys: &BTreeMap<Int, String>,
    ) -> Result<BoxBoxInt, Problem<()>> {
        if keys.is_empty() {
            return Err(Problem::Failed(()));
        }
        Ok(BoxBoxInt { value: boxed })
    }

    fn r#fn(
        _: &Context,
        context: &Keywords,
        _: Loose,
        _: Shape,
    ) -> Result<Tools2, Problem<String>> {
        assert!(!context.self_, "asked to stop");
        if context.r#ref.is_empty() {
            std::panic::panic_any(7);
        }
        Err(Problem::NotRun(format!("not {}", context.r#ref)))
    }

    fn pick(&self, context: &Context, options: Vec<Json>, boxed: &BoxT) -> Json {
        self.started(context.call());
        assert_eq!(context.run(), "run-1");
        let schema = context.schema().cloned().unwrap_or(Json::Null);
        Json::Array(vec![
            options.into_iter().next().unwrap_or(Json::Null),
            boxed.value.json().clone(),
            schema,
        ])
    }
}

fn encoded_problem<E: Data>(problem: Problem<E>) -> Problem<Json> {
    match problem {
        Problem::Failed(value) => Problem::Failed(value.encode()),
        Problem::NotRun(reason) => Problem::NotRun(reason),
        Problem::Unknown(reason) => Problem::Unknown(reason),
    }
}

/// Private protocol fixture construction, never a native authoring API.
fn declarations(edge: &Arc<Edge>) -> Vec<Declaration> {
    let document = json(&listing(&own("tests/fixture/edge.flow")));
    let Json::Array(programs) = document.get("programs").unwrap() else {
        panic!()
    };
    let program = &programs[0];
    let Json::Object(templates) = program.get("types").unwrap() else {
        panic!()
    };
    let templates = templates.iter().cloned().collect();
    let Json::Array(tools) = program.get("tools").unwrap() else {
        panic!()
    };
    tools
        .iter()
        .map(|tool| {
            let name = tool.get("tool").unwrap().get("name").unwrap().clone();
            let mut spec = Json::Object(
                ["generic", "params", "ok", "err"]
                    .into_iter()
                    .map(|key| (key.into(), tool.get(key).unwrap().clone()))
                    .collect(),
            );
            let Json::Object(fields) = &mut spec else {
                panic!()
            };
            fields.push((
                "declarations".into(),
                crate::function::reachable_templates(tool, &templates).unwrap(),
            ));
            let spec = TypeSpec::read(&spec).unwrap();
            let edge = edge.clone();
            Declaration::contextual(&tool.canonical(), spec, move |context, args| {
                let convert = |answer: Result<Json, Problem<Json>>| Ok(answer);
                let Json::String(name) = &name else { panic!() };
                match name.as_str() {
                    "walk" => convert(
                        edge.walk(context, args.take("chain")?, args.take("tree")?)
                            .map(|v| v.encode())
                            .map_err(encoded_problem),
                    ),
                    "wrap" => convert(
                        Edge::wrap(
                            context,
                            args.take("boxed")?,
                            args.take("texts")?,
                            &args.take("keys")?,
                        )
                        .map(|v| v.encode())
                        .map_err(encoded_problem),
                    ),
                    "fn" => convert(
                        Edge::r#fn(
                            context,
                            &args.take("context")?,
                            args.take("loose")?,
                            args.take("shape")?,
                        )
                        .map(|v| v.encode())
                        .map_err(encoded_problem),
                    ),
                    "pick" => {
                        let codec = context.argument_codec("options")?;
                        let options = codec.decode(args.json("options")?)?;
                        let Json::Array(options) = options else {
                            panic!()
                        };
                        let boxed = BoxT::decode_context(
                            &context.argument_codec("boxed")?,
                            args.json("boxed")?,
                        )?;
                        let value = edge.pick(context, options, &boxed);
                        Ok(match context.success_codec()?.encode(&value) {
                            Ok(value) => Ok(value),
                            Err(error) => Err(Problem::Unknown(format!(
                                "the answer does not encode: {error}"
                            ))),
                        })
                    }
                    _ => panic!(),
                }
            })
        })
        .collect()
}

/// Every line `input` makes the server write, in order, once it is done.
fn served(input: &str) -> Vec<Json> {
    let (started, _) = channel();
    let edge = Edge {
        started: std::sync::Mutex::new(started),
    };
    let server = Server::new(edge::DATA_VERSION, declarations(&Arc::new(edge)));
    let mut output = Vec::new();
    server
        .run(Cursor::new(input.to_owned()), &mut output)
        .expect("served");
    String::from_utf8(output)
        .expect("UTF-8")
        .lines()
        .map(json)
        .collect()
}

const CALL: &str = r#"{"jsonrpc":"2.0","method":"call","params":{"run":"run-1","call":"CALL","tool":{"repository":null,"version":null,"file":"./edge","name":"NAME"},"args":ARGS}}"#;

fn call(call: &str, name: &str, args: &str) -> String {
    CALL.replace("CALL", call)
        .replace("NAME", name)
        .replace("ARGS", args)
}

fn generic_pick(id: &str, args: &str) -> String {
    call(id,"pick",args).replace(r#""args""#,r#""schema":{"$schema":"https://json-schema.org/draft/2020-12/schema"},"types":{"bindings":[{"name":"T","type":"json.Value"}],"params":[{"name":"options","type":{"List":"json.Value"}},{"name":"boxed","type":{"Named":{"declaration":"box","args":["json.Value"]}}}],"ok":"json.Value","err":"Text","declarations":{"box":{"name":"Box","identity":"./edge.Box","lexical_ordinal":1,"generic":["T"],"opaque":false,"kind":"record","doc":null,"fields":[{"name":"value","type":{"Param":{"owner":"box","index":0}},"doc":null}]}}},"args""#)
}

/// The outcome of the reply to `call` among `lines`.
fn outcome(lines: &[Json], call: &str) -> String {
    lines
        .iter()
        .find(|line| {
            line.get("params").and_then(|params| params.get("call"))
                == Some(&Json::String(call.to_owned()))
        })
        .and_then(|line| line.get("params"))
        .and_then(|params| params.get("outcome"))
        .unwrap_or_else(|| panic!("no reply to {call}"))
        .canonical()
}

#[test]
fn describe_lists_each_declaration_by_identity_fingerprint_and_signature() {
    let lines = served(r#"{"jsonrpc":"2.0","method":"describe","params":{"data":"0.1"},"id":7}"#);
    assert_eq!(lines.len(), 1);
    let answer = &lines[0];
    assert_eq!(answer.get("id"), Some(&json("7")));
    assert_eq!(answer.get("jsonrpc"), Some(&json(r#""2.0""#)));
    let result = answer.get("result").expect("a result");
    assert_eq!(result.get("data"), Some(&json(r#""0.1""#)));
    let Some(Json::Array(tools)) = result.get("tools") else {
        panic!("a list of declarations")
    };
    let listed = json(&listing(&own("tests/fixture/edge.flow")));
    let Some(Json::Array(programs)) = listed.get("programs") else {
        panic!("programs")
    };
    let Some(Json::Array(declared)) = programs[0].get("tools") else {
        panic!("tools")
    };
    assert_eq!(tools.len(), declared.len());
    let (started, _) = channel();
    let edge = Edge {
        started: std::sync::Mutex::new(started),
    };
    let server = Server::new("0.1", declarations(&Arc::new(edge)));
    let shown = format!("{server:?}");
    assert!(
        shown.starts_with(r#"Server { data: "0.1", declarations: [Declaration { entry: "#),
        "{shown}"
    );
    for (served, declared) in tools.iter().zip(declared) {
        for key in ["tool", "fingerprint", "signature"] {
            assert_eq!(served.get(key), declared.get(key), "{key}");
        }
    }
}

#[test]
fn a_call_is_answered_with_its_outcome() {
    let chain = r#"{"head": 4, "branches": []}"#;
    let input = [
        call("c1", "wrap", r#"{"boxed": {"value": 1}, "texts": {"value": "t"}, "keys": [[2, "b"], [1, "a"]]}"#),
        call("c2", "wrap", r#"{"boxed": {"value": 1}, "texts": {"value": "t"}, "keys": []}"#),
        call("c3", "fn", r#"{"context": {"impl": 1, "ref": "here", "self": false}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
        generic_pick("c4", r#"{"options":[{"x":1}],"boxed":{"value":2}}"#),
        call("c5", "walk", &format!(r#"{{"chain": {chain}, "tree": {{"Leaf": 1}}}}"#)),
    ]
    .join("\n");
    let lines = served(&input);
    assert_eq!(outcome(&lines, "c1"), r#"{"Ok":{"value":{"value":1}}}"#);
    assert_eq!(outcome(&lines, "c2"), r#"{"Failed":[]}"#);
    assert_eq!(outcome(&lines, "c3"), r#"{"NotRun":"not here"}"#);
    assert_eq!(
        outcome(&lines, "c4"),
        r#"{"Ok":[{"x":1},2,{"$schema":"https://json-schema.org/draft/2020-12/schema"}]}"#
    );
    assert_eq!(outcome(&lines, "c5"), r#"{"Ok":4}"#);
    let reply = lines
        .iter()
        .find(|line| line.get("method") == Some(&json(r#""reply""#)))
        .expect("a reply");
    assert_eq!(reply.get("jsonrpc"), Some(&json(r#""2.0""#)));
    assert_eq!(
        reply.get("params").and_then(|params| params.get("run")),
        Some(&json(r#""run-1""#))
    );
}

#[test]
fn a_call_the_implementation_cannot_take_is_answered_not_run() {
    let input = [
        call(
            "c1",
            "wrap",
            r#"{"boxed": {"value": "one"}, "texts": {"value": "t"}, "keys": []}"#,
        ),
        call("c2", "wrap", r#"{"texts": {"value": "t"}, "keys": []}"#),
        call("c3", "nothing", "{}"),
        call("c4", "wrap", "[]"),
    ]
    .join("\n");
    let lines = served(&input);
    assert_eq!(
        outcome(&lines, "c1"),
        r#"{"NotRun":"the arguments do not decode: `boxed.value` should be an integer, not a string"}"#
    );
    assert_eq!(
        outcome(&lines, "c2"),
        r#"{"NotRun":"the arguments do not decode: `boxed` is missing"}"#
    );
    assert_eq!(
        outcome(&lines, "c3"),
        r#"{"NotRun":"this implementation serves no declaration {\"file\":\"./edge\",\"name\":\"nothing\",\"repository\":null,\"version\":null}"}"#
    );
    assert_eq!(
        outcome(&lines, "c4"),
        r#"{"NotRun":"the arguments do not decode: `boxed` is missing"}"#
    );
}

#[test]
fn a_method_that_panics_is_answered_unknown() {
    let input = [
        call("c1", "fn", r#"{"context": {"impl": 1, "ref": "r", "self": true}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
        call("c2", "fn", r#"{"context": {"impl": 1, "ref": "", "self": false}, "loose": {"raw": 1, "nested": {"value": 2}}, "shape": "Dot"}"#),
    ]
    .join("\n");
    let lines = served(&input);
    assert_eq!(
        outcome(&lines, "c1"),
        r#"{"Unknown":"the implementation stopped: asked to stop"}"#
    );
    assert_eq!(
        outcome(&lines, "c2"),
        r#"{"Unknown":"the implementation stopped: it panicked"}"#
    );
}

#[test]
fn a_line_that_is_no_message_the_implementation_acts_on_is_ignored() {
    let input = [
        "not json".to_owned(),
        r#"{"jsonrpc":"2.0","method":"call","params":{"call":"c0"}}"#.to_owned(),
        r#"{"jsonrpc":"2.0","method":"call","params":{"run":"run-1"}}"#.to_owned(),
        r#"{"jsonrpc":"2.0","method":"cancel","params":{"run":"run-1","call":"nobody"}}"#
            .to_owned(),
        r#"{"jsonrpc":"2.0","method":"cancel","params":{}}"#.to_owned(),
        r#"{"jsonrpc":"2.0","method":"other","params":{}}"#.to_owned(),
        r#"{"jsonrpc":"2.0","result":{}}"#.to_owned(),
        r#"{"jsonrpc":"2.0","method":"describe"}"#.to_owned(),
    ]
    .join("\n");
    let lines = served(&input);
    assert_eq!(lines.len(), 1, "only the describe is answered");
    assert_eq!(lines[0].get("id"), Some(&Json::Null));
}

/// The outcome of a `walk` that waits to be cancelled, sent `after` once
/// it has started.
fn walked(after: &str) -> String {
    let (started, heard) = channel();
    let edge = Edge {
        started: std::sync::Mutex::new(started),
    };
    let server = Server::new(edge::DATA_VERSION, declarations(&Arc::new(edge)));
    let (reader, mut writer) = std::io::pipe().expect("a pipe");
    let chain = r#"{"head": 0, "branches": []}"#;
    let line = call(
        "c1",
        "walk",
        &format!(r#"{{"chain": {chain}, "tree": {{"Leaf": 1}}}}"#),
    );
    let lines = std::thread::scope(|scope| {
        let serving = scope.spawn(|| {
            let mut output = Vec::new();
            server
                .run(std::io::BufReader::new(reader), &mut output)
                .expect("served");
            output
        });
        writeln!(writer, "{line}").expect("sent");
        assert_eq!(heard.recv().expect("the call started"), "c1");
        writeln!(writer, "{after}").expect("sent");
        drop(writer);
        serving.join().expect("the server ends")
    });
    let lines: Vec<Json> = String::from_utf8(lines)
        .expect("UTF-8")
        .lines()
        .map(json)
        .collect();
    outcome(&lines, "c1")
}

#[test]
fn a_cancel_reaches_the_method_working_on_its_call() {
    assert_eq!(
        walked(r#"{"jsonrpc":"2.0","method":"cancel","params":{"run":"run-1","call":"c1"}}"#),
        r#"{"Unknown":"cancelled"}"#
    );
}

#[test]
fn only_a_cancel_cancels() {
    assert_eq!(
        walked(r#"{"jsonrpc":"2.0","method":"other","params":{"run":"run-1","call":"c1"}}"#),
        r#"{"Ok":0}"#
    );
}

#[test]
fn a_context_says_which_call_it_is_for() {
    let context = Context::try_new(
        "run-2",
        "root#3",
        &flow_abi::TypeSpec::read(&json(
            r#"{"generic":[],"params":[],"ok":"Int","err":"Text","declarations":{}}"#,
        ))
        .unwrap(),
        None,
        None,
        Arc::new(std::sync::atomic::AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(context.run(), "run-2");
    assert_eq!(context.call(), "root#3");
    assert_eq!(context.schema(), None);
    assert!(!context.cancelled());
    let shared = context.clone();
    shared.cancel();
    assert!(context.cancelled());
    assert!(context.types().is_none());
}

#[test]
fn generated_phantom_values_roundtrip_only_their_actual_int_field() {
    let value = phantom::PhantomFunctionIntToText { n: int(7) };
    assert_eq!(round_trip(&value), r#"{"n":7}"#);
    assert!(value < phantom::PhantomFunctionIntToText { n: int(8) });
    assert_eq!(
        round_trip(&phantom::PhantomRegex { n: int(7) }),
        r#"{"n":7}"#
    );
    assert_eq!(
        round_trip(&phantom::PhantomTaskInt { n: int(7) }),
        r#"{"n":7}"#
    );
    assert_eq!(
        round_trip(&phantom::PhantomPhantomFunctionTextToInt { n: int(7) }),
        r#"{"n":7}"#
    );
    assert_eq!(
        round_trip(&phantom::PhantomFunctionCallbackToInt { n: int(7) }),
        r#"{"n":7}"#
    );
}

#[test]
fn invalid_generic_metadata_and_args_refuse_before_author_but_invalid_output_is_unknown() {
    let good = generic_pick("good", r#"{"options":[1],"boxed":{"value":2}}"#);
    let mut input = vec![good.clone()];
    for (id, from, to) in [
        ("missing", r#""types""#, r#""absent""#),
        (
            "schema",
            r#""$schema":"https://json-schema.org/draft/2020-12/schema""#,
            r#""type":"integer""#,
        ),
        (
            "binding",
            r#""name":"T","type":"json.Value""#,
            r#""name":"U","type":"json.Value""#,
        ),
        (
            "known",
            r#""owner":"box","index":0"#,
            r#""owner":"box","index":1"#,
        ),
    ] {
        input.push(
            good.replace(r#""call":"good""#, &format!(r#""call":"{id}""#))
                .replace(from, to),
        );
    }
    let integer = generic_pick("after", r#"{"options":[1],"boxed":{"value":2}}"#)
        .replace(r#""json.Value""#, r#""Int""#)
        .replace(
            r#""$schema":"https://json-schema.org/draft/2020-12/schema""#,
            r#""$schema":"https://json-schema.org/draft/2020-12/schema","type":"integer""#,
        );
    input.push(integer.clone());
    input.push(
        integer
            .replace(r#""call":"after""#, r#""call":"args""#)
            .replace(r#""options":[1]"#, r#""options":["wrong"]"#),
    );
    let (started, heard) = channel();
    let server = Server::new(
        edge::DATA_VERSION,
        declarations(&Arc::new(Edge {
            started: std::sync::Mutex::new(started),
        })),
    );
    let mut output = Vec::new();
    server
        .run(Cursor::new(input.join("\n")), &mut output)
        .unwrap();
    let lines = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(json)
        .collect::<Vec<_>>();
    for id in ["missing", "schema", "binding", "known", "args"] {
        assert!(
            outcome(&lines, id).starts_with(r#"{"NotRun":"#),
            "{}",
            outcome(&lines, id)
        );
    }
    assert!(outcome(&lines, "good").starts_with(r#"{"Ok":"#));
    assert!(outcome(&lines, "after").starts_with(r#"{"Unknown":"the answer does not encode:"#));
    let mut invoked = heard.try_iter().collect::<Vec<_>>();
    invoked.sort();
    assert_eq!(invoked, ["after", "good"]);
}