wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
//! Serve the same MIDI and graph-discovery messages as the FM-1 over a local stream.

use alloc::sync::Arc;
use std::{
    fs, io,
    os::unix::fs::{MetadataExt as _, PermissionsExt as _},
    path::{Path, PathBuf},
};
use tokio::{
    io::{AsyncReadExt as _, AsyncWriteExt as _},
    net::{UnixListener, UnixStream},
    sync::{mpsc, watch},
    task::JoinSet,
};
use wavegraph_remote::{
    Graph, MidiCommand, PortKind,
    protocol::{self, ErrorCode, MAX_FRAME, MAX_PAYLOAD, Message, NodeRef, SnapshotMeta},
};

pub(crate) struct Server {
    listener: UnixListener,
    path: PathBuf,
    identity: (u64, u64),
    graph: Arc<Graph>,
    commands: mpsc::Sender<MidiCommand>,
    accepted: watch::Receiver<Option<u64>>,
}

impl Server {
    pub(crate) fn bind(
        path: &Path,
        graph: Graph,
        commands: mpsc::Sender<MidiCommand>,
        accepted: watch::Receiver<Option<u64>>,
    ) -> io::Result<Self> {
        graph.connections()?;
        // Report unsupported frame sizes and aliases before opening the socket.
        snapshot(&graph, 0, 0, &mut Vec::new())?;
        let listener = UnixListener::bind(path)
            .map_err(|e| io::Error::new(e.kind(), format!("bind {}: {e}", path.display())))?;
        let metadata = fs::symlink_metadata(path)?;
        let server = Self {
            listener,
            path: path.into(),
            identity: (metadata.dev(), metadata.ino()),
            graph: Arc::new(graph),
            commands,
            accepted,
        };
        fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
        Ok(server)
    }

    pub(crate) async fn run(self) -> io::Result<()> {
        let mut clients = JoinSet::new();
        loop {
            tokio::select! {
                result = self.listener.accept(), if clients.len() < 32 => {
                    let (stream, _) = result?;
                    clients.spawn(connection(stream, Arc::clone(&self.graph), self.commands.clone(), self.accepted.clone()));
                }
                Some(result) = clients.join_next_with_id(), if !clients.is_empty() => {
                    if let (client, Err(error)) = result.map_err(io::Error::other)? {
                        tracing::warn!(%client, %error, "client connection failed");
                    }
                }
            }
        }
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        // Preserve a replacement listener if the path was renamed or unlinked.
        if fs::symlink_metadata(&self.path).is_ok_and(|m| self.identity == (m.dev(), m.ino())) {
            let _ = fs::remove_file(&self.path);
        }
    }
}

#[tracing::instrument(name = "client", skip_all, fields(id = %tokio::task::id()))]
async fn connection(
    mut stream: UnixStream,
    graph: Arc<Graph>,
    commands: mpsc::Sender<MidiCommand>,
    accepted: watch::Receiver<Option<u64>>,
) -> io::Result<()> {
    let mut frame = [0; MAX_FRAME];
    let mut response = Vec::new();
    loop {
        let mut prefix = [0];
        if stream.read(&mut prefix).await? == 0 {
            return Ok(());
        }
        let bytes = frame
            .get_mut(..usize::from(prefix[0]))
            .filter(|bytes| !bytes.is_empty())
            .ok_or_else(|| invalid("invalid MIDI frame length"))?;
        stream.read_exact(bytes).await?;
        if let Some(command) = MidiCommand::decode(bytes) {
            tracing::info!(?command, "received MIDI command");
            commands
                .send(command)
                .await
                .map_err(|_| io::ErrorKind::BrokenPipe)?;
        } else if protocol::is_remote(bytes) {
            let request = protocol::request_id(bytes).map_err(io::Error::other)?;
            let mut scratch = [0; MAX_PAYLOAD];
            response.clear();
            match protocol::decode(bytes, &mut scratch) {
                Ok((_, Message::Query)) => {
                    let first_frame = *accepted.borrow();
                    tracing::info!(
                        request,
                        ready = first_frame.is_some(),
                        "received graph query"
                    );
                    if let Some(first_frame) = first_frame {
                        snapshot(&graph, first_frame, request, &mut response)?;
                    } else {
                        append(&mut response, request, Message::Error(ErrorCode::NotReady))?;
                    }
                }
                _ => append(
                    &mut response,
                    request,
                    Message::Error(ErrorCode::Unsupported),
                )?,
            }
            stream.write_all(&response).await?;
        }
    }
}

fn append(response: &mut Vec<u8>, request: u32, message: Message<'_>) -> io::Result<()> {
    let mut frame = [0; MAX_FRAME];
    let size = protocol::encode(request, message, &mut frame).map_err(io::Error::other)?;
    response.push(u8::try_from(size).map_err(io::Error::other)?);
    response.extend_from_slice(&frame[..size]);
    Ok(())
}

