use crate::{Transport, protocol::MAX_FRAME};
use alloc::vec::Vec;
use core::time::Duration;
use std::{
env,
io::{self, Read, Write},
net::Shutdown,
os::unix::net::UnixStream,
path::{Path, PathBuf},
time::Instant,
};
pub fn socket_path(path: Option<&Path>) -> io::Result<PathBuf> {
if let Some(path) = path {
return Ok(path.to_owned());
}
if let Some(dir) = env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from)
&& dir.is_absolute()
{
return Ok(dir.join("wavegraph.sock"));
}
env::home_dir()
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join(".wavegraph.sock"))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"cannot locate the default WaveGraph socket. Use --socket PATH",
)
})
}
#[derive(Debug)]
pub struct UnixTransport {
stream: UnixStream,
frame: [u8; MAX_FRAME + 1],
received: usize,
}
impl UnixTransport {
pub fn connect(path: impl AsRef<Path>, write_timeout: Duration) -> io::Result<Self> {
let path = path.as_ref();
let stream = UnixStream::connect(path)
.map_err(|e| io::Error::new(e.kind(), format!("connect to {}: {e}", path.display())))?;
stream.set_write_timeout(Some(write_timeout))?;
Ok(Self::from(stream))
}
}
impl From<UnixStream> for UnixTransport {
fn from(stream: UnixStream) -> Self {
Self {
stream,
frame: [0; MAX_FRAME + 1],
received: 0,
}
}
}
impl Transport for UnixTransport {
fn send(&mut self, message: &[u8]) -> io::Result<()> {
if !(1..=MAX_FRAME).contains(&message.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid MIDI frame length",
));
}
let mut frame = [0; MAX_FRAME + 1];
frame[0] = u8::try_from(message.len()).map_err(io::Error::other)?;
frame[1..=message.len()].copy_from_slice(message);
self.stream
.write_all(&frame[..=message.len()])
.inspect_err(|_| {
let _ = self.stream.shutdown(Shutdown::Both);
})
}
fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>> {
let started = Instant::now();
loop {
let end = if self.received == 0 {
1
} else {
let length = usize::from(self.frame[0]);
if !(1..=MAX_FRAME).contains(&length) {
let _ = self.stream.shutdown(Shutdown::Both);
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid MIDI frame length",
));
}
if self.received > length {
self.received = 0;
return Ok(self.frame[1..=length].to_vec());
}
length.saturating_add(1)
};
let remaining = timeout
.checked_sub(started.elapsed())
.filter(|wait| !wait.is_zero())
.ok_or(io::ErrorKind::TimedOut)?;
self.stream.set_read_timeout(Some(remaining))?;
match self.stream.read(&mut self.frame[self.received..end]) {
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
Ok(count) => self.received = self.received.saturating_add(count),
Err(e) if e.kind() == io::ErrorKind::Interrupted => (),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
return Err(io::ErrorKind::TimedOut.into());
}
Err(e) => return Err(e),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timeout_preserves_a_partial_frame_and_next_message_boundary() -> io::Result<()> {
let (stream, mut peer) = UnixStream::pair()?;
let mut transport = UnixTransport::from(stream);
peer.write_all(&[3, 0x90])?;
assert_eq!(
transport
.receive(Duration::from_millis(10))
.expect_err("incomplete frame")
.kind(),
io::ErrorKind::TimedOut
);
peer.write_all(&[60, 100, 1, 0xfc])?;
assert_eq!(transport.receive(Duration::from_secs(1))?, [0x90, 60, 100]);
assert_eq!(transport.receive(Duration::from_secs(1))?, [0xfc]);
Ok(())
}
}