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
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! Answering an open call from outside it (`abi.md`, *Toolkits* and
//! *Replies from outside a call*).
//!
//! [`reply`] answers the call a [`CallKey`] names from anywhere: a webhook
//! receiver, a script, another Tool, with an answer: `Ok` with a value of
//! the call's result type, or `Err` with a [`ToolProblem`]. A hold is no
//! answer, so it has no way to be sent. It returns once the
//! host has committed or refused the reply, with the [`Ack`] every route
//! that offers an answer gets.
//!
//! The reply reaches the host as a client outside any Tool process: it sends
//! its data version as `describe` (1) carries it, asks the call's result
//! type with `type` (10) and reads the host's `type` (11), then sends one
//! `reply` (4) frame whose `Ok` answer is the value in the value encoding at
//! that type, and reads the `ack` (7). It connects to the Unix-domain socket
//! where the host that holds the run takes such clients: the one
//! [`reply_at`] is given, or for [`reply`] the one `FLOW_REPLY_SOCKET`
//! names, which a host sets for the implementations it starts. With neither
//! there is no host to reply to, and nothing else is looked for.

use std::io::ErrorKind;
#[cfg(unix)]
use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use flow_abi::{Ack, DATA_VERSION, Untyped};
#[cfg(unix)]
use flow_abi::{Outcome, ResultType};
#[cfg(unix)]
use flow_tool_protocol::{Frame, Message, Route};

use std::fmt::Debug;

use flow_abi::wire::Shaped;

use crate::data::DecodeError;
#[cfg(unix)]
use crate::data::refused;
use crate::key::{CallKey, KeyError};
use crate::server::ToolProblem;

/// What can name a call for [`reply`]: a [`CallKey`], or its text form.
pub trait ToCallKey {
    /// The key.
    ///
    /// # Errors
    ///
    /// Text that is not a key's text form.
    fn to_call_key(&self) -> Result<CallKey, KeyError>;
}

impl ToCallKey for CallKey {
    fn to_call_key(&self) -> Result<CallKey, KeyError> {
        Ok(self.clone())
    }
}

impl ToCallKey for str {
    fn to_call_key(&self) -> Result<CallKey, KeyError> {
        self.parse()
    }
}

impl ToCallKey for String {
    fn to_call_key(&self) -> Result<CallKey, KeyError> {
        self.parse()
    }
}

/// Why [`reply`] has no [`Ack`]: nothing was sent, or the host was not
/// reached or does not hold the call's run.
#[derive(Debug)]
#[non_exhaustive]
pub enum ReplyError {
    /// The text given is not a key's text form; nothing was sent.
    Key(KeyError),
    /// The value is not one of the call's result type, and why; no reply
    /// was sent.
    Mistyped(DecodeError),
    /// No socket was given and `FLOW_REPLY_SOCKET` names none, so there is
    /// no host to send to; nothing was sent.
    NoSocket,
    /// The host's socket at `socket` failed: no host answers there, or the
    /// connection failed while the reply was under way.
    Socket {
        /// The host's socket.
        socket: PathBuf,
        /// What the system said.
        error: std::io::Error,
    },
    /// The host at `socket` sent something other than the `expected` frame
    /// about the reply's call.
    Answered {
        /// The host's socket.
        socket: PathBuf,
        /// The frame the host owed.
        expected: ReplyStep,
    },
    /// The host has no result type for the call, and says why; no reply was
    /// sent.
    Untyped(Untyped),
    /// The host at `socket` ended the connection before it acked the reply to
    /// `key`: it does not hold the run, the run never made the call, the run's
    /// program cannot be formed, or it takes no replies of this data version.
    /// Nothing was recorded.
    Ended {
        /// The host's socket.
        socket: PathBuf,
        /// The call the reply answers.
        key: Box<CallKey>,
    },
}

impl std::fmt::Display for ReplyError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReplyError::Key(error) => write!(formatter, "{error}"),
            ReplyError::Mistyped(error) => {
                write!(
                    formatter,
                    "the reply is not a value of the call's type: {error}"
                )
            }
            ReplyError::NoSocket => formatter.write_str(
                "the host was not reached: FLOW_REPLY_SOCKET is not set: a reply goes to the \
                 socket of the host that holds the run, which FLOW_REPLY_SOCKET names or \
                 reply_at is given",
            ),
            ReplyError::Socket { socket, error } => write!(
                formatter,
                "the host was not reached: the reply socket {}: {error}",
                socket.display()
            ),
            ReplyError::Answered { socket, expected } => write!(
                formatter,
                "the host was not reached: the host at {} did not answer with the reply's {}",
                socket.display(),
                match expected {
                    ReplyStep::Type => "type",
                    ReplyStep::Ack => "ack",
                }
            ),
            ReplyError::Untyped(untyped) => {
                write!(formatter, "the host refused the reply: {}", untyped.said)
            }
            ReplyError::Ended { socket, key } => write!(
                formatter,
                "the host refused the reply: the host at {} ended the connection without an ack: \
                 it does not hold run {}, the run never made call {}, the run's program cannot \
                 be formed, or it takes no replies of data version {}",
                socket.display(),
                key.run(),
                key.call(),
                DATA_VERSION
            ),
        }
    }
}

