wavegraph-remote 0.1.0

MIDI control and live graph discovery for WaveGraph
Documentation
use crate::{
    Channel, Graph, MidiCommand, Node, PortKind,
    graph::invalid,
    protocol::{self, ErrorCode, Message, SnapshotMeta},
};
use alloc::vec::Vec;
use core::{hash::BuildHasher as _, time::Duration};
use std::{collections::hash_map::RandomState, io, time::Instant};

/// Bidirectional transport carrying complete MIDI messages.
///
/// Implementations supply message boundaries and bounded receive waits. A local
/// socket implementation can length-prefix the same messages; an in-process
/// implementation can pass them directly. No terminal behavior is required.
pub trait Transport {
    /// Submit one complete MIDI message.
    ///
    /// # Errors
    /// Returns an I/O error if the message cannot be submitted.
    fn send(&mut self, message: &[u8]) -> io::Result<()>;

    /// Receive one complete message, waiting at most `timeout`.
    ///
    /// # Errors
    /// Returns `TimedOut` on expiry, or a transport error on failure/disconnect.
    fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>>;
}

/// A transport-independent MIDI controller and graph-discovery client.
#[derive(Debug)]
pub struct Client<T> {
    transport: T,
    request: u32,
}

impl<T: Transport> Client<T> {
    /// Start a client with a randomized request-ID seed for reply correlation.
    /// Request IDs are not authentication credentials.
    #[must_use]
    pub fn new(transport: T) -> Self {
        let seed = RandomState::new().hash_one(Instant::now()) & u64::from(u32::MAX);
        Self {
            transport,
            request: u32::try_from(seed).unwrap_or_default(),
        }
    }

    /// Return the owned transport.
    #[must_use]
    pub fn into_transport(self) -> T {
        self.transport
    }

    /// Send an ordinary MIDI command, validating data bytes before transmission.
    ///
    /// This confirms transport submission only. It does not wait for audio
    /// application, and ordinary MIDI commands have no remote completion receipt.
    ///
    /// # Errors
    /// Returns an error for invalid MIDI values or a failed transport send.
    pub fn send(&mut self, command: MidiCommand) -> io::Result<()> {
        let mut bytes = [0; 3];
        let len = command.encode(&mut bytes)?;
        self.transport.send(&bytes[..len])
    }

