use std::{
io,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use agent_client_protocol::{
schema::ProtocolVersion, Channel, ConnectTo, ConnectionDriver, Error as AcpError, Lines, Role,
};
use blocking::Unblock;
use futures_util::{
io::{AsyncBufReadExt, AsyncRead, AsyncWriteExt, BufReader},
lock::Mutex as AsyncMutex,
Sink, Stream, StreamExt,
};
use super::initialize_screen::InitializeScreen;
pub(super) struct HostStdio {
shared: Arc<Shared>,
}
impl<R: Role> ConnectTo<R> for HostStdio {
async fn connect_to(self, client: impl ConnectTo<R::Counterpart>) -> Result<(), AcpError> {
let shared = Arc::clone(&self.shared);
shared.excuse(ConnectTo::<R>::connect_to(self.lines(), client).await)
}
fn into_channel_and_future(self) -> (Channel, Option<ConnectionDriver>) {
let shared = Arc::clone(&self.shared);
let (channel, driver) = ConnectTo::<R>::into_channel_and_future(self.lines());
let driver =
driver.map(|driver| driver.map_future(|work| async move { shared.excuse(work.await) }));
(channel, driver)
}
}
impl HostStdio {
pub(super) fn new(supported: &'static [ProtocolVersion]) -> Self {
Self {
shared: Arc::new(Shared {
stdout: AsyncMutex::new(Unblock::new(std::io::stdout())),
screen: InitializeScreen::new(supported),
hung_up: AtomicBool::new(false),
}),
}
}
fn lines(
self,
) -> Lines<
impl Sink<String, Error = io::Error> + Send + 'static,
impl Stream<Item = io::Result<String>> + Send + 'static,
> {
let incoming = lossy_lines(Unblock::new(std::io::stdin())).filter_map({
let shared = Arc::clone(&self.shared);
move |line| {
let shared = Arc::clone(&shared);
async move {
let line = match line {
Ok(line) => line,
Err(error) => return Some(Err(error)),
};
match shared.screen.incoming(&line) {
None => Some(Ok(line)),
Some(reply) => shared.write(reply).await.err().map(Err),
}
}
}
});
let outgoing = futures_util::sink::unfold(self.shared, |shared, line: String| async move {
shared.screen.outgoing(&line);
shared.write(line).await?;
Ok::<_, io::Error>(shared)
});
Lines::new(Box::pin(outgoing), Box::pin(incoming))
}
}
struct Shared {
stdout: AsyncMutex<Unblock<std::io::Stdout>>,
screen: InitializeScreen,
hung_up: AtomicBool,
}
impl Shared {
async fn write(&self, mut line: String) -> io::Result<()> {
line.push('\n');
let mut stdout = self.stdout.lock().await;
let mut written = stdout.write_all(line.as_bytes()).await;
if written.is_ok() {
written = stdout.flush().await;
}
if written
.as_ref()
.is_err_and(|error| error.kind() == io::ErrorKind::BrokenPipe)
{
self.hung_up.store(true, Ordering::Release);
}
written
}
fn excuse(&self, result: Result<(), AcpError>) -> Result<(), AcpError> {
match result {
Err(error) if self.hung_up.load(Ordering::Acquire) => {
tracing::debug!(%error, "the ACP host hung up; ending the connection");
Ok(())
}
other => other,
}
}
}
fn lossy_lines(
reader: impl AsyncRead + Send + 'static,
) -> impl Stream<Item = io::Result<String>> + Send + 'static {
let reader = Box::pin(BufReader::new(reader));
futures_util::stream::try_unfold(reader, |mut reader| async move {
let mut line = Vec::new();
if reader.read_until(b'\n', &mut line).await? == 0 {
return Ok(None);
}
if line.last() == Some(&b'\n') {
line.pop();
if line.last() == Some(&b'\r') {
line.pop();
}
}
Ok(Some((String::from_utf8_lossy(&line).into_owned(), reader)))
})
}