impl std::error::Error for ReplyError {}

/// A frame a host owes a reply: the call's result type, then the `ack`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "a reply's exchange owes these two frames, as the protocol has them"
)]
pub enum ReplyStep {
    /// The `type` (11) answering the reply's `type` (10).
    Type,
    /// The `ack` (7) answering the reply's `reply` (4).
    Ack,
}

impl From<KeyError> for ReplyError {
    fn from(error: KeyError) -> Self {
        ReplyError::Key(error)
    }
}

/// Answers the open call `key` names with `answer`, and returns what the host
/// did with it: [`Ack::Ok`] when the answer is recorded,
/// [`Ack::AlreadyAnswered`] when the call was not open, with `same` true if
/// its answer equals this one, and [`Ack::TypeError`] when the answer does
/// not have the call's type. The last two record nothing and do not stop the
/// run.
///
/// It goes to the host whose socket `FLOW_REPLY_SOCKET` names; with that
/// variable unset or empty it reaches no host. [`reply_at`] names the socket
/// instead. While a [`testing::replies`] capture is alive, the reply is
/// recorded there instead and nothing reaches a host.
///
/// # Errors
///
/// A `key` that is not a key's text form is refused before anything is
/// sent, and a value that is not one of the
/// call's result type, [`ReplyError::Mistyped`], before the reply is sent.
/// No `FLOW_REPLY_SOCKET` is [`ReplyError::NoSocket`], a socket that
/// fails [`ReplyError::Socket`], and a host that answers out of turn
/// [`ReplyError::Answered`]. A host that has no result type for the call,
/// such as one that does not hold its run, is [`ReplyError::Untyped`], and
/// one that ends the connection before its `ack` is [`ReplyError::Ended`].
///
/// An answer is a value or a problem:
///
/// ```no_run
/// use flow_toolkit::{CallKey, ToolProblem, reply};
/// let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
/// reply(&key, Ok("approved".to_owned()))?;
/// reply(&key, Err::<String, _>(ToolProblem::Interrupted("withdrawn".into())))?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// A hold is no answer, so it does not compile:
///
/// ```compile_fail,E0308
/// use flow_toolkit::{CallKey, Hold, reply};
/// let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
/// reply(&key, Err::<String, _>(Hold::new()))?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[expect(
    clippy::needless_pass_by_value,
    reason = "an answer is handed over to be sent once, as a Tool returns one"
)]
pub fn reply(
    key: &(impl ToCallKey + ?Sized),
    answer: Result<impl Shaped + Debug, ToolProblem>,
) -> Result<Ack, ReplyError> {
    let socket = std::env::var_os("FLOW_REPLY_SOCKET").filter(|path| !path.is_empty());
    deliver(socket.as_deref().map(Path::new), key, &answer)
}

/// Answers the open call `key` names with `answer` as [`reply`] does, over
/// the Unix-domain socket at `socket`, where the host that holds the run
/// takes replies; `FLOW_REPLY_SOCKET` is not read.
///
/// # Errors
///
/// As [`reply`]'s, a host that cannot be reached at `socket` included.
#[expect(
    clippy::needless_pass_by_value,
    reason = "an answer is handed over to be sent once, as a Tool returns one"
)]
pub fn reply_at(
    socket: impl AsRef<Path>,
    key: &(impl ToCallKey + ?Sized),
    answer: Result<impl Shaped + Debug, ToolProblem>,
) -> Result<Ack, ReplyError> {
    deliver(Some(socket.as_ref()), key, &answer)
}

/// Sends `answer` to the call `key` names, over `socket`, unless a capture
/// takes it; with no socket there is no host to send it to.
fn deliver(
    socket: Option<&Path>,
    key: &(impl ToCallKey + ?Sized),
    answer: &Result<impl Shaped + Debug, ToolProblem>,
) -> Result<Ack, ReplyError> {
    let key = key.to_call_key()?;
    if let Some(ack) = testing::capture(&key, answer) {
        return Ok(ack);
    }
    let socket = socket.ok_or(ReplyError::NoSocket)?;
    send_to(socket, &key, answer, ANSWER)
}

/// How long `reply` waits on the host's socket, for each write of its
/// frames and for the `ack`.
const ANSWER: std::time::Duration = std::time::Duration::from_secs(60);

/// The largest frame read from the host: a `type` answer, a key and the
/// result type's description or a reason, or an `ack`, a key and a type
/// error's reason.
#[cfg(unix)]
const ANSWER_LIMIT: usize = 1 << 20;

/// Sends `answer` to the call `key` names, over the socket at `socket`
/// where the host takes replies. A host that does not answer there is
/// unreachable; nothing else is tried. The reply socket is a Unix socket,
/// so elsewhere every host is unreachable.
fn send_to(
    socket: &Path,
    key: &CallKey,
    answer: &Result<impl Shaped + Debug, ToolProblem>,
    within: std::time::Duration,
) -> Result<Ack, ReplyError> {
    #[cfg(unix)]
    {
        let stream =
            flow_start::unix::connect(socket).map_err(|error| socket_error(socket, error))?;
        over(stream, socket, key, answer, within)
    }
    #[cfg(not(unix))]
    {
        let _ = (socket, key, answer, within);
        Err(socket_error(socket, ErrorKind::Unsupported.into()))
    }
}

