1use std::time::Duration;
2
3use serde::Serialize;
4use tokio::io::{AsyncWrite, AsyncWriteExt as _};
5use tokio::sync::{mpsc, oneshot};
6
7use super::reader::MAX_RPC_FRAME_BYTES;
8
9pub const RPC_WRITER_QUEUE_CAPACITY: usize = 32;
11pub const RPC_WRITER_DEADLINE: Duration = Duration::from_millis(500);
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16pub enum RpcWriteError {
17 #[error("RPC output value is invalid")]
19 InvalidValue,
20 #[error("RPC output is closed")]
22 Closed,
23 #[error("RPC output deadline exceeded")]
25 Deadline,
26}
27
28struct WriteRequest {
29 line: Vec<u8>,
30 acknowledgement: oneshot::Sender<Result<(), RpcWriteError>>,
31}
32
33#[derive(Debug)]
35pub struct RpcLineWriter {
36 sender: Option<mpsc::Sender<WriteRequest>>,
37 task: tokio::task::JoinHandle<Result<(), RpcWriteError>>,
38 deadline: Duration,
39}
40
41impl RpcLineWriter {
42 #[must_use]
44 pub fn spawn<W>(output: W) -> Self
45 where
46 W: AsyncWrite + Unpin + Send + 'static,
47 {
48 Self::spawn_with_deadline(output, RPC_WRITER_DEADLINE)
49 }
50
51 #[must_use]
53 pub fn spawn_with_deadline<W>(output: W, deadline: Duration) -> Self
54 where
55 W: AsyncWrite + Unpin + Send + 'static,
56 {
57 let (sender, receiver) = mpsc::channel(RPC_WRITER_QUEUE_CAPACITY);
58 let task = tokio::spawn(writer_loop(output, receiver, deadline));
59 Self {
60 sender: Some(sender),
61 task,
62 deadline,
63 }
64 }
65
66 pub async fn write<T: Serialize>(&self, value: &T) -> Result<(), RpcWriteError> {
72 let line = encode_line(value)?;
73 let (acknowledgement, received) = oneshot::channel();
74 let request = WriteRequest {
75 line,
76 acknowledgement,
77 };
78 let sender = self.sender.as_ref().ok_or(RpcWriteError::Closed)?;
79 tokio::time::timeout(self.deadline, sender.send(request))
80 .await
81 .map_err(|_| RpcWriteError::Deadline)?
82 .map_err(|_| RpcWriteError::Closed)?;
83 tokio::time::timeout(self.deadline, received)
84 .await
85 .map_err(|_| RpcWriteError::Deadline)?
86 .map_err(|_| RpcWriteError::Closed)?
87 }
88
89 pub async fn shutdown(mut self) -> Result<(), RpcWriteError> {
95 self.sender.take();
96 tokio::time::timeout(self.deadline, &mut self.task)
97 .await
98 .map_err(|_| {
99 self.task.abort();
100 RpcWriteError::Deadline
101 })?
102 .map_err(|_| RpcWriteError::Closed)?
103 }
104}
105
106fn encode_line<T: Serialize>(value: &T) -> Result<Vec<u8>, RpcWriteError> {
107 let mut line = serde_json::to_vec(value).map_err(|_| RpcWriteError::InvalidValue)?;
108 if line.is_empty()
109 || line.len() > MAX_RPC_FRAME_BYTES
110 || line.contains(&b'\n')
111 || line.contains(&b'\r')
112 {
113 return Err(RpcWriteError::InvalidValue);
114 }
115 line.push(b'\n');
116 Ok(line)
117}
118
119async fn writer_loop<W: AsyncWrite + Unpin>(
120 mut output: W,
121 mut receiver: mpsc::Receiver<WriteRequest>,
122 deadline: Duration,
123) -> Result<(), RpcWriteError> {
124 while let Some(request) = receiver.recv().await {
125 let result = tokio::time::timeout(deadline, async {
126 output
127 .write_all(&request.line)
128 .await
129 .map_err(|_| RpcWriteError::Closed)?;
130 output.flush().await.map_err(|_| RpcWriteError::Closed)
131 })
132 .await
133 .map_err(|_| RpcWriteError::Deadline)
134 .and_then(std::convert::identity);
135 let failed = result.is_err();
136 let _ = request.acknowledgement.send(result);
137 if failed {
138 return Err(result.expect_err("failed result checked above"));
139 }
140 }
141 Ok(())
142}