Skip to main content

jsonrpsee_server/
utils.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27use 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
52/// Largest data frame [`PermitBody`] yields.
53const BODY_CHUNK_SIZE: usize = 64 * 1024;
54
55/// Default for how long a connection may take to send its first request.
56pub(crate) const DEFAULT_FIRST_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
57
58/// Default timeout for reading a request body after its head has arrived, matching the
59/// compressed-body read timeout.
60pub(crate) const DEFAULT_REQUEST_BODY_READ_TIMEOUT: Duration = Duration::from_secs(30);
61
62/// How long an accept loop pauses after `accept` fails for a reason that outlasts the attempt.
63const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_secs(1);
64
65/// Default timeout for writing a single WebSocket message and for a stalled HTTP response write,
66/// matching geth.
67pub(crate) const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
68
69/// Default interval at which WebSocket connections are pinged, matching geth.
70pub(crate) const DEFAULT_PING_INTERVAL: Duration = Duration::from_secs(30);
71
72/// Notifies `request_received` whenever hyper passes a request to the service.
73#[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
99/// Resolves with an error if no request was received within `timeout`, otherwise never.
100pub(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
113/// Serve a service over a TCP connection with graceful shutdown.
114/// This means that pending requests will be completed before the server is stopped.
115///
116/// Connections which don't send a request within 30 seconds are closed.
117pub 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    // Also bounds how long an idle HTTP/1 keep-alive connection waits for its next request.
143    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        // Return if the connection was completed.
150        res = &mut conn => res,
151        // If the server is stopped, we should gracefully shutdown
152        // the connection and poll it until it finishes.
153        _ = &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
161/// Deserializes a JSON-RPC notification, rejecting objects that contain an `id` member.
162pub(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
183/// Pauses an accept loop after `accept` failed with `err`.
184///
185/// Errors that concern only the connection being accepted (refused, aborted or reset) return at
186/// once. Any other error, such as running out of file descriptors, persists and would make the
187/// loop spin, so it is followed by a one second sleep.
188///
189/// Returns the `stopped` future to keep polling, or `None` if it resolved during the sleep and
190/// the loop must exit.
191pub 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/// HTTP response body that holds the connection permit until the body is written or dropped.
211///
212/// hyper writes the body after the service has returned the response, so a permit dropped by the
213/// service would no longer limit the connections that are still sending a response.
214///
215/// hyper drops the body as soon as it has taken the last frame, even if it still has to write
216/// that frame to the socket. A response is therefore yielded in frames of at most
217/// [`BODY_CHUNK_SIZE`] bytes: hyper only takes the next frame while its write buffer has room, so
218/// the permit is held until all but the last few frames have been written.
219#[pin_project]
220pub(crate) struct PermitBody {
221    #[pin]
222    inner: HttpBody,
223    /// Rest of the data frame that is being yielded in chunks.
224    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/// IO that fails a write with [`io::ErrorKind::TimedOut`] once the peer has accepted no bytes for
274/// the configured duration.
275///
276/// A peer that stops reading leaves hyper's buffered response, and the permit held by its body,
277/// pending forever otherwise.
278#[pin_project]
279pub(crate) struct WriteTimeoutIo<T> {
280    #[pin]
281    inner: T,
282    timeout: Duration,
283    /// Armed when a write returns `Pending` and cleared when a write makes progress.
284    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
337/// Arms the stall timer when a write is `Pending`, so the task is woken when it fires, and clears
338/// it when the write makes progress.
339fn 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}