/// The exchange over `stream`, a connection to the host at `socket`, with
/// each write and the wait for the `ack` bounded by `within`.
#[cfg(unix)]
fn over(
    stream: std::os::unix::net::UnixStream,
    socket: &Path,
    key: &CallKey,
    answer: &Result<impl Shaped + Debug, ToolProblem>,
    within: std::time::Duration,
) -> Result<Ack, ReplyError> {
    stream
        .set_read_timeout(Some(within))
        .and_then(|()| stream.set_write_timeout(Some(within)))
        .map_err(|error| {
            // Darwin refuses socket options with EINVAL or ENOTCONN once
            // the peer has shut the connection: the host ended it before
            // reading.
            if cfg!(target_vendor = "apple")
                && (error.raw_os_error() == Some(rustix::io::Errno::INVAL.raw_os_error())
                    || error.kind() == ErrorKind::NotConnected)
            {
                ended(socket, key)
            } else {
                socket_error(socket, error)
            }
        })?;
    let mut stream = Quiet::new(stream);
    exchange(&mut stream, socket, key, answer)
}

/// A connection to the host whose writes never raise SIGPIPE.
///
/// A write to a socket whose peer has closed raises SIGPIPE, and a process
/// whose SIGPIPE has its default disposition dies of it. Rust's runtime
/// ignores SIGPIPE, but a library cannot count on its host program keeping
/// it so, so each write asks the kernel not to raise the signal: with
/// `MSG_NOSIGNAL` where `send` takes it, and on Apple's systems, which lack
/// that flag, with `SO_NOSIGPIPE` set on the socket before the first write.
/// A closed host is then the broken pipe `exchange` reports.
#[cfg(unix)]
struct Quiet {
    stream: std::os::unix::net::UnixStream,
    #[cfg(target_vendor = "apple")]
    nosigpipe: bool,
}

#[cfg(unix)]
impl Quiet {
    fn new(stream: std::os::unix::net::UnixStream) -> Self {
        Self {
            stream,
            #[cfg(target_vendor = "apple")]
            nosigpipe: false,
        }
    }
}

#[cfg(unix)]
impl Read for Quiet {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.stream.read(buf)
    }
}

#[cfg(unix)]
impl Write for Quiet {
    #[cfg(target_vendor = "apple")]
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        use rustix::io::Errno;
        if !self.nosigpipe {
            // Darwin refuses socket options with EINVAL once the peer has
            // shut the connection, which is the closed host a write would
            // meet as a broken pipe, so it is reported as one.
            let set = rustix::net::sockopt::set_socket_nosigpipe(&self.stream, true);
            set.map_err(|e| if e == Errno::INVAL { Errno::PIPE } else { e })?;
            self.nosigpipe = true;
        }
        Ok(rustix::net::send(
            &self.stream,
            buf,
            rustix::net::SendFlags::empty(),
        )?)
    }
    #[cfg(not(target_vendor = "apple"))]
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        Ok(rustix::net::send(
            &self.stream,
            buf,
            rustix::net::SendFlags::NOSIGNAL,
        )?)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// The refusal of the host at `socket` that ended the connection before it
/// acked the reply to `key`.
#[cfg(unix)]
fn ended(socket: &Path, key: &CallKey) -> ReplyError {
    ReplyError::Ended {
        socket: socket.to_owned(),
        key: Box::new(key.clone()),
    }
}

/// A failure of the host's socket other than the host ending the
/// connection, such as a write or read that passed its bound.
fn socket_error(socket: &Path, error: std::io::Error) -> ReplyError {
    ReplyError::Socket {
        socket: socket.to_owned(),
        error,
    }
}

/// The `reply` frame that carries `answer` to the call `key` names: an `Ok`
/// answer is the value in the value encoding at the call's result type,
/// `types`, as the host said it.
#[cfg(unix)]
fn reply_frame(
    key: &CallKey,
    answer: &Result<impl Shaped + Debug, ToolProblem>,
    types: &ResultType,
) -> Result<Message, ReplyError> {
    let outcome = match answer {
        Ok(value) => {
            let mut bytes = Vec::new();
            flow_abi::write_shaped(&mut bytes, types.catalog(), types.result(), value)
                .map_err(|error| ReplyError::Mistyped(refused(error.problem)))?;
            Outcome::Ok(flow_abi::wire::Rest(bytes))
        }
        Err(problem) => problem.clone().into(),
    };
    Ok(Message::Reply(flow_tool_protocol::Reply {
        run: *key.run(),
        call: key.call().clone(),
        outcome,
    }))
}

