use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc;
use crate::proto::{JsonRpcNotification, JsonRpcResponse};
#[derive(Debug)]
pub enum Outgoing {
Response(Box<JsonRpcResponse>),
Notification(Box<JsonRpcNotification>),
}
impl Outgoing {
#[must_use]
pub fn response(response: JsonRpcResponse) -> Self {
Self::Response(Box::new(response))
}
#[must_use]
pub fn notification(notification: JsonRpcNotification) -> Self {
Self::Notification(Box::new(notification))
}
fn to_line(&self) -> Result<String, serde_json::Error> {
match self {
Self::Response(response) => serde_json::to_string(response),
Self::Notification(notification) => serde_json::to_string(notification),
}
}
}
pub const CHANNEL_CAPACITY: usize = 1024;
pub async fn run<W>(mut writer: W, mut rx: mpsc::Receiver<Outgoing>)
where
W: AsyncWrite + Unpin,
{
while let Some(message) = rx.recv().await {
let line = match message.to_line() {
Ok(line) => line,
Err(error) => {
tracing::error!(error = ?error, "Failed to serialize outgoing message.");
continue;
}
};
debug_assert!(
!line.contains('\n'),
"serialized message contains a raw newline"
);
if let Err(error) = writer.write_all(line.as_bytes()).await {
tracing::error!(error = ?error, "Failed to write to stdout.");
return;
}
if let Err(error) = writer.write_all(b"\n").await {
tracing::error!(error = ?error, "Failed to write message delimiter.");
return;
}
if let Err(error) = writer.flush().await {
tracing::error!(error = ?error, "Failed to flush stdout.");
return;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::proto::JsonRpcResponse;
#[tokio::test]
async fn writes_one_line_per_message() {
let (tx, rx) = mpsc::channel(8);
let mut buffer = Vec::new();
tx.send(Outgoing::response(JsonRpcResponse::success(
serde_json::json!(1),
serde_json::json!({ "resultType": "complete" }),
)))
.await
.unwrap();
tx.send(Outgoing::notification(JsonRpcNotification::new(
"notifications/progress",
serde_json::json!({ "progressToken": "t", "progress": 1 }),
)))
.await
.unwrap();
drop(tx);
run(&mut buffer, rx).await;
let text = String::from_utf8(buffer).unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[0].contains("\"id\":1"));
assert!(lines[1].contains("notifications/progress"));
}
#[tokio::test]
async fn embedded_newlines_are_escaped_not_emitted() {
let (tx, rx) = mpsc::channel(8);
let mut buffer = Vec::new();
tx.send(Outgoing::response(JsonRpcResponse::success(
serde_json::json!(1),
serde_json::json!({ "text": "first\nsecond\nthird" }),
)))
.await
.unwrap();
drop(tx);
run(&mut buffer, rx).await;
let text = String::from_utf8(buffer).unwrap();
assert_eq!(text.matches('\n').count(), 1);
assert!(text.contains("first\\nsecond\\nthird"));
}
#[tokio::test]
async fn returns_when_all_senders_drop() {
let (tx, rx) = mpsc::channel::<Outgoing>(1);
drop(tx);
tokio::time::timeout(std::time::Duration::from_secs(1), run(Vec::new(), rx))
.await
.expect("writer exits on channel close");
}
}