fn snapshot(
    graph: &Graph,
    first_frame: u64,
    request: u32,
    response: &mut Vec<u8>,
) -> io::Result<()> {
    if !(1..=4096).contains(&graph.program.len()) || graph.outputs.len() > 16 {
        return Err(invalid("graph exceeds remote v1 bytecode or output limits"));
    }
    let meta = SnapshotMeta {
        session: graph.session,
        revision: graph.revision,
        first_frame,
        nodes: u8::try_from(graph.nodes.len())
            .map_err(|_| invalid("graph exceeds 255 remote nodes"))?,
        code_len: u16::try_from(graph.program.len()).map_err(io::Error::other)?,
    };
    append(
        response,
        request,
        Message::Begin {
            meta,
            outputs: &graph.outputs,
        },
    )?;
    let ports = |kinds: &[PortKind]| {
        kinds
            .iter()
            .map(|kind| u8::from(*kind == PortKind::Message))
            .collect::<Vec<_>>()
    };
    for node in &graph.nodes {
        append(response, request, Message::Node(NodeRef {
            id: node.id,
            generation: node.generation,
            alias: &node.alias,
            kind: &node.kind,
            midi_channel: node.midi_channel.map(|channel| channel.index()),
            inlets: &ports(&node.inlets),
            outlets: &ports(&node.outlets),
        })).map_err(|e| invalid(format!("cannot publish node '{}': {e} (remote aliases allow up to 32 ASCII alphanumeric characters)", node.alias)))?;
    }
    let mut offset = 0u16;
    for bytes in graph.program.chunks(MAX_PAYLOAD - 2) {
        append(response, request, Message::Code { offset, bytes })?;
        offset = offset.saturating_add(u16::try_from(bytes.len()).map_err(io::Error::other)?);
    }
    append(response, request, Message::End)
}

fn invalid(detail: impl Into<String>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, detail.into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::time::Duration;
    use std::env;
    use wavegraph_remote::{Channel, Client, Node, UnixTransport};

    fn graph() -> Graph {
        Graph {
            session: 9,
            revision: 1,
            first_frame: 0,
            nodes: vec![Node {
                id: 0,
                generation: 1,
                alias: "bass".into(),
                kind: "source".into(),
                midi_channel: Some(Channel::new(2).expect("channel 2")),
                inlets: vec![PortKind::Message],
                outlets: vec![PortKind::Signal],
            }],
            program: vec![wavegraph_core::bytecode::VERSION, 1, 0, 0, 1],
            outputs: vec![0, 0],
        }
    }

    #[tokio::test]
    async fn wr_queries_accepted_audio_and_sends_midi() -> io::Result<()> {
        let graph = graph();
        let (client, server) = std::os::unix::net::UnixStream::pair()?;
        server.set_nonblocking(true)?;
        let (commands, mut received) = mpsc::channel(2);
        let (first_frame, accepted) = watch::channel(None);
        let running = tokio::spawn(connection(
            UnixStream::from_std(server)?,
            Arc::new(graph.clone()),
            commands,
            accepted,
        ));
        let note = MidiCommand::NoteOn {
            channel: Channel::new(2)?,
            note: 60,
            velocity: 90,
        };
        tokio::task::spawn_blocking(move || -> io::Result<()> {
            let mut client = Client::new(UnixTransport::from(client));
            let timeout = Duration::from_secs(2);
            assert_eq!(
                client.graph(timeout).expect_err("unsubmitted audio").kind(),
                io::ErrorKind::WouldBlock
            );
            first_frame.send_replace(Some(128));
            assert_eq!(
                client.graph(timeout)?,
                Graph {
                    first_frame: 128,
                    ..graph
                }
            );
            client.send(note)
        })
        .await
        .map_err(io::Error::other)??;
        running.await.map_err(io::Error::other)??;
        assert_eq!(received.recv().await, Some(note));
        Ok(())
    }

    #[tokio::test]
    async fn listener_accepts_a_second_client_and_cleans_up_its_socket() -> io::Result<()> {
        let path = env::temp_dir().join(format!("wavegraph-test-{}.sock", std::process::id()));
        let (commands, mut received) = mpsc::channel(2);
        let (_, accepted) = watch::channel(None);
        let server = Server::bind(&path, graph(), commands.clone(), accepted.clone())?;
        assert!(Server::bind(&path, graph(), commands, accepted).is_err());
        let running = tokio::spawn(server.run());
        let idle = UnixStream::connect(&path).await?;
        let mut second = UnixStream::connect(&path).await?;
        second.write_all(&[1, 0xfc]).await?;
        assert_eq!(
            tokio::time::timeout(Duration::from_secs(2), received.recv()).await?,
            Some(MidiCommand::Stop)
        );
        drop(idle);
        running.abort();
        assert!(running.await.expect_err("aborted server").is_cancelled());
        assert!(!path.exists());
        Ok(())
    }
}