/// The exchange over a connection to the host at `socket`: this client's data version as
/// `describe` carries it, the `type` asked of the call `key` names and the
/// host's answer, then the `reply` written at that type and the `ack` that
/// answers it.
#[cfg(unix)]
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "std's io::ErrorKind and flow-abi's Message are foreign; any other kind or frame is the error"
)]
fn exchange(
    stream: &mut (impl Read + Write),
    socket: &Path,
    key: &CallKey,
    answer: &Result<impl Shaped + Debug, ToolProblem>,
) -> Result<Ack, ReplyError> {
    let describe = Message::Describe {
        version: DATA_VERSION,
        reply_limit: 0,
    };
    let broken = |error: std::io::Error| match error.kind() {
        ErrorKind::BrokenPipe
        | ErrorKind::ConnectionReset
        | ErrorKind::NotConnected
        | ErrorKind::UnexpectedEof => ended(socket, key),
        _ => socket_error(socket, error),
    };
    let ask = Message::Type {
        run: *key.run(),
        call: key.call().clone(),
    };
    flow_tool_protocol::write_frame(stream, &describe).map_err(broken)?;
    flow_tool_protocol::write_frame(stream, &ask).map_err(broken)?;
    let types = match answered(stream, socket, key, ReplyStep::Type)? {
        Message::Typed { run, call, answer } if &run == key.run() && &call == key.call() => {
            answer.map_err(ReplyError::Untyped)?
        }
        _ => return Err(out_of_turn(socket, ReplyStep::Type)),
    };
    let reply = reply_frame(key, answer, &types)?;
    flow_tool_protocol::write_frame(stream, &reply).map_err(broken)?;
    match answered(stream, socket, key, ReplyStep::Ack)? {
        Message::Ack { run, call, result } if &run == key.run() && &call == key.call() => {
            Ok(result)
        }
        _ => Err(out_of_turn(socket, ReplyStep::Ack)),
    }
}

/// The refusal of a host at `socket` that sent something other than the
/// `expected` frame.
#[cfg(unix)]
fn out_of_turn(socket: &Path, expected: ReplyStep) -> ReplyError {
    ReplyError::Answered {
        socket: socket.to_owned(),
        expected,
    }
}

