wavegraph-remote 0.1.0

MIDI control and live graph discovery for WaveGraph
Documentation
//! Client, MIDI validation and signal-graph reconstruction tests.
#![cfg(feature = "std")]

extern crate alloc;

use alloc::collections::VecDeque;
use core::time::Duration;
use std::io;
use wavegraph_remote::{
    Channel, Client, Graph, MidiCommand, Node, PortKind, Transport,
    protocol::{self, ErrorCode, MAX_FRAME, MAX_PAYLOAD, Message, NodeRef, SnapshotMeta},
};

const PROGRAM: [u8; 8] = [1, 1, 0, 0, 1, 2, 0, 64];

#[derive(Clone, Copy, Debug, Default)]
enum Fault {
    #[default]
    None,
    MissingEnd,
    DuplicateNode,
    MissingCode,
    ReorderedCode,
    InvalidGraph,
    Unsupported,
    Busy,
    ForeignInvalid,
}

#[derive(Debug, Default)]
struct Peer {
    sent: Vec<Vec<u8>>,
    replies: VecDeque<Vec<u8>>,
    fault: Fault,
}

fn frame(request: u32, message: Message<'_>) -> Vec<u8> {
    let mut bytes = [0; MAX_FRAME];
    let len = protocol::encode(request, message, &mut bytes).expect("fixture record");
    bytes[..len].to_vec()
}

impl Transport for Peer {
    fn send(&mut self, bytes: &[u8]) -> io::Result<()> {
        self.sent.push(bytes.into());
        if !protocol::is_remote(bytes) {
            return Ok(());
        }
        let (request, Message::Query) =
            protocol::decode(bytes, &mut [0; MAX_PAYLOAD]).map_err(io::Error::other)?
        else {
            return Err(io::Error::other("unexpected request"));
        };
        let mut code = PROGRAM;
        if matches!(self.fault, Fault::InvalidGraph) {
            code[6] = 255;
        }
        let push =
            |queue: &mut VecDeque<Vec<u8>>, message| queue.push_back(frame(request, message));
        if matches!(self.fault, Fault::Unsupported | Fault::Busy) {
            push(
                &mut self.replies,
                Message::Error(if matches!(self.fault, Fault::Busy) {
                    ErrorCode::Busy
                } else {
                    ErrorCode::Unsupported
                }),
            );
            return Ok(());
        }
        self.replies.push_back(vec![0x90, 60, 100]);
        self.replies
            .push_back(frame(request.wrapping_sub(1), Message::End));
        if matches!(self.fault, Fault::ForeignInvalid) {
            let mut other = frame(request.wrapping_sub(1), Message::Query);
            other[4] = 99;
            other[5] = 99;
            self.replies.push_back(other);
        }
        push(
            &mut self.replies,
            Message::Begin {
                meta: SnapshotMeta {
                    session: 7,
                    revision: 3,
                    first_frame: 1024,
                    nodes: 1,
                    code_len: 8,
                },
                outputs: &[1],
            },
        );
        let node = Message::Node(NodeRef {
            id: 0,
            generation: 8,
            alias: "tb303",
            kind: "wavegraph-303",
            midi_channel: Some(2),
            inlets: &[1],
            outlets: &[0, 1],
        });
        push(&mut self.replies, node);
        if matches!(self.fault, Fault::DuplicateNode) {
            push(&mut self.replies, node);
        }
        if !matches!(self.fault, Fault::MissingCode) {
            push(
                &mut self.replies,
                Message::Code {
                    offset: if matches!(self.fault, Fault::ReorderedCode) {
                        1
                    } else {
                        0
                    },
                    bytes: &code[..4],
                },
            );
            push(
                &mut self.replies,
                Message::Code {
                    offset: 4,
                    bytes: &code[4..],
                },
            );
        }
        if !matches!(self.fault, Fault::MissingEnd) {
            push(&mut self.replies, Message::End);
        }
        Ok(())
    }

    fn receive(&mut self, _: Duration) -> io::Result<Vec<u8>> {
        self.replies
            .pop_front()
            .ok_or_else(|| io::Error::from(io::ErrorKind::TimedOut))
    }
}

#[test]
fn coherent_snapshot_ignores_unrelated_midi_and_preserves_real_gain_route() {
    let mut client = Client::new(Peer::default());
    let graph = client
        .graph(Duration::from_secs(1))
        .expect("complete snapshot");
    assert_eq!(
        (graph.session, graph.revision, graph.first_frame),
        (7, 3, 1024)
    );
    assert_eq!(graph.program, PROGRAM);
    assert_eq!(
        graph
            .node("tb303")
            .expect("alias")
            .midi_channel
            .expect("channel")
            .number(),
        3
    );
    assert_eq!(graph.node("tb303").expect("alias").generation, 8);
    let edges = graph.connections().expect("validated program");
    assert_eq!(edges.len(), 2);
    assert_eq!(edges[0].source, "tb303.out0");
    assert!(edges[0].destination.starts_with("@gain1"));
    assert_eq!(edges[1].destination, "output0");
}

