1use std::{
28 borrow::Cow,
29 future::Future,
30 io,
31 pin::{pin, Pin},
32 sync::Arc,
33 task::{Context, Poll},
34 time::Duration,
35};
36
37use crate::{ConnectionPermit, HttpBody};
38
39use futures_util::{future, ready};
40use hyper::body::{Bytes, Frame};
41use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
42use jsonrpsee_core::{middleware::Notification, BoxError, JsonRawValue};
43use jsonrpsee_types::TwoPointZero;
44use pin_project::pin_project;
45use serde::{Deserialize, Deserializer};
46use tokio::{
47 io::{AsyncRead, AsyncWrite, ReadBuf},
48 sync::Notify,
49 time::Sleep,
50};
51
52const BODY_CHUNK_SIZE: usize = 64 * 1024;
54
55pub(crate) const DEFAULT_FIRST_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
57
58pub(crate) const DEFAULT_REQUEST_BODY_READ_TIMEOUT: Duration = Duration::from_secs(30);
61
62const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_secs(1);
64
65pub(crate) const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
68
69pub(crate) const DEFAULT_PING_INTERVAL: Duration = Duration::from_secs(30);
71
72#[derive(Debug, Clone)]
74pub(crate) struct NotifyOnRequest<S> {
75 service: S,
76 request_received: Arc<Notify>,
77}
78
79impl<S> NotifyOnRequest<S> {
80 pub(crate) fn new(service: S, request_received: Arc<Notify>) -> Self {
81 Self { service, request_received }
82 }
83}
84
85impl<S, R> hyper::service::Service<R> for NotifyOnRequest<S>
86where
87 S: hyper::service::Service<R>,
88{
89 type Response = S::Response;
90 type Error = S::Error;
91 type Future = S::Future;
92
93 fn call(&self, request: R) -> Self::Future {
94 self.request_received.notify_one();
95 self.service.call(request)
96 }
97}
98
99pub(crate) async fn no_request_within(
101 request_received: &Notify,
102 timeout: Option<Duration>,
103) -> BoxError {
104 if let Some(timeout) = timeout &&
105 tokio::time::timeout(timeout, request_received.notified()).await.is_err()
106 {
107 return io::Error::new(io::ErrorKind::TimedOut, "no request received in time").into();
108 }
109
110 future::pending().await
111}
112
113pub async fn serve_with_graceful_shutdown<S, B, I>(
118 io: I,
119 service: S,
120 stopped: impl Future<Output = ()>,
121) -> Result<(), BoxError>
122where
123 S: tower::Service<http::Request<hyper::body::Incoming>, Response = http::Response<B>>
124 + Clone
125 + Send
126 + 'static,
127 S::Future: Send,
128 S::Response: Send,
129 S::Error: Into<BoxError>,
130 B: http_body::Body<Data = hyper::body::Bytes> + Send + 'static,
131 B::Error: Into<BoxError>,
132 I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin + 'static,
133{
134 let request_received = Arc::new(Notify::new());
135 let service = NotifyOnRequest::new(
136 hyper_util::service::TowerToHyperService::new(service),
137 request_received.clone(),
138 );
139 let io = TokioIo::new(io);
140
141 let mut builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
142 builder.http1().timer(TokioTimer::new()).header_read_timeout(DEFAULT_FIRST_REQUEST_TIMEOUT);
144 let conn = builder.serve_connection_with_upgrades(io, service);
145
146 tokio::pin!(stopped, conn);
147
148 tokio::select! {
149 res = &mut conn => res,
151 _ = &mut stopped => {
154 conn.as_mut().graceful_shutdown();
155 conn.await
156 }
157 err = no_request_within(&request_received, Some(DEFAULT_FIRST_REQUEST_TIMEOUT)) => Err(err),
158 }
159}
160
161pub(crate) fn deserialize_notification(data: &[u8]) -> Result<Notification<'_>, serde_json::Error> {
163 let notif = serde_json::from_slice::<NotificationWithoutId<'_>>(data)?;
164 Ok(Notification::new(notif.method, notif.params.map(Cow::Borrowed)))
165}
166
167#[derive(Deserialize)]
168struct NotificationWithoutId<'a> {
169 #[serde(rename = "jsonrpc")]
170 _jsonrpc: TwoPointZero,
171 #[serde(borrow)]
172 method: Cow<'a, str>,
173 #[serde(borrow)]
174 params: Option<&'a JsonRawValue>,
175 #[serde(default, rename = "id", deserialize_with = "reject_notification_id")]
176 _id: (),
177}
178
179fn reject_notification_id<'de, D: Deserializer<'de>>(_: D) -> Result<(), D::Error> {
180 Err(serde::de::Error::custom("notification must not contain an id"))
181}
182
183pub async fn accept_error_backoff<S>(err: &io::Error, stopped: S) -> Option<S>
192where
193 S: Future + Unpin,
194{
195 if matches!(
196 err.kind(),
197 io::ErrorKind::ConnectionRefused |
198 io::ErrorKind::ConnectionAborted |
199 io::ErrorKind::ConnectionReset
200 ) {
201 return Some(stopped);
202 }
203
204 match future::select(pin!(tokio::time::sleep(ACCEPT_ERROR_BACKOFF)), stopped).await {
205 future::Either::Left((_, stopped)) => Some(stopped),
206 future::Either::Right(_) => None,
207 }
208}
209
210#[pin_project]
220pub(crate) struct PermitBody {
221 #[pin]
222 inner: HttpBody,
223 pending: Bytes,
225 _conn_permit: ConnectionPermit,
226}
227
228impl PermitBody {
229 pub(crate) fn new(inner: HttpBody, conn_permit: ConnectionPermit) -> Self {
230 Self { inner, pending: Bytes::new(), _conn_permit: conn_permit }
231 }
232}
233
234impl http_body::Body for PermitBody {
235 type Data = Bytes;
236 type Error = BoxError;
237
238 fn poll_frame(
239 self: Pin<&mut Self>,
240 cx: &mut Context<'_>,
241 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
242 let this = self.project();
243
244 if this.pending.is_empty() {
245 match ready!(this.inner.poll_frame(cx)) {
246 Some(Ok(frame)) => match frame.into_data() {
247 Ok(data) => *this.pending = data,
248 Err(frame) => return Poll::Ready(Some(Ok(frame))),
249 },
250 end_or_error => return Poll::Ready(end_or_error),
251 }
252 }
253
254 let chunk = this.pending.split_to(this.pending.len().min(BODY_CHUNK_SIZE));
255 Poll::Ready(Some(Ok(Frame::data(chunk))))
256 }
257
258 fn is_end_stream(&self) -> bool {
259 self.pending.is_empty() && self.inner.is_end_stream()
260 }
261
262 fn size_hint(&self) -> http_body::SizeHint {
263 let pending = self.pending.len() as u64;
264 let mut hint = self.inner.size_hint();
265 hint.set_lower(hint.lower() + pending);
266 if let Some(upper) = hint.upper() {
267 hint.set_upper(upper + pending);
268 }
269 hint
270 }
271}
272
273#[pin_project]
279pub(crate) struct WriteTimeoutIo<T> {
280 #[pin]
281 inner: T,
282 timeout: Duration,
283 stalled: Option<Pin<Box<Sleep>>>,
285}
286
287impl<T> WriteTimeoutIo<T> {
288 pub(crate) fn new(inner: T, timeout: Duration) -> Self {
289 Self { inner, timeout, stalled: None }
290 }
291}
292
293impl<T: AsyncRead> AsyncRead for WriteTimeoutIo<T> {
294 fn poll_read(
295 self: Pin<&mut Self>,
296 cx: &mut Context<'_>,
297 buf: &mut ReadBuf<'_>,
298 ) -> Poll<io::Result<()>> {
299 self.project().inner.poll_read(cx, buf)
300 }
301}
302
303impl<T: AsyncWrite> AsyncWrite for WriteTimeoutIo<T> {
304 fn poll_write(
305 self: Pin<&mut Self>,
306 cx: &mut Context<'_>,
307 buf: &[u8],
308 ) -> Poll<io::Result<usize>> {
309 let this = self.project();
310 let poll = this.inner.poll_write(cx, buf);
311 poll_write_timeout(this.stalled, *this.timeout, cx, poll)
312 }
313
314 fn poll_write_vectored(
315 self: Pin<&mut Self>,
316 cx: &mut Context<'_>,
317 bufs: &[io::IoSlice<'_>],
318 ) -> Poll<io::Result<usize>> {
319 let this = self.project();
320 let poll = this.inner.poll_write_vectored(cx, bufs);
321 poll_write_timeout(this.stalled, *this.timeout, cx, poll)
322 }
323
324 fn is_write_vectored(&self) -> bool {
325 self.inner.is_write_vectored()
326 }
327
328 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
329 self.project().inner.poll_flush(cx)
330 }
331
332 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
333 self.project().inner.poll_shutdown(cx)
334 }
335}
336
337fn poll_write_timeout(
340 stalled: &mut Option<Pin<Box<Sleep>>>,
341 timeout: Duration,
342 cx: &mut Context<'_>,
343 poll: Poll<io::Result<usize>>,
344) -> Poll<io::Result<usize>> {
345 if poll.is_ready() {
346 *stalled = None;
347 return poll;
348 }
349
350 let stalled = stalled.get_or_insert_with(|| Box::pin(tokio::time::sleep(timeout)));
351 match stalled.as_mut().poll(cx) {
352 Poll::Ready(()) => Poll::Ready(Err(io::ErrorKind::TimedOut.into())),
353 Poll::Pending => Poll::Pending,
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use tokio::time::Instant;
361
362 #[test]
363 fn notification_id_classification_notification_metadata() {
364 for (raw, expected) in [
365 (
366 r#"{"jsonrpc":"2.0","method":"example","params":[1],"extra":{"id":true}}"#,
367 Some("[1]"),
368 ),
369 (r#"{"jsonrpc":"2.0","method":"example"}"#, None),
370 ] {
371 let notification = deserialize_notification(raw.as_bytes()).unwrap();
372 assert_eq!(notification.method_name(), "example");
373 assert_eq!(notification.params().as_ref().map(|p| p.get()), expected);
374 assert!(!matches!(notification.params(), Some(Cow::Owned(_))));
375 }
376 for id in ["true", "false", "{}", "[]", "null", "0", "\"valid\""] {
377 let raw = format!(r#"{{"jsonrpc":"2.0","method":"example","id":{id}}}"#);
378 assert!(deserialize_notification(raw.as_bytes()).is_err());
379 }
380 }
381
382 #[tokio::test(start_paused = true)]
383 async fn accept_error_backoff_skips_connection_errors() {
384 for kind in [
385 io::ErrorKind::ConnectionRefused,
386 io::ErrorKind::ConnectionAborted,
387 io::ErrorKind::ConnectionReset,
388 ] {
389 let start = Instant::now();
390 let stopped =
391 accept_error_backoff(&io::Error::from(kind), future::pending::<()>()).await;
392 assert!(stopped.is_some());
393 assert_eq!(start.elapsed(), Duration::ZERO);
394 }
395 }
396
397 #[tokio::test(start_paused = true)]
398 async fn accept_error_backoff_sleeps_on_persistent_errors() {
399 let start = Instant::now();
400 let err = io::Error::other("too many open files");
401 assert!(accept_error_backoff(&err, future::pending::<()>()).await.is_some());
402 assert_eq!(start.elapsed(), ACCEPT_ERROR_BACKOFF);
403 }
404
405 #[tokio::test(start_paused = true)]
406 async fn accept_error_backoff_observes_stop() {
407 let start = Instant::now();
408 let err = io::Error::other("out of descriptors");
409 assert!(accept_error_backoff(&err, future::ready(())).await.is_none());
410 assert_eq!(start.elapsed(), Duration::ZERO);
411 }
412}