1use 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
42pub trait ToCallKey {
44 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#[derive(Debug)]
73#[non_exhaustive]
74pub enum ReplyError {
75 Key(KeyError),
77 Mistyped(DecodeError),
80 NoSocket,
83 Socket {
86 socket: PathBuf,
88 error: std::io::Error,
90 },
91 Answered {
94 socket: PathBuf,
96 expected: ReplyStep,
98 },
99 Untyped(Untyped),
102 Ended {
107 socket: PathBuf,
109 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#[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 Type,
171 Ack,
173}
174
175impl From<KeyError> for ReplyError {
176 fn from(error: KeyError) -> Self {
177 ReplyError::Key(error)
178 }
179}
180
181#[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#[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
253fn 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
268const ANSWER: std::time::Duration = std::time::Duration::from_secs(60);
271
272#[cfg(unix)]
276const ANSWER_LIMIT: usize = 1 << 20;
277
278fn 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#[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 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#[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 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#[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
407fn socket_error(socket: &Path, error: std::io::Error) -> ReplyError {
410 ReplyError::Socket {
411 socket: socket.to_owned(),
412 error,
413 }
414}
415
416#[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#[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#[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#[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 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 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 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 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 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 fn text_type() -> ResultType {
682 ResultType::read(&[3, 0]).unwrap()
683 }
684
685 fn asked() -> Message {
687 Message::Type {
688 run: *key().run(),
689 call: key().call().clone(),
690 }
691 }
692
693 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 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 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 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 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 #[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 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 #[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 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 #[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 #[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 #[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
1099pub 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 #[derive(Clone, PartialEq, Eq, Debug)]
1118 #[non_exhaustive]
1119 pub struct Sent {
1120 pub key: CallKey,
1122 pub answer: Result<String, ToolProblem>,
1124 }
1125
1126 #[derive(Debug)]
1134 pub struct Replies {
1135 _turn: MutexGuard<'static, ()>,
1136 }
1137
1138 impl Replies {
1139 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 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 static TURN: Mutex<()> = Mutex::new(());
1160 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 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}