Skip to main content

wavegraph_remote/
unix.rs

1use crate::{Transport, protocol::MAX_FRAME};
2use alloc::vec::Vec;
3use core::time::Duration;
4use std::{
5    env,
6    io::{self, Read, Write},
7    net::Shutdown,
8    os::unix::net::UnixStream,
9    path::{Path, PathBuf},
10    time::Instant,
11};
12
13/// Resolve an explicit socket path or the per-user default shared by `wavegraph` and `wr`.
14/// The default is `$XDG_RUNTIME_DIR/wavegraph.sock` when the runtime directory
15/// is absolute, or `~/.wavegraph.sock` otherwise.
16///
17/// # Errors
18/// Returns an error if neither a runtime directory nor a home directory is available.
19pub fn socket_path(path: Option<&Path>) -> io::Result<PathBuf> {
20    if let Some(path) = path {
21        return Ok(path.to_owned());
22    }
23    if let Some(dir) = env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from)
24        && dir.is_absolute()
25    {
26        return Ok(dir.join("wavegraph.sock"));
27    }
28    env::home_dir()
29        .filter(|dir| dir.is_absolute())
30        .map(|dir| dir.join(".wavegraph.sock"))
31        .ok_or_else(|| {
32            io::Error::new(
33                io::ErrorKind::NotFound,
34                "cannot locate the default WaveGraph socket. Use --socket PATH",
35            )
36        })
37}
38
39/// Local stream of MIDI messages, each preceded by its length as one byte.
40/// Messages must contain between one and [`MAX_FRAME`] bytes.
41#[derive(Debug)]
42pub struct UnixTransport {
43    stream: UnixStream,
44    frame: [u8; MAX_FRAME + 1],
45    received: usize,
46}
47
48impl UnixTransport {
49    /// Open a connection to the WaveGraph host and bound stalled writes.
50    ///
51    /// # Errors
52    /// Returns an error if the socket is unavailable or the timeout is zero.
53    pub fn connect(path: impl AsRef<Path>, write_timeout: Duration) -> io::Result<Self> {
54        let path = path.as_ref();
55        let stream = UnixStream::connect(path)
56            .map_err(|e| io::Error::new(e.kind(), format!("connect to {}: {e}", path.display())))?;
57        stream.set_write_timeout(Some(write_timeout))?;
58        Ok(Self::from(stream))
59    }
60}
61
62impl From<UnixStream> for UnixTransport {
63    fn from(stream: UnixStream) -> Self {
64        Self {
65            stream,
66            frame: [0; MAX_FRAME + 1],
67            received: 0,
68        }
69    }
70}
71
72impl Transport for UnixTransport {
73    fn send(&mut self, message: &[u8]) -> io::Result<()> {
74        if !(1..=MAX_FRAME).contains(&message.len()) {
75            return Err(io::Error::new(
76                io::ErrorKind::InvalidInput,
77                "invalid MIDI frame length",
78            ));
79        }
80        let mut frame = [0; MAX_FRAME + 1];
81        frame[0] = u8::try_from(message.len()).map_err(io::Error::other)?;
82        frame[1..=message.len()].copy_from_slice(message);
83        self.stream
84            .write_all(&frame[..=message.len()])
85            .inspect_err(|_| {
86                // A partial write would leave the peer inside an incomplete frame.
87                let _ = self.stream.shutdown(Shutdown::Both);
88            })
89    }
90
91    fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>> {
92        let started = Instant::now();
93        loop {
94            let end = if self.received == 0 {
95                1
96            } else {
97                let length = usize::from(self.frame[0]);
98                if !(1..=MAX_FRAME).contains(&length) {
99                    let _ = self.stream.shutdown(Shutdown::Both);
100                    return Err(io::Error::new(
101                        io::ErrorKind::InvalidData,
102                        "invalid MIDI frame length",
103                    ));
104                }
105                if self.received > length {
106                    self.received = 0;
107                    return Ok(self.frame[1..=length].to_vec());
108                }
109                length.saturating_add(1)
110            };
111            let remaining = timeout
112                .checked_sub(started.elapsed())
113                .filter(|wait| !wait.is_zero())
114                .ok_or(io::ErrorKind::TimedOut)?;
115            self.stream.set_read_timeout(Some(remaining))?;
116            match self.stream.read(&mut self.frame[self.received..end]) {
117                Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
118                Ok(count) => self.received = self.received.saturating_add(count),
119                Err(e) if e.kind() == io::ErrorKind::Interrupted => (),
120                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
121                    return Err(io::ErrorKind::TimedOut.into());
122                }
123                Err(e) => return Err(e),
124            }
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn timeout_preserves_a_partial_frame_and_next_message_boundary() -> io::Result<()> {
135        let (stream, mut peer) = UnixStream::pair()?;
136        let mut transport = UnixTransport::from(stream);
137        peer.write_all(&[3, 0x90])?;
138        assert_eq!(
139            transport
140                .receive(Duration::from_millis(10))
141                .expect_err("incomplete frame")
142                .kind(),
143            io::ErrorKind::TimedOut
144        );
145        peer.write_all(&[60, 100, 1, 0xfc])?;
146        assert_eq!(transport.receive(Duration::from_secs(1))?, [0x90, 60, 100]);
147        assert_eq!(transport.receive(Duration::from_secs(1))?, [0xfc]);
148        Ok(())
149    }
150}