muse_code_sdk/connection/stdio.rs
1use std::future::Future;
2use std::io;
3use std::pin::Pin;
4
5use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
6use tokio::process::{ChildStdin, ChildStdout};
7
8use crate::DuplexTransport;
9
10/// The newline-framed MSP transport over a spawned host's stdin and stdout.
11///
12/// Hand it the pipes from [`MuseChild::take_stdin`] and
13/// [`MuseChild::take_stdout`], and [`Connection::new`] gives you a raw
14/// connection to that host. [`MuseClient::spawn`] uses this same transport.
15///
16/// The transport owns the host's stdin, so close the connection before
17/// [`MuseChild::close`]: closing it sends the host EOF, and the host exits.
18/// Closing the host first sends no EOF, so it waits out the shutdown timeout
19/// and then ends the host by signal.
20///
21/// ```no_run
22/// use muse_code_sdk::connection::{Connection, StdioTransport};
23/// use muse_code_sdk::spawn::{SpawnOptions, spawn_muse};
24///
25/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
26/// let mut host = spawn_muse(SpawnOptions::default())?;
27/// let (stdin, stdout) = (host.take_stdin(), host.take_stdout());
28/// let transport = StdioTransport::new(stdin.ok_or("no stdin")?, stdout.ok_or("no stdout")?);
29/// let (connection, driver) = Connection::new(transport);
30/// tokio::spawn(driver.run());
31/// // ... the handshake, then requests ...
32/// connection.close().await;
33/// host.close().await?;
34/// # Ok(())
35/// # }
36/// ```
37///
38/// [`MuseChild::take_stdin`]: crate::spawn::MuseChild::take_stdin
39/// [`MuseChild::take_stdout`]: crate::spawn::MuseChild::take_stdout
40/// [`MuseChild::close`]: crate::spawn::MuseChild::close
41/// [`Connection::new`]: crate::connection::Connection::new
42/// [`MuseClient::spawn`]: crate::client::MuseClient::spawn
43#[derive(Debug)]
44pub struct StdioTransport {
45 pipes: PipeTransport<ChildStdin, ChildStdout>,
46}
47
48impl StdioTransport {
49 /// Wraps a spawned host's stdin and stdout.
50 #[must_use]
51 pub fn new(stdin: ChildStdin, stdout: ChildStdout) -> Self {
52 Self {
53 pipes: PipeTransport::new(stdin, stdout),
54 }
55 }
56}
57
58impl DuplexTransport for StdioTransport {
59 fn read_chunk(
60 &mut self,
61 ) -> Pin<Box<dyn Future<Output = io::Result<Option<String>>> + Send + '_>> {
62 self.pipes.read_chunk()
63 }
64
65 fn write(&mut self, frame: &str) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>> {
66 self.pipes.write(frame)
67 }
68}
69
70/// The stdio transport's framing, generic over the pipe halves so tests can
71/// drive it over in-memory pipes. [`StdioTransport`] is this over a child's
72/// stdin and stdout.
73#[derive(Debug)]
74pub(crate) struct PipeTransport<W, R> {
75 stdin: W,
76 stdout: BufReader<R>,
77 /// Bytes already taken out of `stdout` that do not yet end on a UTF-8
78 /// boundary. They live on the transport, not in a read future, so a read
79 /// the driver drops in favour of an outbound write loses nothing.
80 held: Vec<u8>,
81}
82
83impl<W, R> PipeTransport<W, R>
84where
85 W: AsyncWrite + Unpin + Send,
86 R: AsyncRead + Unpin + Send,
87{
88 pub(crate) fn new(stdin: W, stdout: R) -> Self {
89 Self {
90 stdin,
91 stdout: BufReader::new(stdout),
92 held: Vec::new(),
93 }
94 }
95}
96
97impl<W, R> DuplexTransport for PipeTransport<W, R>
98where
99 W: AsyncWrite + Unpin + Send,
100 R: AsyncRead + Unpin + Send,
101{
102 fn read_chunk(
103 &mut self,
104 ) -> Pin<Box<dyn Future<Output = io::Result<Option<String>>> + Send + '_>> {
105 Box::pin(async move {
106 loop {
107 // `fill_buf` is cancel safe: a read dropped here leaves every
108 // byte inside the reader, unlike `read_line`, whose dropped
109 // future takes the bytes it already copied out with it.
110 let available = self.stdout.fill_buf().await?;
111 if available.is_empty() {
112 return if self.held.is_empty() {
113 Ok(None)
114 } else {
115 Err(io::Error::new(
116 io::ErrorKind::InvalidData,
117 "inbound stream ended inside a UTF-8 sequence",
118 ))
119 };
120 }
121 let pulled = available.len();
122 self.held.extend_from_slice(available);
123 self.stdout.consume(pulled);
124 if let Some(chunk) = take_complete_utf8(&mut self.held)? {
125 return Ok(Some(chunk));
126 }
127 }
128 })
129 }
130
131 fn write(&mut self, frame: &str) -> Pin<Box<dyn Future<Output = io::Result<()>> + Send + '_>> {
132 let frame = frame.as_bytes().to_vec();
133 Box::pin(async move {
134 self.stdin.write_all(&frame).await?;
135 self.stdin.flush().await
136 })
137 }
138}
139
140/// Splits the longest complete UTF-8 prefix off `bytes`, leaving a trailing
141/// partial sequence behind for the next read. `None` means nothing complete
142/// has arrived yet; invalid UTF-8 is an error, as it was for `read_line`.
143fn take_complete_utf8(bytes: &mut Vec<u8>) -> io::Result<Option<String>> {
144 let complete = match std::str::from_utf8(bytes) {
145 Ok(_) => bytes.len(),
146 Err(error) if error.error_len().is_none() => error.valid_up_to(),
147 Err(error) => return Err(io::Error::new(io::ErrorKind::InvalidData, error)),
148 };
149 if complete == 0 {
150 return Ok(None);
151 }
152 let rest = bytes.split_off(complete);
153 let chunk = std::mem::replace(bytes, rest);
154 String::from_utf8(chunk)
155 .map(Some)
156 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
157}