/// The next frame the host sends over `stream`, a connection to the host at
/// `socket` about the call `key` names, read as the `expected` frame.
#[cfg(unix)]
#[expect(
    clippy::wildcard_enum_match_arm,
    reason = "io::ErrorKind is std's; any other kind is a failure of the socket"
)]
fn answered(
    stream: &mut impl Read,
    socket: &Path,
    key: &CallKey,
    expected: ReplyStep,
) -> Result<Message, ReplyError> {
    let body = match flow_tool_protocol::read_frame(stream, ANSWER_LIMIT) {
        Ok(None) => return Err(ended(socket, key)),
        Ok(Some(Frame::Body(body))) => body,
        Ok(Some(Frame::TooLarge { .. })) => return Err(out_of_turn(socket, expected)),
        Err(error) => {
            return Err(match error.kind() {
                ErrorKind::ConnectionReset | ErrorKind::UnexpectedEof => ended(socket, key),
                _ => socket_error(socket, error),
            });
        }
    };
    Message::parse(Route::Socket, &body).map_err(|_| out_of_turn(socket, expected))
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
#[cfg(unix)]
mod tests {
    use std::os::unix::net::UnixStream;
    use std::time::{Duration, Instant};

    use super::*;
    use flow_abi::Json;

    use crate::data::LIMITS;
    use crate::{Int, NoType};

    const RUN: &str = "7f3a91c04be2d5e6f708192a3b4c5d6e";

    fn key() -> CallKey {
        CallKey::new(
            flow_span::RunId::parse(RUN).unwrap(),
            flow_span::CallRef::parse("root#1").unwrap(),
        )
    }

    /// `toolkits/conformance/reply.json`'s frames.
    fn frames() -> Json {
        let json = flow_abi::parse(include_str!("../../conformance/reply.json"), &LIMITS).unwrap();
        json.get("frames").unwrap().clone()
    }

    /// The string member `key` of `case`, when it has one.
    fn text(case: &Json, key: &str) -> Option<String> {
        let member = case.get(key)?;
        let Json::String(text) = member else {
            panic!("{key} is {}", member.kind());
        };
        Some(text.clone())
    }

    /// The boolean member `key` of `case`, when it has one.
    fn flag(case: &Json, key: &str) -> Option<bool> {
        let member = case.get(key)?;
        let Json::Bool(flag) = member else {
            panic!("{key} is {}", member.kind());
        };
        Some(*flag)
    }

    /// The array member `key` of `json`.
    fn cases<'j>(json: &'j Json, key: &str) -> &'j [Json] {
        match json.get(key) {
            Some(Json::Array(cases)) => cases,
            other => panic!("{key} is {other:?}"),
        }
    }

    fn hex(bytes: &[u8]) -> String {
        use std::fmt::Write as _;
        bytes.iter().fold(String::new(), |mut hex, byte| {
            let _ = write!(hex, "{byte:02x}");
            hex
        })
    }

    fn unhex(text: &str) -> Vec<u8> {
        (0..text.len())
            .step_by(2)
            .map(|at| u8::from_str_radix(&text[at..at + 2], 16).unwrap())
            .collect()
    }

    #[test]
    fn the_frames_are_the_shared_vectors() {
        let frames = frames();
        let describe = Message::Describe {
            version: DATA_VERSION,
            reply_limit: 0,
        };
        assert_eq!(Some(hex(&describe.frame())), text(&frames, "describe"));
        assert_eq!(Some(hex(&asked().frame())), text(&frames, "asked"));
        for case in cases(&frames, "typed") {
            let frame = text(case, "frame").unwrap();
            let answer = match (text(case, "result_type"), case.get("refused")) {
                (Some(types), None) => Ok(ResultType::read(&unhex(&types)).unwrap()),
                (None, Some(refused)) => Err(Untyped {
                    reason: flow_abi::wire::Wire::decode(&[match refused.get("reason") {
                        Some(Json::Number(reason)) => reason.to_string().parse().unwrap(),
                        other => panic!("reason is {other:?}"),
                    }])
                    .unwrap(),
                    said: text(refused, "said").unwrap(),
                }),
                other => panic!("{other:?}"),
            };
            if let Ok(types) = &answer {
                assert_eq!(types.result(), &flow_types::Type::Text);
            }
            let typed = typed("root#1", answer);
            assert_eq!(hex(&typed.frame()), frame);
            assert_eq!(
                Message::parse(Route::Socket, &unhex(&frame)[1..]).unwrap(),
                typed
            );
        }
        for case in cases(&frames, "replies") {
            let answer = case.get("answer").unwrap();
            let answer = match (text(answer, "Ok"), answer.get("Err")) {
                (Some(value), None) => Ok(value),
                (None, Some(problem)) => Err(
                    match (
                        text(problem, "NotStarted"),
                        text(problem, "Interrupted"),
                        problem.get("NetworkError"),
                    ) {
                        (Some(reason), None, None) => ToolProblem::NotStarted(reason),
                        (None, Some(reason), None) => ToolProblem::Interrupted(reason),
                        (None, None, Some(failed)) => ToolProblem::NetworkError {
                            sent: flag(failed, "sent").unwrap(),
                            reason: text(failed, "reason").unwrap(),
                        },
                        other => panic!("{other:?}"),
                    },
                ),
                other => panic!("{other:?}"),
            };
            let frame = reply_frame(&key(), &answer, &text_type()).unwrap().frame();
            assert_eq!(Some(hex(&frame)), text(case, "frame"));
        }
        for case in cases(&frames, "acks") {
            let frame = text(case, "frame").unwrap();
            let result = match (
                flag(case, "ok"),
                flag(case, "same"),
                text(case, "type_error"),
            ) {
                (Some(true), _, _) => Ack::Ok,
                (_, Some(same), _) => Ack::AlreadyAnswered { same },
                (_, _, reason) => Ack::TypeError(reason.unwrap()),
            };
            assert_eq!(
                flag(case, "already_answered").is_some(),
                matches!(result, Ack::AlreadyAnswered { .. })
            );
            let ack = Message::Ack {
                run: flow_span::RunId::parse(RUN).unwrap(),
                call: flow_span::CallRef::parse("root#1").unwrap(),
                result,
            };
            assert_eq!(hex(&ack.frame()), frame);
            // Each is shorter than 128 bytes: its length is its first byte.
            let bytes = unhex(&frame);
            assert_eq!(usize::from(bytes[0]), bytes.len() - 1);
            assert_eq!(Message::parse(Route::Socket, &bytes[1..]).unwrap(), ack);
        }
    }

    /// The result type `Text`, as a host describes it.
    fn text_type() -> ResultType {
        ResultType::read(&[3, 0]).unwrap()
    }

    /// The `type` asked of the call `key` names.
    fn asked() -> Message {
        Message::Type {
            run: *key().run(),
            call: key().call().clone(),
        }
    }

    /// The host's answer to a `type` asked of `call`.
    fn typed(call: &str, answer: Result<ResultType, Untyped>) -> Message {
        Message::Typed {
            run: flow_span::RunId::parse(RUN).unwrap(),
            call: flow_span::CallRef::parse(call).unwrap(),
            answer,
        }
    }

    /// What a host reads of the exchange up to the reply of `sent` at
    /// `Text`: describe, the type asked, and the reply.
    fn exchanged(sent: &Result<String, ToolProblem>) -> (Vec<u8>, Vec<u8>) {
        let describe = Message::Describe {
            version: DATA_VERSION,
            reply_limit: 0,
        };
        let reply = reply_frame(&key(), sent, &text_type()).unwrap();
        ([describe.frame(), asked().frame()].concat(), reply.frame())
    }

    /// The host's end of the exchange over `host`: it reads describe and
    /// the type asked, answers that the result type is `Text`, reads the
    /// reply of `sent` and then answers as `answer` says.
    fn serve(
        host: &mut UnixStream,
        sent: &Result<String, ToolProblem>,
        answer: impl FnOnce(&mut UnixStream),
    ) {
        let (opening, reply) = exchanged(sent);
        let mut read = vec![0; opening.len()];
        host.read_exact(&mut read).unwrap();
        assert_eq!(read, opening, "describe, then the type asked");
        flow_tool_protocol::write_frame(host, &typed("root#1", Ok(text_type()))).unwrap();
        let mut read = vec![0; reply.len()];
        host.read_exact(&mut read).unwrap();
        assert_eq!(read, reply, "then the reply");
        answer(host);
    }

    /// A host on the other end of a socket pair: it serves the exchange
    /// and answers the reply as `answer` says.
    fn against(
        answer: impl FnOnce(&mut UnixStream) + Send + 'static,
        sent: &Result<String, ToolProblem>,
    ) -> Result<Ack, ReplyError> {
        let (mut client, mut daemon) = flow_start::unix::pair().unwrap();
        let served = sent.clone();
        let serving = std::thread::spawn(move || serve(&mut daemon, &served, answer));
        let acked = exchange(&mut client, Path::new("/h/reply.sock"), &key(), sent);
        serving.join().unwrap();
        acked
    }

    /// A host that answers the type asked with `answer` and then reads
    /// nothing more.
    fn typed_as(
        answer: Vec<u8>,
        sent: &Result<impl Shaped + Debug, ToolProblem>,
    ) -> Result<Ack, ReplyError> {
        let (mut client, mut daemon) = flow_start::unix::pair().unwrap();
        let serving = std::thread::spawn(move || {
            let (opening, _) = exchanged(&Ok(String::new()));
            let mut read = vec![0; opening.len()];
            daemon.read_exact(&mut read).unwrap();
            daemon.write_all(&answer).unwrap();
            daemon
        });
        let acked = exchange(&mut client, Path::new("/h/reply.sock"), &key(), sent);
        drop(serving.join().unwrap());
        acked
    }

    #[test]
    fn a_type_the_host_refuses_or_does_not_give_sends_no_reply() {
        let untyped = Untyped {
            reason: NoType::NoSuchCall,
            said: "the run made no call root#1".into(),
        };
        let refused = typed_as(
            typed("root#1", Err(untyped.clone())).frame(),
            &Ok(String::new()),
        );
        assert!(
            matches!(&refused, Err(ReplyError::Untyped(said)) if *said == untyped),
            "{refused:?}"
        );
        let other_call = typed_as(typed("root#2", Ok(text_type())).frame(), &Ok(String::new()));
        assert!(
            matches!(
                &other_call,
                Err(ReplyError::Answered {
                    expected: ReplyStep::Type,
                    ..
                })
            ),
            "{other_call:?}"
        );
        let garbage = typed_as(vec![2, 99, 0], &Ok(String::new()));
        assert!(
            matches!(
                &garbage,
                Err(ReplyError::Answered {
                    expected: ReplyStep::Type,
                    ..
                })
            ),
            "{garbage:?}"
        );
        let mut huge = Vec::new();
        flow_abi::primitives::write_bytes(&mut huge, &vec![7; ANSWER_LIMIT + 1]);
        let too_large = typed_as(huge, &Ok(String::new()));
        assert!(
            matches!(
                &too_large,
                Err(ReplyError::Answered {
                    expected: ReplyStep::Type,
                    ..
                })
            ),
            "{too_large:?}"
        );
        let mistyped = typed_as(typed("root#1", Ok(text_type())).frame(), &Ok(Int::from(2)));
        assert!(
            matches!(&mistyped, Err(ReplyError::Mistyped(_))),
            "{mistyped:?}"
        );
        assert!(
            mistyped
                .unwrap_err()
                .to_string()
                .starts_with("the reply is not a value of the call's type: ")
        );
    }

    fn ack(call: &str, result: Ack) -> Message {
        Message::Ack {
            run: flow_span::RunId::parse(RUN).unwrap(),
            call: flow_span::CallRef::parse(call).unwrap(),
            result,
        }
    }

    #[test]
    fn each_ack_the_daemon_sends_comes_back() {
        for result in [
            Ack::Ok,
            Ack::AlreadyAnswered { same: true },
            Ack::AlreadyAnswered { same: false },
            Ack::TypeError("not Text".into()),
        ] {
            let expected = result.clone();
            let acked = against(
                move |daemon| {
                    flow_tool_protocol::write_frame(daemon, &ack("root#1", result)).unwrap();
                },
                &Ok("yes".to_owned()),
            );
            assert!(matches!(&acked, Ok(ack) if *ack == expected), "{acked:?}");
        }
    }

    #[test]
    fn a_connection_that_ends_without_an_ack_is_refused_naming_the_host_run_and_call() {
        let refused = against(|_| {}, &Ok(String::new()));
        assert!(
            matches!(&refused, Err(ReplyError::Ended { socket, key: ended })
                if *socket == Path::new("/h/reply.sock") && **ended == key()),
            "{refused:?}"
        );
    }

    #[test]
    fn a_connection_the_daemon_already_closed_is_refused() {
        let (client, daemon) = flow_start::unix::pair().unwrap();
        drop(daemon);
        let mut client = Quiet::new(client);
        let refused = exchange(
            &mut client,
            Path::new("/h/reply.sock"),
            &key(),
            &Ok(String::new()),
        );
        assert!(
            matches!(&refused, Err(ReplyError::Ended { .. })),
            "{refused:?}"
        );
    }

    /// A host program may give SIGPIPE its default, terminating disposition;
    /// a reply to a daemon that already closed is still an error to it.
    #[test]
    fn a_closed_daemon_is_refused_even_where_sigpipe_would_end_the_process() {
        use flow_start::Spawn as _;
        use flow_testing::{Rerun, rerun};
        let Rerun::Parent(mut command) =
            rerun(a_closed_daemon_is_refused_even_where_sigpipe_would_end_the_process)
        else {
            // std gives SIGPIPE its default disposition just before `execvp`
            // and keeps it when `execvp` refuses, as it refuses an argument
            // longer than any system's limit.
            let refused = std::process::Command::new("/bin/sh")
                .arg("x".repeat(16 << 20))
                .locked_exec();
            assert_eq!(
                refused.raw_os_error(),
                Some(rustix::io::Errno::TOOBIG.raw_os_error()),
                "{refused}"
            );
            let (client, daemon) = flow_start::unix::pair().unwrap();
            drop(daemon);
            let mut client = Quiet::new(client);
            let refused = exchange(
                &mut client,
                Path::new("/h/reply.sock"),
                &key(),
                &Ok(String::new()),
            );
            assert!(
                matches!(refused, Err(ReplyError::Ended { .. })),
                "{refused:?}"
            );
            return;
        };
        let output = command.locked_output().expect("the test binary runs again");
        assert!(output.status.success(), "{output:?}");
    }

    #[test]
    fn a_daemon_of_another_data_version_ends_the_connection_and_the_error_names_the_version() {
        let refused = against(
            |daemon| daemon.shutdown(std::net::Shutdown::Both).unwrap(),
            &Err(ToolProblem::NotStarted("no".into())),
        );
        let version = format!("data version {DATA_VERSION}");
        assert!(
            matches!(&refused, Err(ReplyError::Ended { .. })),
            "{refused:?}"
        );
        assert!(refused.unwrap_err().to_string().contains(&version));
    }

    #[test]
    fn an_answer_that_is_not_the_reply_s_ack_is_no_answer() {
        let other_call = against(
            |daemon| {
                flow_tool_protocol::write_frame(daemon, &ack("root#2", Ack::Ok)).unwrap();
            },
            &Ok(String::new()),
        );
        assert!(
            matches!(
                &other_call,
                Err(ReplyError::Answered {
                    expected: ReplyStep::Ack,
                    ..
                })
            ),
            "{other_call:?}"
        );
        let too_large = against(
            |daemon| {
                let mut frame = Vec::new();
                flow_abi::primitives::write_bytes(&mut frame, &vec![7; ANSWER_LIMIT + 1]);
                daemon.write_all(&frame).unwrap();
            },
            &Ok(String::new()),
        );
        assert!(
            matches!(
                &too_large,
                Err(ReplyError::Answered {
                    expected: ReplyStep::Ack,
                    ..
                })
            ),
            "{too_large:?}"
        );
    }

    /// A host that accepts the connection and never answers: the wait for
    /// the type asked stops at its bound, as an error.
    #[test]
    fn a_host_that_stops_reading_cannot_hold_a_reply_forever() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("reply.sock");
        let listener = flow_start::unix::bind(&path).unwrap();
        let (done, held) = std::sync::mpsc::channel::<()>();
        let accepting = std::thread::spawn(move || {
            let stream = flow_testing::accepted(&listener);
            // Holds the connection open, unread, until the client is done.
            let _ = held.recv();
            drop(stream);
        });
        let begun = Instant::now();
        let stuck = send_to(
            &path,
            &key(),
            &Ok("x".to_owned()),
            Duration::from_millis(300),
        );
        let took = begun.elapsed();
        done.send(()).unwrap();
        accepting.join().unwrap();
        assert!(
            matches!(&stuck, Err(ReplyError::Socket { error, .. })
                if matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)),
            "{stuck:?}"
        );
        assert!(took < Duration::from_secs(10), "{took:?}");
    }

    /// A host that ended the connection before the reply was sent refused
    /// it, even where the closed socket refuses its options too.
    #[test]
    fn a_connection_the_host_already_ended_is_refused() {
        let (stream, host) = flow_start::unix::pair().unwrap();
        drop(host);
        let path = Path::new("reply.sock");
        let refused = over(stream, path, &key(), &Ok("yes".to_owned()), ANSWER);
        assert!(
            matches!(&refused, Err(ReplyError::Ended { .. })),
            "{refused:?}"
        );
    }

    /// The reply goes to the host listening on the socket it is given, and a
    /// socket nobody answers on is unreachable: nothing else is tried.
    #[test]
    fn a_reply_socket_takes_the_reply_and_one_nobody_answers_is_unreachable() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("reply.sock");
        let gone = reply_at(&path, &key(), Ok("yes".to_owned()));
        assert!(
            matches!(&gone, Err(ReplyError::Socket { socket, error })
                if *socket == path && error.kind() == std::io::ErrorKind::NotFound),
            "{gone:?}"
        );
        let listener = flow_start::unix::bind(&path).unwrap();
        let serving = std::thread::spawn(move || {
            let mut host = flow_testing::accepted(&listener);
            serve(&mut host, &Ok("yes".to_owned()), |host| {
                flow_tool_protocol::write_frame(host, &ack("root#1", Ack::Ok)).unwrap();
            });
            let host = flow_testing::accepted(&listener);
            drop(host);
        });
        let acked = reply_at(&path, &key(), Ok("yes".to_owned()));
        assert!(matches!(acked, Ok(Ack::Ok)), "{acked:?}");
        let refused = send_to(&path, &key(), &Ok("yes".to_owned()), ANSWER);
        serving.join().unwrap();
        assert!(
            matches!(&refused, Err(ReplyError::Ended { socket, .. }) if *socket == path),
            "{refused:?}"
        );
    }

    /// With no socket to send to, a reply reaches no host, and the error
    /// names `FLOW_REPLY_SOCKET`; a capture still takes it.
    #[test]
    fn with_no_reply_socket_a_reply_reaches_no_host_and_says_so() {
        let unsent = deliver(None, &key(), &Ok("yes".to_owned()));
        assert!(matches!(&unsent, Err(ReplyError::NoSocket)), "{unsent:?}");
        let captured = testing::replies();
        let taken = deliver(None, &key(), &Ok("yes".to_owned()));
        assert!(matches!(taken, Ok(Ack::Ok)), "{taken:?}");
        assert_eq!(captured.sent().len(), 1);
    }

    #[test]
    fn reply_errors_say_what_happened() {
        assert_eq!(
            ReplyError::from("x".parse::<CallKey>().unwrap_err()).to_string(),
            "\"x\" is not a call's key: the run's id, '/', then the call's id"
        );
        assert!(
            ReplyError::NoSocket
                .to_string()
                .starts_with("the host was not reached: FLOW_REPLY_SOCKET is not set")
        );
        assert_eq!(
            ReplyError::Socket {
                socket: "reply.sock".into(),
                error: std::io::ErrorKind::NotFound.into(),
            }
            .to_string(),
            "the host was not reached: the reply socket reply.sock: entity not found"
        );
        assert_eq!(
            ReplyError::Answered {
                socket: "reply.sock".into(),
                expected: ReplyStep::Ack,
            }
            .to_string(),
            "the host was not reached: the host at reply.sock did not answer with the reply's ack"
        );
        assert_eq!(
            ReplyError::Untyped(Untyped {
                reason: NoType::UnknownRun,
                said: "no run".into(),
            })
            .to_string(),
            "the host refused the reply: no run"
        );
    }
}