    /// Query a complete, coherent graph snapshot within a total time budget.
    ///
    /// Unrelated MIDI and replies to other requests are ignored. Missing,
    /// duplicated, out-of-order and malformed records fail the whole query.
    /// Every call starts fresh; a failed snapshot never replaces a caller's graph.
    ///
    /// # Errors
    /// Returns `TimedOut` when no complete snapshot arrives (including firmware
    /// without this protocol), a target rejection, or invalid-data/transport errors.
    pub fn graph(&mut self, timeout: Duration) -> io::Result<Graph> {
        let deadline = Instant::now()
            .checked_add(timeout)
            .filter(|_| !timeout.is_zero())
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "timeout must be finite and nonzero",
                )
            })?;
        self.request = self.request.wrapping_add(1);
        let request = self.request;
        let mut frame = [0; protocol::MAX_FRAME];
        let length =
            protocol::encode(request, Message::Query, &mut frame).map_err(invalid_protocol)?;
        self.transport.send(&frame[..length])?;
        let mut scratch = [0; protocol::MAX_PAYLOAD];
        let mut snapshot: Option<Snapshot> = None;
        loop {
            let remaining = deadline
                .checked_duration_since(Instant::now())
                .filter(|wait| !wait.is_zero())
                .ok_or_else(timed_out)?;
            let bytes = self.transport.receive(remaining).map_err(|error| {
                if error.kind() == io::ErrorKind::TimedOut {
                    timed_out()
                } else {
                    error
                }
            })?;
            if !protocol::is_remote(&bytes) {
                continue;
            }
            if protocol::request_id(&bytes).map_err(invalid_protocol)? != request {
                continue;
            }
            let (reply, message) =
                protocol::decode(&bytes, &mut scratch).map_err(invalid_protocol)?;
            if reply != request {
                continue;
            }
            match message {
                Message::Begin { meta, outputs } => {
                    if snapshot.is_some()
                        || meta.code_len == 0
                        || meta.code_len > 4096
                        || outputs.len() > 16
                    {
                        return Err(invalid("invalid or duplicate graph snapshot header"));
                    }
                    snapshot = Some(Snapshot {
                        meta,
                        graph: Graph {
                            session: meta.session,
                            revision: meta.revision,
                            first_frame: meta.first_frame,
                            nodes: Vec::with_capacity(usize::from(meta.nodes)),
                            program: Vec::with_capacity(usize::from(meta.code_len)),
                            outputs: outputs.to_vec(),
                        },
                    });
                }
                Message::Node(node) => {
                    let snapshot = snapshot
                        .as_mut()
                        .ok_or_else(|| invalid("node arrived before snapshot header"))?;
                    if snapshot.graph.nodes.len() >= usize::from(snapshot.meta.nodes)
                        || !snapshot.graph.program.is_empty()
                        || snapshot
                            .graph
                            .nodes
                            .iter()
                            .any(|old| old.id == node.id || old.alias == node.alias)
                    {
                        return Err(invalid("unexpected or duplicate graph node"));
                    }
                    let midi_channel = node
                        .midi_channel
                        .map(|channel| Channel::new(channel.saturating_add(1)))
                        .transpose()?;
                    let ports = |bytes: &[u8]| {
                        bytes
                            .iter()
                            .map(|kind| {
                                if *kind == 0 {
                                    PortKind::Signal
                                } else {
                                    PortKind::Message
                                }
                            })
                            .collect()
                    };
                    snapshot.graph.nodes.push(Node {
                        id: node.id,
                        generation: node.generation,
                        alias: node.alias.into(),
                        kind: node.kind.into(),
                        midi_channel,
                        inlets: ports(node.inlets),
                        outlets: ports(node.outlets),
                    });
                }
                Message::Code { offset, bytes } => {
                    let snapshot = snapshot
                        .as_mut()
                        .ok_or_else(|| invalid("bytecode arrived before snapshot header"))?;
                    if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
                        || usize::from(offset) != snapshot.graph.program.len()
                        || snapshot.graph.program.len().saturating_add(bytes.len())
                            > usize::from(snapshot.meta.code_len)
                    {
                        return Err(invalid(
                            "missing, reordered, or oversized graph bytecode chunk",
                        ));
                    }
                    snapshot.graph.program.extend_from_slice(bytes);
                }
                Message::End => {
                    let snapshot =
                        snapshot.ok_or_else(|| invalid("snapshot ended before its header"))?;
                    if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
                        || snapshot.graph.program.len() != usize::from(snapshot.meta.code_len)
                    {
                        return Err(invalid("incomplete graph snapshot"));
                    }
                    snapshot.graph.connections()?;
                    return Ok(snapshot.graph);
                }
                Message::Error(code) => {
                    return Err(match code {
                        ErrorCode::Busy => io::Error::new(
                            io::ErrorKind::WouldBlock,
                            "WaveGraph is serving another graph query; retry",
                        ),
                        ErrorCode::NotReady => io::Error::new(
                            io::ErrorKind::WouldBlock,
                            "WaveGraph has not accepted an audio block yet",
                        ),
                        ErrorCode::Unsupported => io::Error::new(
                            io::ErrorKind::Unsupported,
                            "WaveGraph does not support this query",
                        ),
                    });
                }
                Message::Query => {
                    return Err(invalid("received a query instead of a graph response"));
                }
            }
        }
    }
}

struct Snapshot {
    meta: SnapshotMeta,
    graph: Graph,
}

fn invalid_protocol(error: protocol::ProtocolError) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, error)
}

fn timed_out() -> io::Error {
    io::Error::new(
        io::ErrorKind::TimedOut,
        "no complete WaveGraph snapshot; install firmware with wavegraph-remote support or increase the timeout",
    )
}