Skip to main content

isothrum_client/
wire.rs

1//! One connection to a service: JSON lines over the local endpoint, both ways.
2
3use interprocess::local_socket::tokio::Stream;
4use interprocess::local_socket::traits::tokio::Stream as _;
5use interprocess::local_socket::{GenericFilePath, ToFsName as _};
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader};
9
10use crate::proto::MAX_LINE;
11
12/// The reading half of a connection, by lines.
13pub type Reader = LineReader<tokio::io::ReadHalf<Stream>>;
14
15/// The writing half of a connection.
16pub type Writer = tokio::io::WriteHalf<Stream>;
17
18/// The reading half of a connection.
19pub struct LineReader<R> {
20    inner: BufReader<R>,
21    buf: Vec<u8>,
22}
23
24impl<R: tokio::io::AsyncRead + Unpin> LineReader<R> {
25    /// Lines read from `inner`.
26    pub fn new(inner: R) -> LineReader<R> {
27        LineReader {
28            inner: BufReader::new(inner),
29            buf: Vec::new(),
30        }
31    }
32
33    /// The next line as a `T`; `None` at the end of the stream.
34    ///
35    /// # Errors
36    ///
37    /// The stream failed, a line is longer than [`MAX_LINE`] or isn't a `T` (`InvalidData`).
38    pub async fn next<T: DeserializeOwned>(&mut self) -> std::io::Result<Option<T>> {
39        loop {
40            self.buf.clear();
41            let limit = u64::try_from(MAX_LINE).unwrap_or(u64::MAX).saturating_add(1);
42            let read = (&mut self.inner).take(limit).read_until(b'\n', &mut self.buf).await?;
43            if read == 0 {
44                return Ok(None);
45            }
46            if self.buf.last() != Some(&b'\n') && self.buf.len() > MAX_LINE {
47                return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "a line longer than the protocol allows"));
48            }
49            let line = self.buf.trim_ascii();
50            if line.is_empty() {
51                continue;
52            }
53            return serde_json::from_slice(line)
54                .map(Some)
55                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e));
56        }
57    }
58}
59
60/// Writes `value` as one line to `writer`.
61///
62/// # Errors
63///
64/// The stream failed.
65pub async fn write_line<W: tokio::io::AsyncWrite + Unpin, T: Serialize>(writer: &mut W, value: &T) -> std::io::Result<()> {
66    let mut line = serde_json::to_vec(value).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
67    line.push(b'\n');
68    writer.write_all(&line).await?;
69    writer.flush().await
70}
71
72/// Connects to the endpoint `endpoint` names (a socket path, a pipe name).
73///
74/// # Errors
75///
76/// Nothing listens there.
77pub async fn connect(endpoint: &str) -> std::io::Result<(Reader, Writer)> {
78    let name = endpoint.to_fs_name::<GenericFilePath>()?;
79    let stream = Stream::connect(name).await?;
80    let (recv, send) = tokio::io::split(stream);
81    Ok((LineReader::new(recv), send))
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    /// Lines read from `bytes`, each as JSON.
89    fn reading(bytes: &[u8]) -> LineReader<std::io::Cursor<Vec<u8>>> {
90        LineReader::new(std::io::Cursor::new(bytes.to_vec()))
91    }
92
93    #[tokio::test]
94    async fn each_line_is_a_value_blank_ones_skipped_and_the_end_is_none() {
95        let mut lines = reading(b"{\"a\":1}\n\n  \r\n{\"a\":2}");
96        assert_eq!(lines.next::<serde_json::Value>().await.unwrap(), Some(serde_json::json!({"a": 1})));
97        assert_eq!(
98            lines.next::<serde_json::Value>().await.unwrap(),
99            Some(serde_json::json!({"a": 2})),
100            "a last line with no break"
101        );
102        assert_eq!(lines.next::<serde_json::Value>().await.unwrap(), None);
103    }
104
105    #[tokio::test]
106    async fn a_malformed_line_and_one_past_the_limit_are_invalid_data() {
107        let malformed = reading(b"{not json}\n").next::<serde_json::Value>().await.unwrap_err();
108        assert_eq!(malformed.kind(), std::io::ErrorKind::InvalidData);
109        let mut long = vec![b'"'; MAX_LINE + 2];
110        long.push(b'\n');
111        let past = reading(&long).next::<serde_json::Value>().await.unwrap_err();
112        assert_eq!(past.kind(), std::io::ErrorKind::InvalidData);
113        assert_eq!(past.to_string(), "a line longer than the protocol allows");
114    }
115
116    #[tokio::test]
117    async fn a_written_value_is_one_line_read_back_as_itself() {
118        let mut out = Vec::new();
119        write_line(&mut out, &serde_json::json!({"cmd": "list", "id": 3})).await.unwrap();
120        assert_eq!(out.last(), Some(&b'\n'));
121        assert_eq!(out.iter().position(|b| *b == b'\n'), Some(out.len() - 1), "one line");
122        let back = reading(&out).next::<serde_json::Value>().await.unwrap();
123        assert_eq!(back, Some(serde_json::json!({"cmd": "list", "id": 3})));
124    }
125}