Skip to main content

flow_toolkit/
reply.rs

1//! Answering an open call from outside it (`abi.md`, *Toolkits* and
2//! *Replies from outside a call*).
3//!
4//! [`reply`] answers the call a [`CallKey`] names from anywhere: a webhook
5//! receiver, a script, another Tool, with an answer: `Ok` with a value of
6//! the call's result type, or `Err` with a [`ToolProblem`]. A hold is no
7//! answer, so it has no way to be sent. It returns once the
8//! host has committed or refused the reply, with the [`Ack`] every route
9//! that offers an answer gets.
10//!
11//! The reply reaches the host as a client outside any Tool process: it sends
12//! its data version as `describe` (1) carries it, asks the call's result
13//! type with `type` (10) and reads the host's `type` (11), then sends one
14//! `reply` (4) frame whose `Ok` answer is the value in the value encoding at
15//! that type, and reads the `ack` (7). It connects to the Unix-domain socket
16//! where the host that holds the run takes such clients: the one
17//! [`reply_at`] is given, or for [`reply`] the one `FLOW_REPLY_SOCKET`
18//! names, which a host sets for the implementations it starts. With neither
19//! there is no host to reply to, and nothing else is looked for.
20
21use std::io::ErrorKind;
22#[cfg(unix)]
23use std::io::{Read, Write};
24use std::path::{Path, PathBuf};
25
26use flow_abi::{Ack, DATA_VERSION, Untyped};
27#[cfg(unix)]
28use flow_abi::{Outcome, ResultType};
29#[cfg(unix)]
30use flow_tool_protocol::{Frame, Message, Route};
31
32use std::fmt::Debug;
33
34use flow_abi::wire::Shaped;
35
36use crate::data::DecodeError;
37#[cfg(unix)]
38use crate::data::refused;
39use crate::key::{CallKey, KeyError};
40use crate::server::ToolProblem;
41
42/// What can name a call for [`reply`]: a [`CallKey`], or its text form.
43pub trait ToCallKey {
44    /// The key.
45    ///
46    /// # Errors
47    ///
48    /// Text that is not a key's text form.
49    fn to_call_key(&self) -> Result<CallKey, KeyError>;
50}
51
52impl ToCallKey for CallKey {
53    fn to_call_key(&self) -> Result<CallKey, KeyError> {
54        Ok(self.clone())
55    }
56}
57
58impl ToCallKey for str {
59    fn to_call_key(&self) -> Result<CallKey, KeyError> {
60        self.parse()
61    }
62}
63
64impl ToCallKey for String {
65    fn to_call_key(&self) -> Result<CallKey, KeyError> {
66        self.parse()
67    }
68}
69
70/// Why [`reply`] has no [`Ack`]: nothing was sent, or the host was not
71/// reached or does not hold the call's run.
72#[derive(Debug)]
73#[non_exhaustive]
74pub enum ReplyError {
75    /// The text given is not a key's text form; nothing was sent.
76    Key(KeyError),
77    /// The value is not one of the call's result type, and why; no reply
78    /// was sent.
79    Mistyped(DecodeError),
80    /// No socket was given and `FLOW_REPLY_SOCKET` names none, so there is
81    /// no host to send to; nothing was sent.
82    NoSocket,
83    /// The host's socket at `socket` failed: no host answers there, or the
84    /// connection failed while the reply was under way.
85    Socket {
86        /// The host's socket.
87        socket: PathBuf,
88        /// What the system said.
89        error: std::io::Error,
90    },
91    /// The host at `socket` sent something other than the `expected` frame
92    /// about the reply's call.
93    Answered {
94        /// The host's socket.
95        socket: PathBuf,
96        /// The frame the host owed.
97        expected: ReplyStep,
98    },
99    /// The host has no result type for the call, and says why; no reply was
100    /// sent.
101    Untyped(Untyped),
102    /// The host at `socket` ended the connection before it acked the reply to
103    /// `key`: it does not hold the run, the run never made the call, the run's
104    /// program cannot be formed, or it takes no replies of this data version.
105    /// Nothing was recorded.
106    Ended {
107        /// The host's socket.
108        socket: PathBuf,
109        /// The call the reply answers.
110        key: Box<CallKey>,
111    },
112}
113
114impl std::fmt::Display for ReplyError {
115    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            ReplyError::Key(error) => write!(formatter, "{error}"),
118            ReplyError::Mistyped(error) => {
119                write!(
120                    formatter,
121                    "the reply is not a value of the call's type: {error}"
122                )
123            }
124            ReplyError::NoSocket => formatter.write_str(
125                "the host was not reached: FLOW_REPLY_SOCKET is not set: a reply goes to the \
126                 socket of the host that holds the run, which FLOW_REPLY_SOCKET names or \
127                 reply_at is given",
128            ),
129            ReplyError::Socket { socket, error } => write!(
130                formatter,
131                "the host was not reached: the reply socket {}: {error}",
132                socket.display()
133            ),
134            ReplyError::Answered { socket, expected } => write!(
135                formatter,
136                "the host was not reached: the host at {} did not answer with the reply's {}",
137                socket.display(),
138                match expected {
139                    ReplyStep::Type => "type",
140                    ReplyStep::Ack => "ack",
141                }
142            ),
143            ReplyError::Untyped(untyped) => {
144                write!(formatter, "the host refused the reply: {}", untyped.said)
145            }
146            ReplyError::Ended { socket, key } => write!(
147                formatter,
148                "the host refused the reply: the host at {} ended the connection without an ack: \
149                 it does not hold run {}, the run never made call {}, the run's program cannot \
150                 be formed, or it takes no replies of data version {}",
151                socket.display(),
152                key.run(),
153                key.call(),
154                DATA_VERSION
155            ),
156        }
157    }
158}
159
160impl std::error::Error for ReplyError {}
161
162/// A frame a host owes a reply: the call's result type, then the `ack`.
163#[derive(Clone, Copy, PartialEq, Eq, Debug)]
164#[expect(
165    clippy::exhaustive_enums,
166    reason = "a reply's exchange owes these two frames, as the protocol has them"
167)]
168pub enum ReplyStep {
169    /// The `type` (11) answering the reply's `type` (10).
170    Type,
171    /// The `ack` (7) answering the reply's `reply` (4).
172    Ack,
173}
174
175impl From<KeyError> for ReplyError {
176    fn from(error: KeyError) -> Self {
177        ReplyError::Key(error)
178    }
179}
180
181/// Answers the open call `key` names with `answer`, and returns what the host
182/// did with it: [`Ack::Ok`] when the answer is recorded,
183/// [`Ack::AlreadyAnswered`] when the call was not open, with `same` true if
184/// its answer equals this one, and [`Ack::TypeError`] when the answer does
185/// not have the call's type. The last two record nothing and do not stop the
186/// run.
187///
188/// It goes to the host whose socket `FLOW_REPLY_SOCKET` names; with that
189/// variable unset or empty it reaches no host. [`reply_at`] names the socket
190/// instead. While a [`testing::replies`] capture is alive, the reply is
191/// recorded there instead and nothing reaches a host.
192///
193/// # Errors
194///
195/// A `key` that is not a key's text form is refused before anything is
196/// sent, and a value that is not one of the
197/// call's result type, [`ReplyError::Mistyped`], before the reply is sent.
198/// No `FLOW_REPLY_SOCKET` is [`ReplyError::NoSocket`], a socket that
199/// fails [`ReplyError::Socket`], and a host that answers out of turn
200/// [`ReplyError::Answered`]. A host that has no result type for the call,
201/// such as one that does not hold its run, is [`ReplyError::Untyped`], and
202/// one that ends the connection before its `ack` is [`ReplyError::Ended`].
203///
204/// An answer is a value or a problem:
205///
206/// ```no_run
207/// use flow_toolkit::{CallKey, ToolProblem, reply};
208/// let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
209/// reply(&key, Ok("approved".to_owned()))?;
210/// reply(&key, Err::<String, _>(ToolProblem::Interrupted("withdrawn".into())))?;
211/// # Ok::<(), Box<dyn std::error::Error>>(())
212/// ```
213///
214/// A hold is no answer, so it does not compile:
215///
216/// ```compile_fail,E0308
217/// use flow_toolkit::{CallKey, Hold, reply};
218/// let key: CallKey = "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1".parse()?;
219/// reply(&key, Err::<String, _>(Hold::new()))?;
220/// # Ok::<(), Box<dyn std::error::Error>>(())
221/// ```
222#[expect(
223    clippy::needless_pass_by_value,
224    reason = "an answer is handed over to be sent once, as a Tool returns one"
225)]
226pub fn reply(
227    key: &(impl ToCallKey + ?Sized),
228    answer: Result<impl Shaped + Debug, ToolProblem>,
229) -> Result<Ack, ReplyError> {
230    let socket = std::env::var_os("FLOW_REPLY_SOCKET").filter(|path| !path.is_empty());
231    deliver(socket.as_deref().map(Path::new), key, &answer)
232}
233
234/// Answers the open call `key` names with `answer` as [`reply`] does, over
235/// the Unix-domain socket at `socket`, where the host that holds the run
236/// takes replies; `FLOW_REPLY_SOCKET` is not read.
237///
238/// # Errors
239///
240/// As [`reply`]'s, a host that cannot be reached at `socket` included.
241#[expect(
242    clippy::needless_pass_by_value,
243    reason = "an answer is handed over to be sent once, as a Tool returns one"
244)]
245pub fn reply_at(
246    socket: impl AsRef<Path>,
247    key: &(impl ToCallKey + ?Sized),
248    answer: Result<impl Shaped + Debug, ToolProblem>,
249) -> Result<Ack, ReplyError> {
250    deliver(Some(socket.as_ref()), key, &answer)
251}
252
253/// Sends `answer` to the call `key` names, over `socket`, unless a capture
254/// takes it; with no socket there is no host to send it to.
255fn deliver(
256    socket: Option<&Path>,
257    key: &(impl ToCallKey + ?Sized),
258    answer: &Result<impl Shaped + Debug, ToolProblem>,
259) -> Result<Ack, ReplyError> {
260    let key = key.to_call_key()?;
261    if let Some(ack) = testing::capture(&key, answer) {
262        return Ok(ack);
263    }
264    let socket = socket.ok_or(ReplyError::NoSocket)?;
265    send_to(socket, &key, answer, ANSWER)
266}
267
268/// How long `reply` waits on the host's socket, for each write of its
269/// frames and for the `ack`.
270const ANSWER: std::time::Duration = std::time::Duration::from_secs(60);
271
272/// The largest frame read from the host: a `type` answer, a key and the
273/// result type's description or a reason, or an `ack`, a key and a type
274/// error's reason.
275#[cfg(unix)]
276const ANSWER_LIMIT: usize = 1 << 20;
277
278/// Sends `answer` to the call `key` names, over the socket at `socket`
279/// where the host takes replies. A host that does not answer there is
280/// unreachable; nothing else is tried. The reply socket is a Unix socket,
281/// so elsewhere every host is unreachable.
282fn send_to(
283    socket: &Path,
284    key: &CallKey,
285    answer: &Result<impl Shaped + Debug, ToolProblem>,
286    within: std::time::Duration,
287) -> Result<Ack, ReplyError> {
288    #[cfg(unix)]
289    {
290        let stream =
291            flow_start::unix::connect(socket).map_err(|error| socket_error(socket, error))?;
292        over(stream, socket, key, answer, within)
293    }
294    #[cfg(not(unix))]
295    {
296        let _ = (socket, key, answer, within);
297        Err(socket_error(socket, ErrorKind::Unsupported.into()))
298    }
299}
300
301/// The exchange over `stream`, a connection to the host at `socket`, with
302/// each write and the wait for the `ack` bounded by `within`.
303#[cfg(unix)]
304fn over(
305    stream: std::os::unix::net::UnixStream,
306    socket: &Path,
307    key: &CallKey,
308    answer: &Result<impl Shaped + Debug, ToolProblem>,
309    within: std::time::Duration,
310) -> Result<Ack, ReplyError> {
311    stream
312        .set_read_timeout(Some(within))
313        .and_then(|()| stream.set_write_timeout(Some(within)))
314        .map_err(|error| {
315            // Darwin refuses socket options with EINVAL or ENOTCONN once
316            // the peer has shut the connection: the host ended it before
317            // reading.
318            if cfg!(target_vendor = "apple")
319                && (error.raw_os_error() == Some(rustix::io::Errno::INVAL.raw_os_error())
320                    || error.kind() == ErrorKind::NotConnected)
321            {
322                ended(socket, key)
323            } else {
324                socket_error(socket, error)
325            }
326        })?;
327    let mut stream = Quiet::new(stream);
328    exchange(&mut stream, socket, key, answer)
329}
330
331/// A connection to the host whose writes never raise SIGPIPE.
332///
333/// A write to a socket whose peer has closed raises SIGPIPE, and a process
334/// whose SIGPIPE has its default disposition dies of it. Rust's runtime
335/// ignores SIGPIPE, but a library cannot count on its host program keeping
336/// it so, so each write asks the kernel not to raise the signal: with
337/// `MSG_NOSIGNAL` where `send` takes it, and on Apple's systems, which lack
338/// that flag, with `SO_NOSIGPIPE` set on the socket before the first write.
339/// A closed host is then the broken pipe `exchange` reports.
340#[cfg(unix)]
341struct Quiet {
342    stream: std::os::unix::net::UnixStream,
343    #[cfg(target_vendor = "apple")]
344    nosigpipe: bool,
345}
346
347#[cfg(unix)]
348impl Quiet {
349    fn new(stream: std::os::unix::net::UnixStream) -> Self {
350        Self {
351            stream,
352            #[cfg(target_vendor = "apple")]
353            nosigpipe: false,
354        }
355    }
356}
357
358#[cfg(unix)]
359impl Read for Quiet {
360    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
361        self.stream.read(buf)
362    }
363}
364
365#[cfg(unix)]
366impl Write for Quiet {
367    #[cfg(target_vendor = "apple")]
368    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
369        use rustix::io::Errno;
370        if !self.nosigpipe {
371            // Darwin refuses socket options with EINVAL once the peer has
372            // shut the connection, which is the closed host a write would
373            // meet as a broken pipe, so it is reported as one.
374            let set = rustix::net::sockopt::set_socket_nosigpipe(&self.stream, true);
375            set.map_err(|e| if e == Errno::INVAL { Errno::PIPE } else { e })?;
376            self.nosigpipe = true;
377        }
378        Ok(rustix::net::send(
379            &self.stream,
380            buf,
381            rustix::net::SendFlags::empty(),
382        )?)
383    }
384    #[cfg(not(target_vendor = "apple"))]
385    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
386        Ok(rustix::net::send(
387            &self.stream,
388            buf,
389            rustix::net::SendFlags::NOSIGNAL,
390        )?)
391    }
392    fn flush(&mut self) -> std::io::Result<()> {
393        Ok(())
394    }
395}
396
397/// The refusal of the host at `socket` that ended the connection before it
398/// acked the reply to `key`.
399#[cfg(unix)]
400fn ended(socket: &Path, key: &CallKey) -> ReplyError {
401    ReplyError::Ended {
402        socket: socket.to_owned(),
403        key: Box::new(key.clone()),
404    }
405}
406
407/// A failure of the host's socket other than the host ending the
408/// connection, such as a write or read that passed its bound.
409fn socket_error(socket: &Path, error: std::io::Error) -> ReplyError {
410    ReplyError::Socket {
411        socket: socket.to_owned(),
412        error,
413    }
414}
415
416/// The `reply` frame that carries `answer` to the call `key` names: an `Ok`
417/// answer is the value in the value encoding at the call's result type,
418/// `types`, as the host said it.
419#[cfg(unix)]
420fn reply_frame(
421    key: &CallKey,
422    answer: &Result<impl Shaped + Debug, ToolProblem>,
423    types: &ResultType,
424) -> Result<Message, ReplyError> {
425    let outcome = match answer {
426        Ok(value) => {
427            let mut bytes = Vec::new();
428            flow_abi::write_shaped(&mut bytes, types.catalog(), types.result(), value)
429                .map_err(|error| ReplyError::Mistyped(refused(error.problem)))?;
430            Outcome::Ok(flow_abi::wire::Rest(bytes))
431        }
432        Err(problem) => problem.clone().into(),
433    };
434    Ok(Message::Reply(flow_tool_protocol::Reply {
435        run: *key.run(),
436        call: key.call().clone(),
437        outcome,
438    }))
439}
440
441/// The exchange over a connection to the host at `socket`: this client's data version as
442/// `describe` carries it, the `type` asked of the call `key` names and the
443/// host's answer, then the `reply` written at that type and the `ack` that
444/// answers it.
445#[cfg(unix)]
446#[expect(
447    clippy::wildcard_enum_match_arm,
448    reason = "std's io::ErrorKind and flow-abi's Message are foreign; any other kind or frame is the error"
449)]
450fn exchange(
451    stream: &mut (impl Read + Write),
452    socket: &Path,
453    key: &CallKey,
454    answer: &Result<impl Shaped + Debug, ToolProblem>,
455) -> Result<Ack, ReplyError> {
456    let describe = Message::Describe {
457        version: DATA_VERSION,
458        reply_limit: 0,
459    };
460    let broken = |error: std::io::Error| match error.kind() {
461        ErrorKind::BrokenPipe
462        | ErrorKind::ConnectionReset
463        | ErrorKind::NotConnected
464        | ErrorKind::UnexpectedEof => ended(socket, key),
465        _ => socket_error(socket, error),
466    };
467    let ask = Message::Type {
468        run: *key.run(),
469        call: key.call().clone(),
470    };
471    flow_tool_protocol::write_frame(stream, &describe).map_err(broken)?;
472    flow_tool_protocol::write_frame(stream, &ask).map_err(broken)?;
473    let types = match answered(stream, socket, key, ReplyStep::Type)? {
474        Message::Typed { run, call, answer } if &run == key.run() && &call == key.call() => {
475            answer.map_err(ReplyError::Untyped)?
476        }
477        _ => return Err(out_of_turn(socket, ReplyStep::Type)),
478    };
479    let reply = reply_frame(key, answer, &types)?;
480    flow_tool_protocol::write_frame(stream, &reply).map_err(broken)?;
481    match answered(stream, socket, key, ReplyStep::Ack)? {
482        Message::Ack { run, call, result } if &run == key.run() && &call == key.call() => {
483            Ok(result)
484        }
485        _ => Err(out_of_turn(socket, ReplyStep::Ack)),
486    }
487}
488
489/// The refusal of a host at `socket` that sent something other than the
490/// `expected` frame.
491#[cfg(unix)]
492fn out_of_turn(socket: &Path, expected: ReplyStep) -> ReplyError {
493    ReplyError::Answered {
494        socket: socket.to_owned(),
495        expected,
496    }
497}
498
499/// The next frame the host sends over `stream`, a connection to the host at
500/// `socket` about the call `key` names, read as the `expected` frame.
501#[cfg(unix)]
502#[expect(
503    clippy::wildcard_enum_match_arm,
504    reason = "io::ErrorKind is std's; any other kind is a failure of the socket"
505)]
506fn answered(
507    stream: &mut impl Read,
508    socket: &Path,
509    key: &CallKey,
510    expected: ReplyStep,
511) -> Result<Message, ReplyError> {
512    let body = match flow_tool_protocol::read_frame(stream, ANSWER_LIMIT) {
513        Ok(None) => return Err(ended(socket, key)),
514        Ok(Some(Frame::Body(body))) => body,
515        Ok(Some(Frame::TooLarge { .. })) => return Err(out_of_turn(socket, expected)),
516        Err(error) => {
517            return Err(match error.kind() {
518                ErrorKind::ConnectionReset | ErrorKind::UnexpectedEof => ended(socket, key),
519                _ => socket_error(socket, error),
520            });
521        }
522    };
523    Message::parse(Route::Socket, &body).map_err(|_| out_of_turn(socket, expected))
524}
525
526#[cfg(test)]
527#[cfg_attr(coverage, coverage(off))]
528#[cfg(unix)]
529mod tests {
530    use std::os::unix::net::UnixStream;
531    use std::time::{Duration, Instant};
532
533    use super::*;
534    use flow_abi::Json;
535
536    use crate::data::LIMITS;
537    use crate::{Int, NoType};
538
539    const RUN: &str = "7f3a91c04be2d5e6f708192a3b4c5d6e";
540
541    fn key() -> CallKey {
542        CallKey::new(
543            flow_span::RunId::parse(RUN).unwrap(),
544            flow_span::CallRef::parse("root#1").unwrap(),
545        )
546    }
547
548    /// `toolkits/conformance/reply.json`'s frames.
549    fn frames() -> Json {
550        let json = flow_abi::parse(include_str!("../../conformance/reply.json"), &LIMITS).unwrap();
551        json.get("frames").unwrap().clone()
552    }
553
554    /// The string member `key` of `case`, when it has one.
555    fn text(case: &Json, key: &str) -> Option<String> {
556        let member = case.get(key)?;
557        let Json::String(text) = member else {
558            panic!("{key} is {}", member.kind());
559        };
560        Some(text.clone())
561    }
562
563    /// The boolean member `key` of `case`, when it has one.
564    fn flag(case: &Json, key: &str) -> Option<bool> {
565        let member = case.get(key)?;
566        let Json::Bool(flag) = member else {
567            panic!("{key} is {}", member.kind());
568        };
569        Some(*flag)
570    }
571
572    /// The array member `key` of `json`.
573    fn cases<'j>(json: &'j Json, key: &str) -> &'j [Json] {
574        match json.get(key) {
575            Some(Json::Array(cases)) => cases,
576            other => panic!("{key} is {other:?}"),
577        }
578    }
579
580    fn hex(bytes: &[u8]) -> String {
581        use std::fmt::Write as _;
582        bytes.iter().fold(String::new(), |mut hex, byte| {
583            let _ = write!(hex, "{byte:02x}");
584            hex
585        })
586    }
587
588    fn unhex(text: &str) -> Vec<u8> {
589        (0..text.len())
590            .step_by(2)
591            .map(|at| u8::from_str_radix(&text[at..at + 2], 16).unwrap())
592            .collect()
593    }
594
595    #[test]
596    fn the_frames_are_the_shared_vectors() {
597        let frames = frames();
598        let describe = Message::Describe {
599            version: DATA_VERSION,
600            reply_limit: 0,
601        };
602        assert_eq!(Some(hex(&describe.frame())), text(&frames, "describe"));
603        assert_eq!(Some(hex(&asked().frame())), text(&frames, "asked"));
604        for case in cases(&frames, "typed") {
605            let frame = text(case, "frame").unwrap();
606            let answer = match (text(case, "result_type"), case.get("refused")) {
607                (Some(types), None) => Ok(ResultType::read(&unhex(&types)).unwrap()),
608                (None, Some(refused)) => Err(Untyped {
609                    reason: flow_abi::wire::Wire::decode(&[match refused.get("reason") {
610                        Some(Json::Number(reason)) => reason.to_string().parse().unwrap(),
611                        other => panic!("reason is {other:?}"),
612                    }])
613                    .unwrap(),
614                    said: text(refused, "said").unwrap(),
615                }),
616                other => panic!("{other:?}"),
617            };
618            if let Ok(types) = &answer {
619                assert_eq!(types.result(), &flow_types::Type::Text);
620            }
621            let typed = typed("root#1", answer);
622            assert_eq!(hex(&typed.frame()), frame);
623            assert_eq!(
624                Message::parse(Route::Socket, &unhex(&frame)[1..]).unwrap(),
625                typed
626            );
627        }
628        for case in cases(&frames, "replies") {
629            let answer = case.get("answer").unwrap();
630            let answer = match (text(answer, "Ok"), answer.get("Err")) {
631                (Some(value), None) => Ok(value),
632                (None, Some(problem)) => Err(
633                    match (
634                        text(problem, "NotStarted"),
635                        text(problem, "Interrupted"),
636                        problem.get("NetworkError"),
637                    ) {
638                        (Some(reason), None, None) => ToolProblem::NotStarted(reason),
639                        (None, Some(reason), None) => ToolProblem::Interrupted(reason),
640                        (None, None, Some(failed)) => ToolProblem::NetworkError {
641                            sent: flag(failed, "sent").unwrap(),
642                            reason: text(failed, "reason").unwrap(),
643                        },
644                        other => panic!("{other:?}"),
645                    },
646                ),
647                other => panic!("{other:?}"),
648            };
649            let frame = reply_frame(&key(), &answer, &text_type()).unwrap().frame();
650            assert_eq!(Some(hex(&frame)), text(case, "frame"));
651        }
652        for case in cases(&frames, "acks") {
653            let frame = text(case, "frame").unwrap();
654            let result = match (
655                flag(case, "ok"),
656                flag(case, "same"),
657                text(case, "type_error"),
658            ) {
659                (Some(true), _, _) => Ack::Ok,
660                (_, Some(same), _) => Ack::AlreadyAnswered { same },
661                (_, _, reason) => Ack::TypeError(reason.unwrap()),
662            };
663            assert_eq!(
664                flag(case, "already_answered").is_some(),
665                matches!(result, Ack::AlreadyAnswered { .. })
666            );
667            let ack = Message::Ack {
668                run: flow_span::RunId::parse(RUN).unwrap(),
669                call: flow_span::CallRef::parse("root#1").unwrap(),
670                result,
671            };
672            assert_eq!(hex(&ack.frame()), frame);
673            // Each is shorter than 128 bytes: its length is its first byte.
674            let bytes = unhex(&frame);
675            assert_eq!(usize::from(bytes[0]), bytes.len() - 1);
676            assert_eq!(Message::parse(Route::Socket, &bytes[1..]).unwrap(), ack);
677        }
678    }
679
680    /// The result type `Text`, as a host describes it.
681    fn text_type() -> ResultType {
682        ResultType::read(&[3, 0]).unwrap()
683    }
684
685    /// The `type` asked of the call `key` names.
686    fn asked() -> Message {
687        Message::Type {
688            run: *key().run(),
689            call: key().call().clone(),
690        }
691    }
692
693    /// The host's answer to a `type` asked of `call`.
694    fn typed(call: &str, answer: Result<ResultType, Untyped>) -> Message {
695        Message::Typed {
696            run: flow_span::RunId::parse(RUN).unwrap(),
697            call: flow_span::CallRef::parse(call).unwrap(),
698            answer,
699        }
700    }
701
702    /// What a host reads of the exchange up to the reply of `sent` at
703    /// `Text`: describe, the type asked, and the reply.
704    fn exchanged(sent: &Result<String, ToolProblem>) -> (Vec<u8>, Vec<u8>) {
705        let describe = Message::Describe {
706            version: DATA_VERSION,
707            reply_limit: 0,
708        };
709        let reply = reply_frame(&key(), sent, &text_type()).unwrap();
710        ([describe.frame(), asked().frame()].concat(), reply.frame())
711    }
712
713    /// The host's end of the exchange over `host`: it reads describe and
714    /// the type asked, answers that the result type is `Text`, reads the
715    /// reply of `sent` and then answers as `answer` says.
716    fn serve(
717        host: &mut UnixStream,
718        sent: &Result<String, ToolProblem>,
719        answer: impl FnOnce(&mut UnixStream),
720    ) {
721        let (opening, reply) = exchanged(sent);
722        let mut read = vec![0; opening.len()];
723        host.read_exact(&mut read).unwrap();
724        assert_eq!(read, opening, "describe, then the type asked");
725        flow_tool_protocol::write_frame(host, &typed("root#1", Ok(text_type()))).unwrap();
726        let mut read = vec![0; reply.len()];
727        host.read_exact(&mut read).unwrap();
728        assert_eq!(read, reply, "then the reply");
729        answer(host);
730    }
731
732    /// A host on the other end of a socket pair: it serves the exchange
733    /// and answers the reply as `answer` says.
734    fn against(
735        answer: impl FnOnce(&mut UnixStream) + Send + 'static,
736        sent: &Result<String, ToolProblem>,
737    ) -> Result<Ack, ReplyError> {
738        let (mut client, mut daemon) = flow_start::unix::pair().unwrap();
739        let served = sent.clone();
740        let serving = std::thread::spawn(move || serve(&mut daemon, &served, answer));
741        let acked = exchange(&mut client, Path::new("/h/reply.sock"), &key(), sent);
742        serving.join().unwrap();
743        acked
744    }
745
746    /// A host that answers the type asked with `answer` and then reads
747    /// nothing more.
748    fn typed_as(
749        answer: Vec<u8>,
750        sent: &Result<impl Shaped + Debug, ToolProblem>,
751    ) -> Result<Ack, ReplyError> {
752        let (mut client, mut daemon) = flow_start::unix::pair().unwrap();
753        let serving = std::thread::spawn(move || {
754            let (opening, _) = exchanged(&Ok(String::new()));
755            let mut read = vec![0; opening.len()];
756            daemon.read_exact(&mut read).unwrap();
757            daemon.write_all(&answer).unwrap();
758            daemon
759        });
760        let acked = exchange(&mut client, Path::new("/h/reply.sock"), &key(), sent);
761        drop(serving.join().unwrap());
762        acked
763    }
764
765    #[test]
766    fn a_type_the_host_refuses_or_does_not_give_sends_no_reply() {
767        let untyped = Untyped {
768            reason: NoType::NoSuchCall,
769            said: "the run made no call root#1".into(),
770        };
771        let refused = typed_as(
772            typed("root#1", Err(untyped.clone())).frame(),
773            &Ok(String::new()),
774        );
775        assert!(
776            matches!(&refused, Err(ReplyError::Untyped(said)) if *said == untyped),
777            "{refused:?}"
778        );
779        let other_call = typed_as(typed("root#2", Ok(text_type())).frame(), &Ok(String::new()));
780        assert!(
781            matches!(
782                &other_call,
783                Err(ReplyError::Answered {
784                    expected: ReplyStep::Type,
785                    ..
786                })
787            ),
788            "{other_call:?}"
789        );
790        let garbage = typed_as(vec![2, 99, 0], &Ok(String::new()));
791        assert!(
792            matches!(
793                &garbage,
794                Err(ReplyError::Answered {
795                    expected: ReplyStep::Type,
796                    ..
797                })
798            ),
799            "{garbage:?}"
800        );
801        let mut huge = Vec::new();
802        flow_abi::primitives::write_bytes(&mut huge, &vec![7; ANSWER_LIMIT + 1]);
803        let too_large = typed_as(huge, &Ok(String::new()));
804        assert!(
805            matches!(
806                &too_large,
807                Err(ReplyError::Answered {
808                    expected: ReplyStep::Type,
809                    ..
810                })
811            ),
812            "{too_large:?}"
813        );
814        let mistyped = typed_as(typed("root#1", Ok(text_type())).frame(), &Ok(Int::from(2)));
815        assert!(
816            matches!(&mistyped, Err(ReplyError::Mistyped(_))),
817            "{mistyped:?}"
818        );
819        assert!(
820            mistyped
821                .unwrap_err()
822                .to_string()
823                .starts_with("the reply is not a value of the call's type: ")
824        );
825    }
826
827    fn ack(call: &str, result: Ack) -> Message {
828        Message::Ack {
829            run: flow_span::RunId::parse(RUN).unwrap(),
830            call: flow_span::CallRef::parse(call).unwrap(),
831            result,
832        }
833    }
834
835    #[test]
836    fn each_ack_the_daemon_sends_comes_back() {
837        for result in [
838            Ack::Ok,
839            Ack::AlreadyAnswered { same: true },
840            Ack::AlreadyAnswered { same: false },
841            Ack::TypeError("not Text".into()),
842        ] {
843            let expected = result.clone();
844            let acked = against(
845                move |daemon| {
846                    flow_tool_protocol::write_frame(daemon, &ack("root#1", result)).unwrap();
847                },
848                &Ok("yes".to_owned()),
849            );
850            assert!(matches!(&acked, Ok(ack) if *ack == expected), "{acked:?}");
851        }
852    }
853
854    #[test]
855    fn a_connection_that_ends_without_an_ack_is_refused_naming_the_host_run_and_call() {
856        let refused = against(|_| {}, &Ok(String::new()));
857        assert!(
858            matches!(&refused, Err(ReplyError::Ended { socket, key: ended })
859                if *socket == Path::new("/h/reply.sock") && **ended == key()),
860            "{refused:?}"
861        );
862    }
863
864    #[test]
865    fn a_connection_the_daemon_already_closed_is_refused() {
866        let (client, daemon) = flow_start::unix::pair().unwrap();
867        drop(daemon);
868        let mut client = Quiet::new(client);
869        let refused = exchange(
870            &mut client,
871            Path::new("/h/reply.sock"),
872            &key(),
873            &Ok(String::new()),
874        );
875        assert!(
876            matches!(&refused, Err(ReplyError::Ended { .. })),
877            "{refused:?}"
878        );
879    }
880
881    /// A host program may give SIGPIPE its default, terminating disposition;
882    /// a reply to a daemon that already closed is still an error to it.
883    #[test]
884    fn a_closed_daemon_is_refused_even_where_sigpipe_would_end_the_process() {
885        use flow_start::Spawn as _;
886        use flow_testing::{Rerun, rerun};
887        let Rerun::Parent(mut command) =
888            rerun(a_closed_daemon_is_refused_even_where_sigpipe_would_end_the_process)
889        else {
890            // std gives SIGPIPE its default disposition just before `execvp`
891            // and keeps it when `execvp` refuses, as it refuses an argument
892            // longer than any system's limit.
893            let refused = std::process::Command::new("/bin/sh")
894                .arg("x".repeat(16 << 20))
895                .locked_exec();
896            assert_eq!(
897                refused.raw_os_error(),
898                Some(rustix::io::Errno::TOOBIG.raw_os_error()),
899                "{refused}"
900            );
901            let (client, daemon) = flow_start::unix::pair().unwrap();
902            drop(daemon);
903            let mut client = Quiet::new(client);
904            let refused = exchange(
905                &mut client,
906                Path::new("/h/reply.sock"),
907                &key(),
908                &Ok(String::new()),
909            );
910            assert!(
911                matches!(refused, Err(ReplyError::Ended { .. })),
912                "{refused:?}"
913            );
914            return;
915        };
916        let output = command.locked_output().expect("the test binary runs again");
917        assert!(output.status.success(), "{output:?}");
918    }
919
920    #[test]
921    fn a_daemon_of_another_data_version_ends_the_connection_and_the_error_names_the_version() {
922        let refused = against(
923            |daemon| daemon.shutdown(std::net::Shutdown::Both).unwrap(),
924            &Err(ToolProblem::NotStarted("no".into())),
925        );
926        let version = format!("data version {DATA_VERSION}");
927        assert!(
928            matches!(&refused, Err(ReplyError::Ended { .. })),
929            "{refused:?}"
930        );
931        assert!(refused.unwrap_err().to_string().contains(&version));
932    }
933
934    #[test]
935    fn an_answer_that_is_not_the_reply_s_ack_is_no_answer() {
936        let other_call = against(
937            |daemon| {
938                flow_tool_protocol::write_frame(daemon, &ack("root#2", Ack::Ok)).unwrap();
939            },
940            &Ok(String::new()),
941        );
942        assert!(
943            matches!(
944                &other_call,
945                Err(ReplyError::Answered {
946                    expected: ReplyStep::Ack,
947                    ..
948                })
949            ),
950            "{other_call:?}"
951        );
952        let too_large = against(
953            |daemon| {
954                let mut frame = Vec::new();
955                flow_abi::primitives::write_bytes(&mut frame, &vec![7; ANSWER_LIMIT + 1]);
956                daemon.write_all(&frame).unwrap();
957            },
958            &Ok(String::new()),
959        );
960        assert!(
961            matches!(
962                &too_large,
963                Err(ReplyError::Answered {
964                    expected: ReplyStep::Ack,
965                    ..
966                })
967            ),
968            "{too_large:?}"
969        );
970    }
971
972    /// A host that accepts the connection and never answers: the wait for
973    /// the type asked stops at its bound, as an error.
974    #[test]
975    fn a_host_that_stops_reading_cannot_hold_a_reply_forever() {
976        let dir = tempfile::tempdir().unwrap();
977        let path = dir.path().join("reply.sock");
978        let listener = flow_start::unix::bind(&path).unwrap();
979        let (done, held) = std::sync::mpsc::channel::<()>();
980        let accepting = std::thread::spawn(move || {
981            let stream = flow_testing::accepted(&listener);
982            // Holds the connection open, unread, until the client is done.
983            let _ = held.recv();
984            drop(stream);
985        });
986        let begun = Instant::now();
987        let stuck = send_to(
988            &path,
989            &key(),
990            &Ok("x".to_owned()),
991            Duration::from_millis(300),
992        );
993        let took = begun.elapsed();
994        done.send(()).unwrap();
995        accepting.join().unwrap();
996        assert!(
997            matches!(&stuck, Err(ReplyError::Socket { error, .. })
998                if matches!(error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut)),
999            "{stuck:?}"
1000        );
1001        assert!(took < Duration::from_secs(10), "{took:?}");
1002    }
1003
1004    /// A host that ended the connection before the reply was sent refused
1005    /// it, even where the closed socket refuses its options too.
1006    #[test]
1007    fn a_connection_the_host_already_ended_is_refused() {
1008        let (stream, host) = flow_start::unix::pair().unwrap();
1009        drop(host);
1010        let path = Path::new("reply.sock");
1011        let refused = over(stream, path, &key(), &Ok("yes".to_owned()), ANSWER);
1012        assert!(
1013            matches!(&refused, Err(ReplyError::Ended { .. })),
1014            "{refused:?}"
1015        );
1016    }
1017
1018    /// The reply goes to the host listening on the socket it is given, and a
1019    /// socket nobody answers on is unreachable: nothing else is tried.
1020    #[test]
1021    fn a_reply_socket_takes_the_reply_and_one_nobody_answers_is_unreachable() {
1022        let dir = tempfile::tempdir().unwrap();
1023        let path = dir.path().join("reply.sock");
1024        let gone = reply_at(&path, &key(), Ok("yes".to_owned()));
1025        assert!(
1026            matches!(&gone, Err(ReplyError::Socket { socket, error })
1027                if *socket == path && error.kind() == std::io::ErrorKind::NotFound),
1028            "{gone:?}"
1029        );
1030        let listener = flow_start::unix::bind(&path).unwrap();
1031        let serving = std::thread::spawn(move || {
1032            let mut host = flow_testing::accepted(&listener);
1033            serve(&mut host, &Ok("yes".to_owned()), |host| {
1034                flow_tool_protocol::write_frame(host, &ack("root#1", Ack::Ok)).unwrap();
1035            });
1036            let host = flow_testing::accepted(&listener);
1037            drop(host);
1038        });
1039        let acked = reply_at(&path, &key(), Ok("yes".to_owned()));
1040        assert!(matches!(acked, Ok(Ack::Ok)), "{acked:?}");
1041        let refused = send_to(&path, &key(), &Ok("yes".to_owned()), ANSWER);
1042        serving.join().unwrap();
1043        assert!(
1044            matches!(&refused, Err(ReplyError::Ended { socket, .. }) if *socket == path),
1045            "{refused:?}"
1046        );
1047    }
1048
1049    /// With no socket to send to, a reply reaches no host, and the error
1050    /// names `FLOW_REPLY_SOCKET`; a capture still takes it.
1051    #[test]
1052    fn with_no_reply_socket_a_reply_reaches_no_host_and_says_so() {
1053        let unsent = deliver(None, &key(), &Ok("yes".to_owned()));
1054        assert!(matches!(&unsent, Err(ReplyError::NoSocket)), "{unsent:?}");
1055        let captured = testing::replies();
1056        let taken = deliver(None, &key(), &Ok("yes".to_owned()));
1057        assert!(matches!(taken, Ok(Ack::Ok)), "{taken:?}");
1058        assert_eq!(captured.sent().len(), 1);
1059    }
1060
1061    #[test]
1062    fn reply_errors_say_what_happened() {
1063        assert_eq!(
1064            ReplyError::from("x".parse::<CallKey>().unwrap_err()).to_string(),
1065            "\"x\" is not a call's key: the run's id, '/', then the call's id"
1066        );
1067        assert!(
1068            ReplyError::NoSocket
1069                .to_string()
1070                .starts_with("the host was not reached: FLOW_REPLY_SOCKET is not set")
1071        );
1072        assert_eq!(
1073            ReplyError::Socket {
1074                socket: "reply.sock".into(),
1075                error: std::io::ErrorKind::NotFound.into(),
1076            }
1077            .to_string(),
1078            "the host was not reached: the reply socket reply.sock: entity not found"
1079        );
1080        assert_eq!(
1081            ReplyError::Answered {
1082                socket: "reply.sock".into(),
1083                expected: ReplyStep::Ack,
1084            }
1085            .to_string(),
1086            "the host was not reached: the host at reply.sock did not answer with the reply's ack"
1087        );
1088        assert_eq!(
1089            ReplyError::Untyped(Untyped {
1090                reason: NoType::UnknownRun,
1091                said: "no run".into(),
1092            })
1093            .to_string(),
1094            "the host refused the reply: no run"
1095        );
1096    }
1097}
1098
1099/// Testing Tools and [`reply`] natively, without a host.
1100///
1101/// A Tool function is an ordinary function: a test calls it with
1102/// [`Context::for_test`](crate::Context::for_test) and checks what it
1103/// returns, a [`Hold`](crate::Hold) included. [`replies`](testing::replies) captures the replies
1104/// [`reply`] sends while it is alive, so a test can drive a held call and
1105/// the webhook that answers it in one process.
1106pub mod testing {
1107    use std::sync::{Mutex, MutexGuard, PoisonError};
1108
1109    use std::fmt::Debug;
1110
1111    use flow_abi::Ack;
1112
1113    use crate::key::CallKey;
1114    use crate::server::ToolProblem;
1115
1116    /// One reply [`reply`](crate::reply()) sent while a capture was alive.
1117    #[derive(Clone, PartialEq, Eq, Debug)]
1118    #[non_exhaustive]
1119    pub struct Sent {
1120        /// The call it answers.
1121        pub key: CallKey,
1122        /// The value, as its `Debug` text writes it, or the problem.
1123        pub answer: Result<String, ToolProblem>,
1124    }
1125
1126    /// The replies sent while it is alive, which reach no host. Each is
1127    /// acked as a host that holds every call open would ack it: `ok` for a
1128    /// key's first reply, then `already answered`, with `same` true when the
1129    /// answer is the same value as the first. It checks no types.
1130    ///
1131    /// Captures are taken one at a time across the process: a second waits
1132    /// until the first is dropped.
1133    #[derive(Debug)]
1134    pub struct Replies {
1135        _turn: MutexGuard<'static, ()>,
1136    }
1137
1138    impl Replies {
1139        /// The replies sent so far, in the order they were sent.
1140        pub fn sent(&self) -> Vec<Sent> {
1141            lock(&CAPTURED).clone().unwrap_or_default()
1142        }
1143    }
1144
1145    impl Drop for Replies {
1146        fn drop(&mut self) {
1147            *lock(&CAPTURED) = None;
1148        }
1149    }
1150
1151    /// Starts capturing replies; they reach no host until it is dropped.
1152    pub fn replies() -> Replies {
1153        let turn = TURN.lock().unwrap_or_else(PoisonError::into_inner);
1154        *lock(&CAPTURED) = Some(Vec::new());
1155        Replies { _turn: turn }
1156    }
1157
1158    /// One capture at a time.
1159    static TURN: Mutex<()> = Mutex::new(());
1160    /// The replies captured, while a capture is alive.
1161    static CAPTURED: Mutex<Option<Vec<Sent>>> = Mutex::new(None);
1162
1163    fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1164        mutex.lock().unwrap_or_else(PoisonError::into_inner)
1165    }
1166
1167    /// Records a reply when a capture is alive, and acks it.
1168    pub(crate) fn capture(key: &CallKey, answer: &Result<impl Debug, ToolProblem>) -> Option<Ack> {
1169        let mut captured = lock(&CAPTURED);
1170        let sent = captured.as_mut()?;
1171        let answer = match answer {
1172            Ok(value) => Ok(format!("{value:?}")),
1173            Err(problem) => Err(problem.clone()),
1174        };
1175        let ack = match sent.iter().find(|earlier| earlier.key == *key) {
1176            Some(first) => Ack::AlreadyAnswered {
1177                same: first.answer == answer,
1178            },
1179            None => Ack::Ok,
1180        };
1181        sent.push(Sent {
1182            key: key.clone(),
1183            answer,
1184        });
1185        Some(ack)
1186    }
1187}