wavegraph_remote/
client.rs1use crate::{
2 Channel, Graph, MidiCommand, Node, PortKind,
3 graph::invalid,
4 protocol::{self, ErrorCode, Message, SnapshotMeta},
5};
6use alloc::vec::Vec;
7use core::{hash::BuildHasher as _, time::Duration};
8use std::{collections::hash_map::RandomState, io, time::Instant};
9
10pub trait Transport {
16 fn send(&mut self, message: &[u8]) -> io::Result<()>;
21
22 fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>>;
27}
28
29#[derive(Debug)]
31pub struct Client<T> {
32 transport: T,
33 request: u32,
34}
35
36impl<T: Transport> Client<T> {
37 #[must_use]
40 pub fn new(transport: T) -> Self {
41 let seed = RandomState::new().hash_one(Instant::now()) & u64::from(u32::MAX);
42 Self {
43 transport,
44 request: u32::try_from(seed).unwrap_or_default(),
45 }
46 }
47
48 #[must_use]
50 pub fn into_transport(self) -> T {
51 self.transport
52 }
53
54 pub fn send(&mut self, command: MidiCommand) -> io::Result<()> {
62 let mut bytes = [0; 3];
63 let len = command.encode(&mut bytes)?;
64 self.transport.send(&bytes[..len])
65 }
66
67 pub fn graph(&mut self, timeout: Duration) -> io::Result<Graph> {
77 let deadline = Instant::now()
78 .checked_add(timeout)
79 .filter(|_| !timeout.is_zero())
80 .ok_or_else(|| {
81 io::Error::new(
82 io::ErrorKind::InvalidInput,
83 "timeout must be finite and nonzero",
84 )
85 })?;
86 self.request = self.request.wrapping_add(1);
87 let request = self.request;
88 let mut frame = [0; protocol::MAX_FRAME];
89 let length =
90 protocol::encode(request, Message::Query, &mut frame).map_err(invalid_protocol)?;
91 self.transport.send(&frame[..length])?;
92 let mut scratch = [0; protocol::MAX_PAYLOAD];
93 let mut snapshot: Option<Snapshot> = None;
94 loop {
95 let remaining = deadline
96 .checked_duration_since(Instant::now())
97 .filter(|wait| !wait.is_zero())
98 .ok_or_else(timed_out)?;
99 let bytes = self.transport.receive(remaining).map_err(|error| {
100 if error.kind() == io::ErrorKind::TimedOut {
101 timed_out()
102 } else {
103 error
104 }
105 })?;
106 if !protocol::is_remote(&bytes) {
107 continue;
108 }
109 if protocol::request_id(&bytes).map_err(invalid_protocol)? != request {
110 continue;
111 }
112 let (reply, message) =
113 protocol::decode(&bytes, &mut scratch).map_err(invalid_protocol)?;
114 if reply != request {
115 continue;
116 }
117 match message {
118 Message::Begin { meta, outputs } => {
119 if snapshot.is_some()
120 || meta.code_len == 0
121 || meta.code_len > 4096
122 || outputs.len() > 16
123 {
124 return Err(invalid("invalid or duplicate graph snapshot header"));
125 }
126 snapshot = Some(Snapshot {
127 meta,
128 graph: Graph {
129 session: meta.session,
130 revision: meta.revision,
131 first_frame: meta.first_frame,
132 nodes: Vec::with_capacity(usize::from(meta.nodes)),
133 program: Vec::with_capacity(usize::from(meta.code_len)),
134 outputs: outputs.to_vec(),
135 },
136 });
137 }
138 Message::Node(node) => {
139 let snapshot = snapshot
140 .as_mut()
141 .ok_or_else(|| invalid("node arrived before snapshot header"))?;
142 if snapshot.graph.nodes.len() >= usize::from(snapshot.meta.nodes)
143 || !snapshot.graph.program.is_empty()
144 || snapshot
145 .graph
146 .nodes
147 .iter()
148 .any(|old| old.id == node.id || old.alias == node.alias)
149 {
150 return Err(invalid("unexpected or duplicate graph node"));
151 }
152 let midi_channel = node
153 .midi_channel
154 .map(|channel| Channel::new(channel.saturating_add(1)))
155 .transpose()?;
156 let ports = |bytes: &[u8]| {
157 bytes
158 .iter()
159 .map(|kind| {
160 if *kind == 0 {
161 PortKind::Signal
162 } else {
163 PortKind::Message
164 }
165 })
166 .collect()
167 };
168 snapshot.graph.nodes.push(Node {
169 id: node.id,
170 generation: node.generation,
171 alias: node.alias.into(),
172 kind: node.kind.into(),
173 midi_channel,
174 inlets: ports(node.inlets),
175 outlets: ports(node.outlets),
176 });
177 }
178 Message::Code { offset, bytes } => {
179 let snapshot = snapshot
180 .as_mut()
181 .ok_or_else(|| invalid("bytecode arrived before snapshot header"))?;
182 if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
183 || usize::from(offset) != snapshot.graph.program.len()
184 || snapshot.graph.program.len().saturating_add(bytes.len())
185 > usize::from(snapshot.meta.code_len)
186 {
187 return Err(invalid(
188 "missing, reordered, or oversized graph bytecode chunk",
189 ));
190 }
191 snapshot.graph.program.extend_from_slice(bytes);
192 }
193 Message::End => {
194 let snapshot =
195 snapshot.ok_or_else(|| invalid("snapshot ended before its header"))?;
196 if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
197 || snapshot.graph.program.len() != usize::from(snapshot.meta.code_len)
198 {
199 return Err(invalid("incomplete graph snapshot"));
200 }
201 snapshot.graph.connections()?;
202 return Ok(snapshot.graph);
203 }
204 Message::Error(code) => {
205 return Err(match code {
206 ErrorCode::Busy => io::Error::new(
207 io::ErrorKind::WouldBlock,
208 "WaveGraph is serving another graph query; retry",
209 ),
210 ErrorCode::NotReady => io::Error::new(
211 io::ErrorKind::WouldBlock,
212 "WaveGraph has not accepted an audio block yet",
213 ),
214 ErrorCode::Unsupported => io::Error::new(
215 io::ErrorKind::Unsupported,
216 "WaveGraph does not support this query",
217 ),
218 });
219 }
220 Message::Query => {
221 return Err(invalid("received a query instead of a graph response"));
222 }
223 }
224 }
225 }
226}
227
228struct Snapshot {
229 meta: SnapshotMeta,
230 graph: Graph,
231}
232
233fn invalid_protocol(error: protocol::ProtocolError) -> io::Error {
234 io::Error::new(io::ErrorKind::InvalidData, error)
235}
236
237fn timed_out() -> io::Error {
238 io::Error::new(
239 io::ErrorKind::TimedOut,
240 "no complete WaveGraph snapshot; install firmware with wavegraph-remote support or increase the timeout",
241 )
242}