/// Testing Tools and [`reply`] natively, without a host.
///
/// A Tool function is an ordinary function: a test calls it with
/// [`Context::for_test`](crate::Context::for_test) and checks what it
/// returns, a [`Hold`](crate::Hold) included. [`replies`](testing::replies) captures the replies
/// [`reply`] sends while it is alive, so a test can drive a held call and
/// the webhook that answers it in one process.
pub mod testing {
    use std::sync::{Mutex, MutexGuard, PoisonError};

    use std::fmt::Debug;

    use flow_abi::Ack;

    use crate::key::CallKey;
    use crate::server::ToolProblem;

    /// One reply [`reply`](crate::reply()) sent while a capture was alive.
    #[derive(Clone, PartialEq, Eq, Debug)]
    #[non_exhaustive]
    pub struct Sent {
        /// The call it answers.
        pub key: CallKey,
        /// The value, as its `Debug` text writes it, or the problem.
        pub answer: Result<String, ToolProblem>,
    }

    /// The replies sent while it is alive, which reach no host. Each is
    /// acked as a host that holds every call open would ack it: `ok` for a
    /// key's first reply, then `already answered`, with `same` true when the
    /// answer is the same value as the first. It checks no types.
    ///
    /// Captures are taken one at a time across the process: a second waits
    /// until the first is dropped.
    #[derive(Debug)]
    pub struct Replies {
        _turn: MutexGuard<'static, ()>,
    }