#[test]
fn malformed_incomplete_or_out_of_order_snapshots_fail_atomically() {
    for fault in [
        Fault::MissingEnd,
        Fault::DuplicateNode,
        Fault::MissingCode,
        Fault::ReorderedCode,
        Fault::InvalidGraph,
    ] {
        let mut client = Client::new(Peer {
            fault,
            ..Peer::default()
        });
        let error = client
            .graph(Duration::from_secs(1))
            .expect_err("invalid snapshot");
        assert!(matches!(
            error.kind(),
            io::ErrorKind::TimedOut | io::ErrorKind::InvalidData
        ));
        let mut peer = client.into_transport();
        peer.fault = Fault::None;
        // Old queued records must not contaminate the next client/query.
        assert!(Client::new(peer).graph(Duration::from_secs(1)).is_ok());
    }
}

#[test]
fn target_rejections_and_foreign_invalid_replies_are_distinct() {
    for (fault, expected) in [
        (Fault::Busy, io::ErrorKind::WouldBlock),
        (Fault::Unsupported, io::ErrorKind::Unsupported),
    ] {
        let mut client = Client::new(Peer {
            fault,
            ..Peer::default()
        });
        assert_eq!(
            client
                .graph(Duration::from_secs(1))
                .expect_err("target error")
                .kind(),
            expected
        );
    }
    let mut client = Client::new(Peer {
        fault: Fault::ForeignInvalid,
        ..Peer::default()
    });
    assert!(client.graph(Duration::from_secs(1)).is_ok());
}

#[test]
fn invalid_timeout_sends_nothing() {
    let mut client = Client::new(Peer::default());
    for timeout in [Duration::ZERO, Duration::MAX] {
        assert_eq!(
            client.graph(timeout).expect_err("invalid timeout").kind(),
            io::ErrorKind::InvalidInput
        );
    }
    assert!(client.into_transport().sent.is_empty());
}

#[test]
fn midi_channels_and_data_are_validated_before_sending() {
    assert!(Channel::new(0).is_err());
    assert!(Channel::new(17).is_err());
    let mut client = Client::new(Peer::default());
    for number in 1..=16 {
        let channel = Channel::new(number).expect("channel");
        client
            .send(MidiCommand::NoteOn {
                channel,
                note: 36,
                velocity: 110,
            })
            .expect("note");
        client
            .send(MidiCommand::NoteOff { channel, note: 36 })
            .expect("release");
    }
    let channel = Channel::new(3).expect("channel");
    for command in [
        MidiCommand::NoteOn {
            channel,
            note: 128,
            velocity: 100,
        },
        MidiCommand::NoteOn {
            channel,
            note: 36,
            velocity: 0,
        },
        MidiCommand::NoteOff { channel, note: 255 },
        MidiCommand::ControlChange {
            channel,
            controller: 200,
            value: 0,
        },
        MidiCommand::ControlChange {
            channel,
            controller: 74,
            value: 128,
        },
    ] {
        assert_eq!(
            client.send(command).expect_err("invalid MIDI").kind(),
            io::ErrorKind::InvalidInput
        );
    }
    client.send(MidiCommand::Play).expect("play");
    client.send(MidiCommand::Stop).expect("stop");
    client
        .send(MidiCommand::AllNotesOff { channel })
        .expect("release channel");
    let sent = client.into_transport().sent;
    assert_eq!(sent.len(), 35);
    for (index, pair) in sent[..32].chunks(2).enumerate() {
        let index = u8::try_from(index).expect("sixteen channels");
        assert_eq!(pair[0], [0x90 | index, 36, 110]);
        assert_eq!(pair[1], [0x80 | index, 36, 64]);
    }
    assert_eq!(sent[32], [0xfa]);
    assert_eq!(sent[33], [0xfc]);
    assert_eq!(sent[34], [0xb2, 123, 0]);
}

#[test]
fn graph_connections_use_local_port_indices_including_message_ports() {
    let mut graph = Graph {
        session: 0,
        revision: 0,
        first_frame: 0,
        nodes: vec![
            Node {
                id: 0,
                generation: 0,
                alias: "source".into(),
                kind: "test".into(),
                midi_channel: None,
                inlets: vec![],
                outlets: vec![PortKind::Message, PortKind::Signal],
            },
            Node {
                id: 1,
                generation: 0,
                alias: "sink".into(),
                kind: "test".into(),
                midi_channel: None,
                inlets: vec![PortKind::Message, PortKind::Signal],
                outlets: vec![PortKind::Signal],
            },
        ],
        program: vec![1, 1, 0, 0, 1, 1, 1, 1, 1, 0],
        outputs: vec![1],
    };
    let edges = graph.connections().expect("graph");
    assert_eq!(edges[0].source, "source.out1");
    assert_eq!(edges[0].destination, "sink.in1");
    graph.outputs = vec![255];
    assert!(graph.connections().is_err());
    graph.outputs = vec![1];
    graph.nodes[1].id = 0;
    assert!(graph.connections().is_err());
}