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;
pub trait ToCallKey {
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()
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ReplyError {
Key(KeyError),
Mistyped(DecodeError),
NoSocket,
Socket {
socket: PathBuf,
error: std::io::Error,
},
Answered {
socket: PathBuf,
expected: ReplyStep,
},
Untyped(Untyped),
Ended {
socket: PathBuf,
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 {}
#[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 {
Type,
Ack,
}
impl From<KeyError> for ReplyError {
fn from(error: KeyError) -> Self {
ReplyError::Key(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)
}
#[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)
}
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)
}
const ANSWER: std::time::Duration = std::time::Duration::from_secs(60);
#[cfg(unix)]
const ANSWER_LIMIT: usize = 1 << 20;
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()))
}
}
#[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| {
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)
}
#[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 {
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(())
}
}
#[cfg(unix)]
fn ended(socket: &Path, key: &CallKey) -> ReplyError {
ReplyError::Ended {
socket: socket.to_owned(),
key: Box::new(key.clone()),
}
}
fn socket_error(socket: &Path, error: std::io::Error) -> ReplyError {
ReplyError::Socket {
socket: socket.to_owned(),
error,
}
}
#[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,
}))
}
#[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)),
}
}
#[cfg(unix)]
fn out_of_turn(socket: &Path, expected: ReplyStep) -> ReplyError {
ReplyError::Answered {
socket: socket.to_owned(),
expected,
}
}
#[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(),
)
}
fn frames() -> Json {
let json = flow_abi::parse(include_str!("../../conformance/reply.json"), &LIMITS).unwrap();
json.get("frames").unwrap().clone()
}
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())
}
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)
}
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);
let bytes = unhex(&frame);
assert_eq!(usize::from(bytes[0]), bytes.len() - 1);
assert_eq!(Message::parse(Route::Socket, &bytes[1..]).unwrap(), ack);
}
}
fn text_type() -> ResultType {
ResultType::read(&[3, 0]).unwrap()
}
fn asked() -> Message {
Message::Type {
run: *key().run(),
call: key().call().clone(),
}
}
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,
}
}
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())
}
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);
}
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
}
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:?}"
);
}
#[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 {
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:?}"
);
}
#[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);
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:?}");
}
#[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:?}"
);
}
#[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:?}"
);
}
#[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"
);
}
}
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;
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Sent {
pub key: CallKey,
pub answer: Result<String, ToolProblem>,
}
#[derive(Debug)]
pub struct Replies {
_turn: MutexGuard<'static, ()>,
}
impl Replies {
pub fn sent(&self) -> Vec<Sent> {
lock(&CAPTURED).clone().unwrap_or_default()
}
}
impl Drop for Replies {
fn drop(&mut self) {
*lock(&CAPTURED) = None;
}
}
pub fn replies() -> Replies {
let turn = TURN.lock().unwrap_or_else(PoisonError::into_inner);
*lock(&CAPTURED) = Some(Vec::new());
Replies { _turn: turn }
}
static TURN: Mutex<()> = Mutex::new(());
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)
}
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)
}
}