    impl Replies {
        /// The replies sent so far, in the order they were sent.
        pub fn sent(&self) -> Vec<Sent> {
            lock(&CAPTURED).clone().unwrap_or_default()
        }
    }

    impl Drop for Replies {
        fn drop(&mut self) {
            *lock(&CAPTURED) = None;
        }
    }

    /// Starts capturing replies; they reach no host until it is dropped.
    pub fn replies() -> Replies {
        let turn = TURN.lock().unwrap_or_else(PoisonError::into_inner);
        *lock(&CAPTURED) = Some(Vec::new());
        Replies { _turn: turn }
    }

    /// One capture at a time.
    static TURN: Mutex<()> = Mutex::new(());
    /// The replies captured, while a capture is alive.
    static CAPTURED: Mutex<Option<Vec<Sent>>> = Mutex::new(None);

    fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
        mutex.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Records a reply when a capture is alive, and acks it.
    pub(crate) fn capture(key: &CallKey, answer: &Result<impl Debug, ToolProblem>) -> Option<Ack> {
        let mut captured = lock(&CAPTURED);
        let sent = captured.as_mut()?;
        let answer = match answer {
            Ok(value) => Ok(format!("{value:?}")),
            Err(problem) => Err(problem.clone()),
        };
        let ack = match sent.iter().find(|earlier| earlier.key == *key) {
            Some(first) => Ack::AlreadyAnswered {
                same: first.answer == answer,
            },
            None => Ack::Ok,
        };
        sent.push(Sent {
            key: key.clone(),
            answer,
        });
        Some(ack)
    }
}