Skip to main content

jsonrpsee_server/
server.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    fmt,
30    future::Future,
31    net::SocketAddr,
32    pin::Pin,
33    sync::{Arc, OnceLock},
34    task::Poll,
35    time::Duration,
36};
37
38use crate::{
39    future::{ConnectionGuard, ConnectionPermit, ServerHandle, StopHandle},
40    middleware::rpc::{catch_call_panic, RpcService},
41    transport::{
42        http, ws,
43        ws::{is_upgrade_request, upgrade_response, BackgroundTaskParams},
44    },
45    utils::{
46        accept_error_backoff, deserialize_notification, no_request_within, NotifyOnRequest,
47        PermitBody, WriteTimeoutIo, DEFAULT_FIRST_REQUEST_TIMEOUT, DEFAULT_PING_INTERVAL,
48        DEFAULT_REQUEST_BODY_READ_TIMEOUT, DEFAULT_WRITE_TIMEOUT,
49    },
50    HttpBody, HttpRequest, HttpResponse, LOG_TARGET,
51};
52
53use futures_util::future::{Either, FutureExt};
54use hyper::body::{Bytes, Incoming};
55use hyper_util::{
56    rt::{TokioExecutor, TokioIo, TokioTimer},
57    service::TowerToHyperService,
58};
59use jsonrpsee_core::{
60    id_providers::RandomIntegerIdProvider,
61    middleware::{Batch, BatchEntry, BatchEntryErr, RpcServiceBuilder, RpcServiceT},
62    server::{
63        helpers::prepare_error, BoundedSubscriptions, ConnectionId, MethodResponse, MethodSink,
64        Methods,
65    },
66    traits::IdProvider,
67    BoxError, JsonRawValue, TEN_MB_SIZE_BYTES,
68};
69use jsonrpsee_types::{
70    error::{
71        reject_too_big_batch_request, ErrorCode, BATCHES_NOT_SUPPORTED_CODE,
72        BATCHES_NOT_SUPPORTED_MSG,
73    },
74    ErrorObject, Id, Notification, Request, TwoPointZero,
75};
76use serde::{
77    de::{
78        value::MapAccessDeserializer, DeserializeSeed, Deserializer, Error as _, IgnoredAny,
79        MapAccess, SeqAccess, Visitor,
80    },
81    Deserialize,
82};
83use tokio::{
84    net::{TcpListener, TcpStream, ToSocketAddrs},
85    sync::{mpsc, watch, Notify},
86};
87use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
88use tower::{layer::util::Identity, Layer, Service, ServiceExt};
89use tracing::{instrument, Instrument};
90
91/// Default maximum connections allowed.
92const MAX_CONNECTIONS: u32 = 100;
93
94/// The shortest batch entry that is a valid request: a notification with an empty method name.
95const SHORTEST_BATCH_REQUEST: &str = r#"{"jsonrpc":"2.0","method":""}"#;
96
97/// JSON RPC server.
98pub struct Server<HttpMiddleware = Identity, RpcMiddleware = Identity> {
99    listener: TcpListener,
100    server_cfg: ServerConfig,
101    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
102    http_middleware: tower::ServiceBuilder<HttpMiddleware>,
103}
104
105impl Server<Identity, Identity> {
106    /// Create a builder for the server.
107    pub fn builder() -> Builder<Identity, Identity> {
108        Builder::new()
109    }
110}
111
112impl<RpcMiddleware, HttpMiddleware> std::fmt::Debug for Server<RpcMiddleware, HttpMiddleware> {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("Server")
115            .field("listener", &self.listener)
116            .field("server_cfg", &self.server_cfg)
117            .finish()
118    }
119}
120
121impl<RpcMiddleware, HttpMiddleware> Server<RpcMiddleware, HttpMiddleware> {
122    /// Returns socket address to which the server is bound.
123    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
124        self.listener.local_addr()
125    }
126}
127
128impl<HttpMiddleware, RpcMiddleware, Body> Server<HttpMiddleware, RpcMiddleware>
129where
130    RpcMiddleware: Layer<RpcService> + Clone + Send + 'static,
131    <RpcMiddleware as Layer<RpcService>>::Service: RpcServiceT,
132    HttpMiddleware: Layer<TowerServiceNoHttp<RpcMiddleware>> + Send + 'static,
133    <HttpMiddleware as Layer<TowerServiceNoHttp<RpcMiddleware>>>::Service:
134        Service<HttpRequest, Response = HttpResponse<Body>, Error = BoxError> + Clone + Send,
135    <<HttpMiddleware as Layer<TowerServiceNoHttp<RpcMiddleware>>>::Service as Service<
136        HttpRequest,
137    >>::Future: Send,
138    Body: http_body::Body<Data = Bytes> + Send + 'static,
139    <Body as http_body::Body>::Error: Into<BoxError>,
140{
141    /// Start responding to connections requests.
142    ///
143    /// This will run on the tokio runtime until the server is stopped or the `ServerHandle` is
144    /// dropped.
145    pub fn start(mut self, methods: impl Into<Methods>) -> ServerHandle {
146        let methods = methods.into();
147        let (stop_tx, stop_rx) = watch::channel(());
148
149        let stop_handle = StopHandle::new(stop_rx);
150
151        match self.server_cfg.tokio_runtime.take() {
152            Some(rt) => rt.spawn(self.start_inner(methods, stop_handle)),
153            None => tokio::spawn(self.start_inner(methods, stop_handle)),
154        };
155
156        ServerHandle::new(stop_tx)
157    }
158
159    async fn start_inner(self, methods: Methods, stop_handle: StopHandle) {
160        let connection_guard = ConnectionGuard::new(self.server_cfg.max_connections as usize);
161        let listener = self.listener;
162
163        let stopped = stop_handle.clone().shutdown();
164        tokio::pin!(stopped);
165
166        let (drop_on_completion, mut process_connection_awaiter) = mpsc::channel::<()>(1);
167
168        loop {
169            match try_accept_conn(&listener, stopped).await {
170                AcceptConnection::Established { socket, remote_addr, stop } => {
171                    process_connection(ProcessConnection {
172                        http_middleware: &self.http_middleware,
173                        rpc_middleware: self.rpc_middleware.clone(),
174                        remote_addr,
175                        methods: methods.clone(),
176                        stop_handle: stop_handle.clone(),
177                        conn_id: ConnectionId::next_unique().0,
178                        server_cfg: self.server_cfg.clone(),
179                        conn_guard: &connection_guard,
180                        socket,
181                        drop_on_completion: drop_on_completion.clone(),
182                    });
183                    stopped = stop;
184                }
185                AcceptConnection::Err((e, stop)) => {
186                    tracing::debug!(target: LOG_TARGET, "Error while awaiting a new connection: {:?}", e);
187                    let Some(stop) = accept_error_backoff(&e, stop).await else { break };
188                    stopped = stop;
189                }
190                AcceptConnection::Shutdown => break,
191            }
192        }
193
194        // Drop the last Sender
195        drop(drop_on_completion);
196
197        // Once this channel is closed it is safe to assume that all connections have been
198        // gracefully shutdown
199        while process_connection_awaiter.recv().await.is_some() {
200            // Generally, messages should not be sent across this channel,
201            // but we'll loop here to wait for `None` just to be on the safe side
202        }
203    }
204}
205
206/// Static server configuration which is shared per connection.
207#[derive(Debug, Clone)]
208pub struct ServerConfig {
209    /// Maximum size in bytes of a request.
210    pub(crate) max_request_body_size: u32,
211    /// Maximum size in bytes of a response.
212    pub(crate) max_response_body_size: u32,
213    /// Maximum number of incoming connections allowed.
214    pub(crate) max_connections: u32,
215    /// Maximum number of subscriptions per connection.
216    pub(crate) max_subscriptions_per_connection: u32,
217    /// Whether batch requests are supported by this server or not.
218    pub(crate) batch_requests_config: BatchRequestConfig,
219    /// Custom tokio runtime to run the server on.
220    pub(crate) tokio_runtime: Option<tokio::runtime::Handle>,
221    /// Enable HTTP.
222    pub(crate) enable_http: bool,
223    /// Enable WS.
224    pub(crate) enable_ws: bool,
225    /// Number of messages that server is allowed to `buffer` until backpressure kicks in.
226    pub(crate) message_buffer_capacity: u32,
227    /// ID provider.
228    pub(crate) id_provider: Arc<dyn IdProvider>,
229    /// Timeout for receiving the first request of a connection, and the next request head of an
230    /// HTTP/1 keep-alive connection.
231    pub(crate) first_request_timeout: Option<Duration>,
232    /// Timeout for writing a single message to a WebSocket connection and for a stalled HTTP
233    /// response write.
234    pub(crate) write_timeout: Duration,
235    /// Timeout for reading a request body after its head has arrived. `None` disables the timeout.
236    pub(crate) request_body_read_timeout: Option<Duration>,
237    /// Interval at which WebSocket connections are pinged. A connection that completes neither a
238    /// message nor a pong within twice this interval is closed.
239    pub(crate) ping_interval: Duration,
240}
241
242/// The builder to configure and create a JSON-RPC server configuration.
243#[derive(Debug, Clone)]
244pub struct ServerConfigBuilder(ServerConfig);
245
246/// Configuration for batch request handling.
247#[derive(Debug, Copy, Clone)]
248pub enum BatchRequestConfig {
249    /// Batch requests are disabled.
250    Disabled,
251    /// Each batch request is limited to `len` and any batch request bigger than `len` will not be
252    /// processed.
253    Limit(u32),
254    /// The batch request is limited only by the maximum request size.
255    ///
256    /// A batch may hold as many entries as the shortest valid requests that fit in that size, so
257    /// no batch of valid requests is rejected, but entries that aren't requests (`0` takes two
258    /// bytes) can't make a batch any longer.
259    Unlimited,
260}
261
262/// Connection related state that is needed
263/// to execute JSON-RPC calls.
264#[derive(Debug, Clone)]
265pub struct ConnectionState {
266    /// Stop handle.
267    pub(crate) stop_handle: StopHandle,
268    /// Connection ID
269    pub(crate) conn_id: usize,
270    /// Connection guard.
271    pub(crate) _conn_permit: Arc<ConnectionPermit>,
272}
273
274impl ConnectionState {
275    /// Create a new connection state.
276    pub fn new(
277        stop_handle: StopHandle,
278        conn_id: usize,
279        conn_permit: ConnectionPermit,
280    ) -> ConnectionState {
281        Self { stop_handle, conn_id, _conn_permit: Arc::new(conn_permit) }
282    }
283}
284
285impl Default for ServerConfig {
286    fn default() -> Self {
287        ServerConfig::builder().build()
288    }
289}
290
291impl ServerConfig {
292    /// Create a new builder for the [`ServerConfig`].
293    pub fn builder() -> ServerConfigBuilder {
294        ServerConfigBuilder::default()
295    }
296}
297
298impl Default for ServerConfigBuilder {
299    fn default() -> Self {
300        Self(ServerConfig {
301            max_request_body_size: TEN_MB_SIZE_BYTES,
302            max_response_body_size: TEN_MB_SIZE_BYTES,
303            max_connections: MAX_CONNECTIONS,
304            max_subscriptions_per_connection: 1024,
305            batch_requests_config: BatchRequestConfig::Unlimited,
306            tokio_runtime: None,
307            enable_http: true,
308            enable_ws: true,
309            message_buffer_capacity: 1024,
310            id_provider: Arc::new(RandomIntegerIdProvider),
311            first_request_timeout: Some(DEFAULT_FIRST_REQUEST_TIMEOUT),
312            write_timeout: DEFAULT_WRITE_TIMEOUT,
313            request_body_read_timeout: Some(DEFAULT_REQUEST_BODY_READ_TIMEOUT),
314            ping_interval: DEFAULT_PING_INTERVAL,
315        })
316    }
317}
318
319impl ServerConfigBuilder {
320    /// Create a new [`ServerConfigBuilder`].
321    pub fn new() -> Self {
322        Self::default()
323    }
324
325    /// Set the maximum size of a request body in bytes. Default is 10 MiB.
326    pub fn max_request_body_size(mut self, size: u32) -> Self {
327        self.0.max_request_body_size = size;
328        self
329    }
330
331    /// Set the maximum size of a response body in bytes. Default is 10 MiB.
332    pub fn max_response_body_size(mut self, size: u32) -> Self {
333        self.0.max_response_body_size = size;
334        self
335    }
336
337    /// Set the maximum number of connections allowed. Default is 100.
338    pub fn max_connections(mut self, max: u32) -> Self {
339        self.0.max_connections = max;
340        self
341    }
342
343    /// Set the maximum number of subscriptions per connection. Default is 1024.
344    pub fn max_subscriptions_per_connection(mut self, max: u32) -> Self {
345        self.0.max_subscriptions_per_connection = max;
346        self
347    }
348
349    /// Configure how [batch requests](https://www.jsonrpc.org/specification#batch) shall be handled
350    /// by the server.
351    ///
352    /// Default: batch requests are allowed and can be arbitrary big but the maximum payload size is
353    /// limited.
354    pub fn set_batch_request_config(mut self, cfg: BatchRequestConfig) -> Self {
355        self.0.batch_requests_config = cfg;
356        self
357    }
358
359    /// Configure a custom [`tokio::runtime::Handle`] to run the server on.
360    ///
361    /// Default: [`tokio::spawn`]
362    pub fn custom_tokio_runtime(mut self, rt: tokio::runtime::Handle) -> Self {
363        self.0.tokio_runtime = Some(rt);
364        self
365    }
366
367    /// Configure the server to only serve JSON-RPC HTTP requests.
368    ///
369    /// Default: both http and ws are enabled.
370    pub fn http_only(mut self) -> Self {
371        self.0.enable_http = true;
372        self.0.enable_ws = false;
373        self
374    }
375
376    /// Configure the server to only serve JSON-RPC WebSocket requests.
377    ///
378    /// That implies that server just denies HTTP requests which isn't a WebSocket upgrade request
379    ///
380    /// Default: both http and ws are enabled.
381    pub fn ws_only(mut self) -> Self {
382        self.0.enable_http = false;
383        self.0.enable_ws = true;
384        self
385    }
386
387    /// The server enforces backpressure which means that
388    /// `n` messages can be buffered and if the client
389    /// can't keep with up the server.
390    ///
391    /// This `capacity` is applied per connection and
392    /// applies globally on the connection which implies
393    /// all JSON-RPC messages.
394    ///
395    /// It is the number of messages (responses and subscription notifications) that can wait to
396    /// be written to the client, and also the most calls a WebSocket connection runs at once.
397    ///
398    /// For example if a subscription produces plenty of new items
399    /// and the client can't keep up then no new messages are handled.
400    ///
401    /// If the client can't keep up then calls wait to queue their response. Once that many calls
402    /// are running, the server stops reading new messages from the connection until one
403    /// completes.
404    ///
405    /// # Panics
406    ///
407    /// Panics if the buffer capacity is 0.
408    pub fn set_message_buffer_capacity(mut self, c: u32) -> Self {
409        assert!(c > 0, "buffer capacity must be set to > 0");
410        self.0.message_buffer_capacity = c;
411        self
412    }
413
414    /// Configure custom `subscription ID` provider for the server to use
415    /// to when getting new subscription calls.
416    ///
417    /// You may choose static dispatch or dynamic dispatch because
418    /// `IdProvider` is implemented for `Box<T>`.
419    ///
420    /// Default: [`RandomIntegerIdProvider`].
421    ///
422    /// # Examples
423    ///
424    /// ```rust
425    /// use jsonrpsee_server::{IdProvider, RandomStringIdProvider, ServerConfigBuilder};
426    ///
427    /// // static dispatch
428    /// let builder1 = ServerConfigBuilder::default().set_id_provider(RandomStringIdProvider::new(16));
429    ///
430    /// // or dynamic dispatch
431    /// let builder2 =
432    ///     ServerConfigBuilder::default().set_id_provider(Box::new(RandomStringIdProvider::new(16)));
433    /// ```
434    pub fn set_id_provider<I: IdProvider + 'static>(mut self, id_provider: I) -> Self {
435        self.0.id_provider = Arc::new(id_provider);
436        self
437    }
438
439    /// Configure how long a connection may take to send its first request, e.g. the WebSocket
440    /// upgrade request, before it is closed. An HTTP/1 keep-alive connection is closed as well
441    /// when it takes longer to send the head of its next request. `None` disables the timeout.
442    ///
443    /// Default is 30 seconds.
444    pub fn set_first_request_timeout(mut self, first_request_timeout: Option<Duration>) -> Self {
445        self.0.first_request_timeout = first_request_timeout;
446        self
447    }
448
449    /// Configure how long writing a single message, ping or close frame to a WebSocket
450    /// connection may take, and how long an HTTP response write may make no progress, before the
451    /// connection is closed.
452    ///
453    /// A client that stops reading fills the socket's send buffer, which blocks the write. When
454    /// the timeout expires, the connection is dropped together with its queued messages,
455    /// subscriptions and pending calls, or with its buffered HTTP response.
456    ///
457    /// Default is 10 seconds.
458    pub fn set_write_timeout(mut self, write_timeout: Duration) -> Self {
459        self.0.write_timeout = write_timeout;
460        self
461    }
462
463    /// Configure how long reading a request body may take after its head has arrived, before the
464    /// request is answered with `408 Request Timeout`. Bodies already collected by HTTP
465    /// middleware, such as a decompression layer, are not covered. `None` disables the timeout.
466    ///
467    /// Default is 30 seconds.
468    pub fn set_request_body_read_timeout(
469        mut self,
470        request_body_read_timeout: Option<Duration>,
471    ) -> Self {
472        self.0.request_body_read_timeout = request_body_read_timeout;
473        self
474    }
475
476    /// Build the [`ServerConfig`].
477    pub fn build(self) -> ServerConfig {
478        self.0
479    }
480}
481
482/// Builder to configure and create a JSON-RPC server.
483#[derive(Debug)]
484pub struct Builder<HttpMiddleware, RpcMiddleware> {
485    server_cfg: ServerConfig,
486    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
487    http_middleware: tower::ServiceBuilder<HttpMiddleware>,
488}
489
490impl Default for Builder<Identity, Identity> {
491    fn default() -> Self {
492        Builder {
493            server_cfg: ServerConfig::default(),
494            rpc_middleware: RpcServiceBuilder::new(),
495            http_middleware: tower::ServiceBuilder::new(),
496        }
497    }
498}
499
500impl Builder<Identity, Identity> {
501    /// Create a default server builder.
502    pub fn new() -> Self {
503        Self::default()
504    }
505
506    /// Create a server builder with the given [`ServerConfig`].
507    pub fn with_config(config: ServerConfig) -> Self {
508        Self { server_cfg: config, ..Default::default() }
509    }
510}
511
512impl<HttpMiddleware, RpcMiddleware> Builder<HttpMiddleware, RpcMiddleware> {
513    /// Configure the [`ServerConfig`].
514    pub fn set_config(mut self, cfg: ServerConfig) -> Self {
515        self.server_cfg = cfg;
516        self
517    }
518
519    /// Enable middleware that is invoked on every JSON-RPC call.
520    ///
521    /// The middleware itself is very similar to the `tower middleware` but
522    /// it has a different service trait which takes &self instead &mut self
523    /// which means that you can't use built-in middleware from tower.
524    ///
525    /// Another consequence of `&self` is that you must wrap any of the middleware state in
526    /// a type which is Send and provides interior mutability such as `Arc<Mutex>`.
527    ///
528    /// The builder itself exposes a similar API as the [`tower::ServiceBuilder`]
529    /// where it is possible to compose layers to the middleware.
530    ///
531    /// To add middleware [`RpcServiceBuilder`] exposes a few different layer APIs that
532    /// are wrapped on top of the [`tower::ServiceBuilder`].
533    ///
534    /// When the server is started these layers are wrapped in the [`RpcService`] and
535    /// that's why the service APIs is not exposed.
536    /// ```
537    /// use std::{
538    ///     net::SocketAddr,
539    ///     sync::{
540    ///         atomic::{AtomicUsize, Ordering},
541    ///         Arc,
542    ///     },
543    ///     time::Instant,
544    /// };
545    ///
546    /// use jsonrpsee_server::{
547    ///     middleware::rpc::{
548    ///         Batch, MethodResponse, Notification, Request, RpcService, RpcServiceBuilder,
549    ///         RpcServiceT,
550    ///     },
551    ///     ServerBuilder,
552    /// };
553    ///
554    /// #[derive(Clone)]
555    /// struct MyMiddleware<S> {
556    ///     service: S,
557    ///     count: Arc<AtomicUsize>,
558    /// }
559    ///
560    /// impl<S> RpcServiceT for MyMiddleware<S>
561    /// where
562    ///     S: RpcServiceT + Clone + Send + Sync + 'static,
563    /// {
564    ///     fn call<'a>(&self, req: Request<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
565    ///         tracing::info!("MyMiddleware processed call {}", req.method);
566    ///         let count = self.count.clone();
567    ///         let service = self.service.clone();
568    ///
569    ///         async move {
570    ///             let rp = service.call(req).await;
571    ///             // Modify the state.
572    ///             count.fetch_add(1, Ordering::Relaxed);
573    ///             rp
574    ///         }
575    ///     }
576    ///
577    ///     fn batch<'a>(&self, batch: Batch<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
578    ///         self.service.batch(batch)
579    ///     }
580    ///
581    ///     fn notification<'a>(
582    ///         &self,
583    ///         notif: Notification<'a>,
584    ///     ) -> impl Future<Output = MethodResponse> + Send + 'a {
585    ///         self.service.notification(notif)
586    ///     }
587    /// }
588    ///
589    /// // Create a state per connection
590    /// // NOTE: The service type can be omitted once `start` is called on the server.
591    /// let m = RpcServiceBuilder::new().layer_fn(move |service: ()| MyMiddleware {
592    ///     service,
593    ///     count: Arc::new(AtomicUsize::new(0)),
594    /// });
595    /// let builder = ServerBuilder::default().set_rpc_middleware(m);
596    /// ```
597    pub fn set_rpc_middleware<T>(
598        self,
599        rpc_middleware: RpcServiceBuilder<T>,
600    ) -> Builder<HttpMiddleware, T> {
601        Builder {
602            server_cfg: self.server_cfg,
603            rpc_middleware,
604            http_middleware: self.http_middleware,
605        }
606    }
607
608    /// Configure a custom [`tower::ServiceBuilder`] middleware for composing layers to be applied
609    /// to the RPC service.
610    ///
611    /// Default: No tower layers are applied to the RPC service.
612    ///
613    /// # Examples
614    ///
615    /// ```rust
616    /// use std::{net::SocketAddr, time::Duration};
617    ///
618    /// #[tokio::main]
619    /// async fn main() {
620    ///     let builder = tower::ServiceBuilder::new().timeout(Duration::from_secs(2));
621    ///
622    ///     let server = jsonrpsee_server::ServerBuilder::new()
623    ///         .set_http_middleware(builder)
624    ///         .build("127.0.0.1:0".parse::<SocketAddr>().unwrap())
625    ///         .await
626    ///         .unwrap();
627    /// }
628    /// ```
629    pub fn set_http_middleware<T>(
630        self,
631        http_middleware: tower::ServiceBuilder<T>,
632    ) -> Builder<T, RpcMiddleware> {
633        Builder {
634            server_cfg: self.server_cfg,
635            http_middleware,
636            rpc_middleware: self.rpc_middleware,
637        }
638    }
639
640    /// Finalize the configuration of the server. Consumes the [`Builder`].
641    ///
642    /// ```rust
643    /// #[tokio::main]
644    /// async fn main() {
645    ///     let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
646    ///     let occupied_addr = listener.local_addr().unwrap();
647    ///     let addrs: &[std::net::SocketAddr] = &[occupied_addr, "127.0.0.1:0".parse().unwrap()];
648    ///     assert!(jsonrpsee_server::ServerBuilder::default().build(occupied_addr).await.is_err());
649    ///     assert!(jsonrpsee_server::ServerBuilder::default().build(addrs).await.is_ok());
650    /// }
651    /// ```
652    pub async fn build(
653        self,
654        addrs: impl ToSocketAddrs,
655    ) -> std::io::Result<Server<HttpMiddleware, RpcMiddleware>> {
656        let listener = TcpListener::bind(addrs).await?;
657
658        Ok(Server {
659            listener,
660            server_cfg: self.server_cfg,
661            rpc_middleware: self.rpc_middleware,
662            http_middleware: self.http_middleware,
663        })
664    }
665}
666
667/// Data required by the server to handle requests.
668struct ServiceData<S> {
669    /// Registered server methods.
670    methods: Methods,
671    /// Stop handle.
672    stop_handle: StopHandle,
673    /// Connection ID
674    conn_id: usize,
675    /// Connection guard.
676    conn_guard: ConnectionGuard,
677    /// ServerConfig
678    server_cfg: ServerConfig,
679    /// RPC service for the HTTP requests of the connection, built on the first one.
680    http_rpc_service: OnceLock<Arc<S>>,
681}
682
683/// jsonrpsee tower service without HTTP specific middleware.
684///
685/// hyper clones the service for every request, so the connection's state is shared behind an
686/// [`Arc`].
687///
688/// # Note
689/// This is similar to [`hyper::service::service_fn`].
690pub struct TowerServiceNoHttp<L: Layer<RpcService>> {
691    inner: Arc<ServiceData<L::Service>>,
692    rpc_middleware: RpcServiceBuilder<L>,
693}
694
695impl<L: Layer<RpcService> + Clone> Clone for TowerServiceNoHttp<L> {
696    fn clone(&self) -> Self {
697        Self { inner: self.inner.clone(), rpc_middleware: self.rpc_middleware.clone() }
698    }
699}
700
701// Not derived, a derive would require the RPC service of the middleware to be `Debug` as well.
702impl<L: Layer<RpcService> + fmt::Debug> fmt::Debug for TowerServiceNoHttp<L> {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        f.debug_struct("TowerServiceNoHttp")
705            .field("conn_id", &self.inner.conn_id)
706            .field("rpc_middleware", &self.rpc_middleware)
707            .finish_non_exhaustive()
708    }
709}
710
711impl<Body, RpcMiddleware> Service<HttpRequest<Body>> for TowerServiceNoHttp<RpcMiddleware>
712where
713    RpcMiddleware: Layer<RpcService>,
714    <RpcMiddleware as Layer<RpcService>>::Service: RpcServiceT + Send + Sync + 'static,
715    Body: http_body::Body<Data = Bytes> + Send + 'static,
716    <Body as http_body::Body>::Error: Into<BoxError>,
717{
718    type Response = HttpResponse;
719
720    // The following associated type is required by the `impl<B, U, M: JsonRpcMiddleware> Server<B,
721    // L>` bounds. It satisfies the server's bounds when the `tower::ServiceBuilder<B>` is not
722    // set (ie `B: Identity`).
723    type Error = BoxError;
724
725    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
726
727    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
728        Poll::Ready(Ok(()))
729    }
730
731    fn call(&mut self, request: HttpRequest<Body>) -> Self::Future {
732        let request = request.map(HttpBody::new);
733
734        let conn_guard = &self.inner.conn_guard;
735        let conn_id = self.inner.conn_id;
736
737        tracing::trace!(
738            target: LOG_TARGET,
739            "{} {} {:?}",
740            request.method(),
741            request.uri(),
742            request.version()
743        );
744
745        let Some(conn_permit) = conn_guard.try_acquire() else {
746            return async move { Ok(http::response::too_many_requests()) }.boxed();
747        };
748
749        let max_conns = conn_guard.max_connections();
750        let curr_conns = max_conns - conn_guard.available_connections();
751        tracing::debug!(target: LOG_TARGET, "Accepting new connection {}/{}", curr_conns, max_conns);
752
753        let is_upgrade_request = is_upgrade_request(&request);
754
755        if self.inner.server_cfg.enable_ws && is_upgrade_request {
756            let this = &self.inner;
757            let conn = ConnectionState::new(this.stop_handle.clone(), conn_id, conn_permit);
758            let server_cfg = this.server_cfg.clone();
759
760            let response = match upgrade_response(&request) {
761                Ok(response) => {
762                    let (tx, rx) = mpsc::channel(this.server_cfg.message_buffer_capacity as usize);
763                    let sink =
764                        MethodSink::new_with_limit(tx, this.server_cfg.max_response_body_size);
765
766                    // On each method call the `pending_calls` is cloned
767                    // then when all pending_calls are dropped
768                    // a graceful shutdown can occur.
769                    let (pending_calls, pending_calls_completed) = mpsc::channel::<()>(1);
770
771                    let rpc_service = RpcService::new(
772                        this.methods.clone(),
773                        this.server_cfg.max_response_body_size as usize,
774                        this.conn_id.into(),
775                        BoundedSubscriptions::new(this.server_cfg.max_subscriptions_per_connection),
776                        sink.clone(),
777                        this.server_cfg.id_provider.clone(),
778                    );
779
780                    let rpc_service = self.rpc_middleware.service(rpc_service);
781
782                    tokio::spawn(
783                        async move {
784                            let upgraded = match hyper::upgrade::on(request).await {
785                                Ok(u) => u,
786                                Err(e) => {
787                                    tracing::debug!(target: LOG_TARGET, "Could not upgrade connection: {}", e);
788                                    return;
789                                }
790                            };
791
792                            let max_request_size = server_cfg.max_request_body_size as usize;
793                            // `tungstenite` reads a frame whole into its read buffer and never
794                            // shrinks it, so after a frame near the limit the connection keeps
795                            // that much allocated until it closes. An unfinished fragmented
796                            // message takes about twice its size: the collected fragments and the
797                            // read buffer that grew for them.
798                            // Frames that a client didn't mask have always been read.
799                            let ws_config = WebSocketConfig::default()
800                                .max_message_size(Some(max_request_size))
801                                .max_frame_size(Some(max_request_size))
802                                .accept_unmasked_frames(true);
803                            let (sender, receiver) =
804                                ws::split(TokioIo::new(upgraded), ws_config).await;
805
806                            let params = BackgroundTaskParams {
807                                server_cfg,
808                                conn,
809                                ws_sender: sender,
810                                ws_receiver: receiver,
811                                rpc_service,
812                                sink,
813                                rx,
814                                pending_calls,
815                                pending_calls_completed,
816                            };
817
818                            ws::background_task(params).await;
819                        }
820                        .in_current_span(),
821                    );
822
823                    response
824                }
825                Err(e) => {
826                    tracing::debug!(target: LOG_TARGET, "Could not upgrade connection: {}", e);
827                    let mut response = HttpResponse::new(HttpBody::from(format!(
828                        "Could not upgrade connection: {e}"
829                    )));
830                    *response.status_mut() = hyper::StatusCode::BAD_REQUEST;
831                    response
832                }
833            };
834
835            async { Ok(response) }.boxed()
836        } else if self.inner.server_cfg.enable_http && !is_upgrade_request {
837            let this = &self.inner;
838            let max_response_size = this.server_cfg.max_response_body_size;
839            let max_request_size = this.server_cfg.max_request_body_size;
840            let batch_config = this.server_cfg.batch_requests_config;
841            let request_body_read_timeout = this.server_cfg.request_body_read_timeout;
842
843            let rpc_service = this
844                .http_rpc_service
845                .get_or_init(|| {
846                    Arc::new(self.rpc_middleware.service(RpcService::without_subscriptions(
847                        this.methods.clone(),
848                        max_response_size as usize,
849                        this.conn_id.into(),
850                    )))
851                })
852                .clone();
853
854            Box::pin(async move {
855                let rp = http::call_with_service(
856                    request,
857                    batch_config,
858                    max_request_size,
859                    request_body_read_timeout,
860                    &*rpc_service,
861                )
862                .await;
863                // NOTE: The `conn guard` must be held until the response body is written (or
864                // dropped) to respect the `max_connections` limit, because hyper writes the body
865                // after this future completes.
866                Ok(rp.map(|body| HttpBody::new(PermitBody::new(body, conn_permit))))
867            })
868        } else {
869            // NOTE: the `conn guard` is dropped when this function which is fine
870            // because it doesn't rely on any async operations.
871            Box::pin(async { Ok(http::response::denied()) })
872        }
873    }
874}
875
876struct ProcessConnection<'a, HttpMiddleware, RpcMiddleware> {
877    http_middleware: &'a tower::ServiceBuilder<HttpMiddleware>,
878    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
879    conn_guard: &'a ConnectionGuard,
880    conn_id: usize,
881    server_cfg: ServerConfig,
882    stop_handle: StopHandle,
883    socket: TcpStream,
884    drop_on_completion: mpsc::Sender<()>,
885    remote_addr: SocketAddr,
886    methods: Methods,
887}
888
889#[instrument(name = "connection", target = LOG_TARGET, skip_all, fields(remote_addr = %params.remote_addr, conn_id = %params.conn_id), level = "INFO")]
890fn process_connection<RpcMiddleware, HttpMiddleware, Body>(
891    params: ProcessConnection<HttpMiddleware, RpcMiddleware>,
892) where
893    RpcMiddleware: Layer<RpcService>,
894    HttpMiddleware: Layer<TowerServiceNoHttp<RpcMiddleware>> + Send + 'static,
895    <HttpMiddleware as Layer<TowerServiceNoHttp<RpcMiddleware>>>::Service: Service<HttpRequest, Response = HttpResponse<Body>, Error = BoxError>
896        + Clone
897        + Send
898        + 'static,
899    <<HttpMiddleware as Layer<TowerServiceNoHttp<RpcMiddleware>>>::Service as Service<
900        HttpRequest,
901    >>::Future: Send + 'static,
902    Body: http_body::Body<Data = Bytes> + Send + 'static,
903    <Body as http_body::Body>::Error: Into<BoxError>,
904{
905    let ProcessConnection {
906        http_middleware,
907        rpc_middleware,
908        conn_guard,
909        conn_id,
910        server_cfg,
911        socket,
912        stop_handle,
913        drop_on_completion,
914        methods,
915        ..
916    } = params;
917
918    if let Err(e) = socket.set_nodelay(true) {
919        tracing::warn!(target: LOG_TARGET, "Could not set NODELAY on socket: {:?}", e);
920        return;
921    }
922
923    let first_request_timeout = server_cfg.first_request_timeout;
924    let write_timeout = server_cfg.write_timeout;
925
926    let tower_service = TowerServiceNoHttp {
927        inner: Arc::new(ServiceData {
928            server_cfg,
929            methods,
930            stop_handle: stop_handle.clone(),
931            conn_id,
932            conn_guard: conn_guard.clone(),
933            http_rpc_service: OnceLock::new(),
934        }),
935        rpc_middleware,
936    };
937
938    let service = http_middleware.service(tower_service);
939
940    let serve = async move {
941        let request_received = Arc::new(Notify::new());
942        // this requires Clone.
943        let service = NotifyOnRequest::new(
944            TowerToHyperService::new(
945                service.map_request(|request: HttpRequest<Incoming>| request.map(HttpBody::new)),
946            ),
947            request_received.clone(),
948        );
949        let io = TokioIo::new(WriteTimeoutIo::new(socket, write_timeout));
950        let mut builder = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
951        // Also bounds how long an idle HTTP/1 keep-alive connection waits for its next request,
952        // which holds the socket without a connection permit.
953        builder.http1().timer(TokioTimer::new()).header_read_timeout(first_request_timeout);
954        let conn = builder.serve_connection_with_upgrades(io, service);
955        let stopped = stop_handle.shutdown();
956
957        tokio::pin!(stopped, conn);
958
959        let res = tokio::select! {
960            res = &mut conn => res,
961            _ = &mut stopped => {
962                // NOTE: the connection should continue to be polled until shutdown can finish.
963                // Thus, both lines below are needed and not a nit.
964                conn.as_mut().graceful_shutdown();
965                conn.await
966            }
967            err = no_request_within(&request_received, first_request_timeout) => Err(err),
968        };
969
970        if let Err(e) = res {
971            tracing::debug!(target: LOG_TARGET, "HTTP serve connection failed {:?}", e);
972        }
973        drop(drop_on_completion)
974    };
975    // `#[instrument]` only spans this function, so the connection span is carried into the task.
976    tokio::spawn(serve.in_current_span());
977}
978
979enum AcceptConnection<S> {
980    Shutdown,
981    Established { socket: TcpStream, remote_addr: SocketAddr, stop: S },
982    Err((std::io::Error, S)),
983}
984
985async fn try_accept_conn<S>(listener: &TcpListener, stopped: S) -> AcceptConnection<S>
986where
987    S: Future + Unpin,
988{
989    let accept = listener.accept();
990    tokio::pin!(accept);
991
992    // `select` polls its first argument first and returns as soon as that one is ready, so the
993    // stop signal has to come first: with `accept` first, a listener that keeps returning without
994    // ever pending starves the stop signal and the server can no longer be stopped.
995    match futures_util::future::select(stopped, accept).await {
996        Either::Left(_) => AcceptConnection::Shutdown,
997        Either::Right((res, stop)) => match res {
998            Ok((socket, remote_addr)) => {
999                AcceptConnection::Established { socket, remote_addr, stop }
1000            }
1001            Err(e) => AcceptConnection::Err((e, stop)),
1002        },
1003    }
1004}
1005
1006/// Parses `body` as a single JSON-RPC message (`is_single`) or a batch, dispatches it to
1007/// `rpc_service` and returns the serialized response.
1008///
1009/// `max_request_size` is the request size limit the caller enforced on `body`, which bounds the
1010/// entries of a [`BatchRequestConfig::Unlimited`] batch.
1011///
1012/// A panicking call is answered with an internal error. The caller sends the response only if it
1013/// [is a method call](MethodResponse::is_method_call) or [a batch](MethodResponse::is_batch):
1014/// notifications are not answered and subscription calls answer through the subscription sink.
1015pub async fn handle_rpc_call<S>(
1016    body: &[u8],
1017    is_single: bool,
1018    batch_config: BatchRequestConfig,
1019    max_request_size: u32,
1020    rpc_service: &S,
1021) -> MethodResponse
1022where
1023    S: RpcServiceT + Send,
1024{
1025    // Single request or notification
1026    if is_single {
1027        if let Ok(req) = serde_json::from_slice::<Request<'_>>(body) {
1028            catch_call_panic(req.id(), || rpc_service.call(req)).await
1029        } else if let Ok(notif) = deserialize_notification(body) {
1030            rpc_service.notification(notif).await
1031        } else {
1032            let (id, code) = prepare_error(body);
1033            MethodResponse::error(id, ErrorObject::from(code))
1034        }
1035    }
1036    // Batch of requests.
1037    else {
1038        let max_len = match batch_config {
1039            BatchRequestConfig::Disabled => {
1040                let rp = MethodResponse::error(
1041                    Id::Null,
1042                    ErrorObject::borrowed(
1043                        BATCHES_NOT_SUPPORTED_CODE,
1044                        BATCHES_NOT_SUPPORTED_MSG,
1045                        None,
1046                    ),
1047                );
1048                return rp;
1049            }
1050            BatchRequestConfig::Limit(limit) => limit as usize,
1051            // Every entry is decoded and kept until the batch runs, and an entry that isn't a
1052            // request can take two bytes. A valid request takes at least the shortest one and a
1053            // separating comma, so this never rejects a batch of valid requests.
1054            BatchRequestConfig::Unlimited => {
1055                max_request_size as usize / (SHORTEST_BATCH_REQUEST.len() + 1)
1056            }
1057        };
1058
1059        match parse_batch(body, max_len) {
1060            Ok(batch) => rpc_service.batch(batch).await,
1061            Err(rp) => rp,
1062        }
1063    }
1064}
1065
1066/// Reads `body` as a batch of at most `max_len` entries, or returns the response to a batch that
1067/// can't be read.
1068fn parse_batch(body: &[u8], max_len: usize) -> Result<Batch<'_>, MethodResponse> {
1069    let mut entries = Vec::new();
1070    let mut too_big = false;
1071
1072    // Most batches hold only valid requests, so the entries are decoded as they are read. Once an
1073    // entry doesn't decode, the batch is read again from that entry on, classifying each raw entry
1074    // to answer the invalid ones in place.
1075    for raw in [false, true] {
1076        let mut deserializer = serde_json::Deserializer::from_slice(body);
1077        let read = BatchSeed { max_len, too_big: &mut too_big, entries: &mut entries, raw }
1078            .deserialize(&mut deserializer)
1079            .and_then(|()| deserializer.end());
1080
1081        if read.is_ok() {
1082            return Ok(Batch::from(entries));
1083        }
1084        // The seed stops reading as soon as the batch exceeds the limit, which surfaces as a
1085        // deserialization error.
1086        if too_big {
1087            return Err(MethodResponse::error(Id::Null, reject_too_big_batch_request(max_len)));
1088        }
1089    }
1090
1091    Err(MethodResponse::error(Id::Null, ErrorObject::from(ErrorCode::ParseError)))
1092}
1093
1094/// Classifies a raw batch entry as a call, a notification or an invalid request.
1095fn parse_batch_entry(call: &JsonRawValue) -> Result<BatchEntry<'_>, BatchEntryErr<'_>> {
1096    // The derived `Deserialize` impls below also accept a JSON array holding the fields in
1097    // order, so only objects may reach them.
1098    if !call.get().starts_with('{') {
1099        return Err(BatchEntryErr::new(Id::Null, ErrorCode::InvalidRequest.into()));
1100    }
1101
1102    if let Ok(req) = serde_json::from_str(call.get()) {
1103        Ok(BatchEntry::Call(req))
1104    } else if let Ok(notif) = deserialize_notification(call.get().as_bytes()) {
1105        Ok(BatchEntry::Notification(notif))
1106    } else {
1107        let id = match serde_json::from_str::<jsonrpsee_types::InvalidRequest>(call.get()) {
1108            Ok(err) => err.id,
1109            Err(_) => Id::Null,
1110        };
1111
1112        Err(BatchEntryErr::new(id, ErrorCode::InvalidRequest.into()))
1113    }
1114}
1115
1116/// A valid batch entry: a call if it has an `id`, a notification otherwise.
1117///
1118/// Unknown members use the raw pass, which validates UTF-8 even in ignored values.
1119#[derive(Deserialize)]
1120#[serde(deny_unknown_fields)]
1121struct ValidBatchEntry<'a> {
1122    jsonrpc: TwoPointZero,
1123    #[serde(borrow, default, deserialize_with = "deserialize_present_id")]
1124    id: Option<Id<'a>>,
1125    #[serde(borrow)]
1126    method: Cow<'a, str>,
1127    #[serde(borrow)]
1128    params: Option<&'a JsonRawValue>,
1129}
1130
1131impl<'a> From<ValidBatchEntry<'a>> for BatchEntry<'a> {
1132    fn from(entry: ValidBatchEntry<'a>) -> Self {
1133        let ValidBatchEntry { jsonrpc, id, method, params } = entry;
1134        let params = params.map(Cow::Borrowed);
1135        match id {
1136            Some(id) => Self::Call(Request { jsonrpc, id, method, params }),
1137            None => Self::Notification(Notification::new(method, params)),
1138        }
1139    }
1140}
1141
1142/// Only runs for an `id` that is present, so `null` is an id and not a missing one.
1143fn deserialize_present_id<'de, D: Deserializer<'de>>(
1144    deserializer: D,
1145) -> Result<Option<Id<'de>>, D::Error> {
1146    Id::deserialize(deserializer).map(Some)
1147}
1148
1149/// Decodes a [`ValidBatchEntry`] from a JSON object only, because its derived `Deserialize` impl
1150/// also accepts a JSON array holding the fields in order.
1151struct ValidBatchEntrySeed;
1152
1153impl<'de> DeserializeSeed<'de> for ValidBatchEntrySeed {
1154    type Value = ValidBatchEntry<'de>;
1155
1156    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
1157        deserializer.deserialize_map(self)
1158    }
1159}
1160
1161impl<'de> Visitor<'de> for ValidBatchEntrySeed {
1162    type Value = ValidBatchEntry<'de>;
1163
1164    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1165        formatter.write_str("a JSON-RPC request object")
1166    }
1167
1168    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
1169        ValidBatchEntry::deserialize(MapAccessDeserializer::new(map))
1170    }
1171}
1172
1173/// Reads a JSON array of batch entries into `entries`.
1174///
1175/// Entries are decoded as they are read, or, if `raw`, classified from their raw JSON, after
1176/// skipping the entries that `entries` already holds.
1177///
1178/// Stops with an error as soon as an entry beyond `max_len` is read and sets `too_big`, so an
1179/// oversized batch is never collected.
1180struct BatchSeed<'a, 'de> {
1181    max_len: usize,
1182    too_big: &'a mut bool,
1183    entries: &'a mut Vec<Result<BatchEntry<'de>, BatchEntryErr<'de>>>,
1184    raw: bool,
1185}
1186
1187impl<'de> DeserializeSeed<'de> for BatchSeed<'_, 'de> {
1188    type Value = ();
1189
1190    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
1191        deserializer.deserialize_seq(self)
1192    }
1193}
1194
1195impl<'de> Visitor<'de> for BatchSeed<'_, 'de> {
1196    type Value = ();
1197
1198    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1199        formatter.write_str("a batch of JSON-RPC requests")
1200    }
1201
1202    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
1203        if self.raw {
1204            for _ in 0..self.entries.len() {
1205                seq.next_element::<IgnoredAny>()?;
1206            }
1207        }
1208
1209        loop {
1210            if self.entries.len() == self.max_len {
1211                // Read the excess entry without decoding or allocating its fields.
1212                if seq.next_element::<&'de JsonRawValue>()?.is_some() {
1213                    *self.too_big = true;
1214                    return Err(A::Error::custom("batch too big"));
1215                }
1216                return Ok(());
1217            }
1218
1219            let entry = if self.raw {
1220                seq.next_element::<&'de JsonRawValue>()?.map(parse_batch_entry)
1221            } else {
1222                seq.next_element_seed(ValidBatchEntrySeed)?.map(|entry| Ok(entry.into()))
1223            };
1224            let Some(entry) = entry else { return Ok(()) };
1225
1226            // Not preallocated from the size hint, which the input controls.
1227            self.entries.push(entry);
1228        }
1229    }
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234    use super::*;
1235    use futures_util::{future, stream};
1236    use http_body::{Body, Frame};
1237    use http_body_util::StreamBody;
1238    use hyper::{header::CONTENT_TYPE, Method, StatusCode, Version};
1239    use std::convert::Infallible;
1240    use test_case::test_case;
1241
1242    const CALL: &str = r#"{"jsonrpc":"2.0","method":"m","params":[1],"id":1}"#;
1243
1244    const NOTIFICATION: &str = r#"{"jsonrpc":"2.0","method":"m"}"#;
1245
1246    /// Classifies every entry of `body` from its raw JSON.
1247    fn classify_raw_batch(body: &str, max_len: usize) -> Option<String> {
1248        let (mut entries, mut too_big) = (Vec::new(), false);
1249        let mut deserializer = serde_json::Deserializer::from_str(body);
1250        BatchSeed { max_len, too_big: &mut too_big, entries: &mut entries, raw: true }
1251            .deserialize(&mut deserializer)
1252            .and_then(|()| deserializer.end())
1253            .ok()
1254            .map(|()| format!("{entries:?}"))
1255    }
1256
1257    #[tokio::test]
1258    async fn try_accept_conn_observes_stop_before_a_waiting_connection() {
1259        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1260        let addr = listener.local_addr().unwrap();
1261
1262        let _client = TcpStream::connect(addr).await.unwrap();
1263        // Let the kernel put the connection in the backlog, so that `accept` would hand it over on
1264        // its first poll and only the polling order keeps it waiting.
1265        tokio::time::sleep(Duration::from_millis(50)).await;
1266
1267        let accepted = try_accept_conn(&listener, future::ready(())).await;
1268        assert!(matches!(accepted, AcceptConnection::Shutdown));
1269    }
1270
1271    #[tokio::test(start_paused = true)]
1272    async fn http2_body_read_timeout_ends_stream_with_headers() {
1273        let (_stop_tx, stop_rx) = watch::channel(());
1274        let mut service = TowerServiceNoHttp {
1275            inner: Arc::new(ServiceData {
1276                methods: Methods::new(),
1277                stop_handle: StopHandle::new(stop_rx),
1278                conn_id: 0,
1279                conn_guard: ConnectionGuard::new(1),
1280                server_cfg: ServerConfig::builder()
1281                    .set_request_body_read_timeout(Some(Duration::from_secs(1)))
1282                    .build(),
1283                http_rpc_service: OnceLock::new(),
1284            }),
1285            rpc_middleware: RpcServiceBuilder::new(),
1286        };
1287        let request = HttpRequest::builder()
1288            .method(Method::POST)
1289            .version(Version::HTTP_2)
1290            .header(CONTENT_TYPE, "application/json")
1291            .body(StreamBody::new(stream::pending::<Result<Frame<Bytes>, Infallible>>()))
1292            .unwrap();
1293
1294        let response = tokio::time::timeout(Duration::from_secs(2), service.call(request))
1295            .await
1296            .unwrap()
1297            .unwrap();
1298        assert_eq!(response.status(), StatusCode::REQUEST_TIMEOUT);
1299        assert!(response.body().is_end_stream());
1300    }
1301
1302    #[test_case(&[CALL, CALL], usize::MAX; "calls")]
1303    #[test_case(&[CALL, NOTIFICATION, r#"{"jsonrpc":"2.0","method":"m","id":null}"#], usize::MAX; "call, notification and null id")]
1304    #[test_case(&[r#"{"id":"a","params":null,"method":"\"m\"","x":1,"jsonrpc":"2.0"}"#], usize::MAX; "escaped method, null params and unknown member")]
1305    #[test_case(&[CALL, r#"{"jsonrpc":"2.0","id":2}"#, NOTIFICATION, CALL], usize::MAX; "missing method between valid entries")]
1306    #[test_case(&[r#"{"jsonrpc":"1.0","method":"m","id":3}"#, CALL], usize::MAX; "wrong version first")]
1307    #[test_case(&[CALL, r#"{"jsonrpc":"2.0","method":"m","id":{}}"#], usize::MAX; "object id")]
1308    #[test_case(&[CALL, r#"{"jsonrpc":"2.0","method":"m","id":1,"id":2}"#], usize::MAX; "duplicate id")]
1309    #[test_case(&[CALL, r#"["2.0",2,"m",[]]"#, "7", CALL], usize::MAX; "array and number entries")]
1310    #[test_case(&[CALL, r#"{"id":2}"#], 2; "invalid entry at the limit")]
1311    #[test_case(&[CALL, r#"{"id":2}"#, CALL], 2; "valid entry past the limit")]
1312    #[test_case(&[CALL, CALL, r#"{"id":2}"#], 2; "invalid entry past the limit")]
1313    #[test_case(&[CALL, r#"{"jsonrpc""#], usize::MAX; "not json")]
1314    fn batch_entries_decode_like_their_raw_json(entries: &[&str], max_len: usize) {
1315        let body = format!("[{}]", entries.join(","));
1316        let batch = parse_batch(body.as_bytes(), max_len)
1317            .ok()
1318            .map(|batch| format!("{:?}", batch.into_iter().collect::<Vec<_>>()));
1319        assert_eq!(batch, classify_raw_batch(&body, max_len));
1320    }
1321
1322    #[test]
1323    fn batch_with_invalid_utf8_is_a_parse_error() {
1324        // Unknown members must still be validated as UTF-8 by the raw pass.
1325        let body = b"[{\"jsonrpc\":\"2.0\",\"method\":\"m\",\"id\":1,\"x\":\"\xff\"}]";
1326        let rp = parse_batch(body, usize::MAX).unwrap_err();
1327        assert_eq!(rp.as_error_code(), Some(ErrorCode::ParseError.code()));
1328    }
1329
1330    #[test]
1331    fn valid_batch_entries_are_calls_or_notifications() {
1332        let body = br#"[{"jsonrpc":"2.0","method":"a","id":null},{"jsonrpc":"2.0","method":"b"}]"#;
1333        let batch = parse_batch(body, usize::MAX).unwrap().into_iter().collect::<Vec<_>>();
1334        assert!(matches!(
1335            batch.as_slice(),
1336            [Ok(BatchEntry::Call(call)), Ok(BatchEntry::Notification(notification))]
1337                if call.id == Id::Null && call.method == "a" && notification.method == "b"
1338        ));
1339    }
1340
1341    #[test_case(&[CALL.as_bytes(), CALL.as_bytes(), b"\"\xff\""], 1, reject_too_big_batch_request(1); "invalid utf8 after excess call")]
1342    #[test_case(&[br#"{"id":2}"#, CALL.as_bytes(), b"\"\xff\""], 1, reject_too_big_batch_request(1); "invalid utf8 after fallback exceeds limit")]
1343    #[test_case(&[CALL.as_bytes(), b"\"\xff\""], 1, ErrorCode::ParseError.into(); "invalid utf8 in excess entry")]
1344    #[test_case(&[b"{\"jsonrpc\":\"2.0\",\"method\":\"m\",\"x\":\"\xff\"}", CALL.as_bytes()], 1, ErrorCode::ParseError.into(); "invalid utf8 before excess entry")]
1345    #[test_case(&[CALL.as_bytes(), br#"{"jsonrpc"#], 1, ErrorCode::ParseError.into(); "malformed excess entry")]
1346    #[test_case(&[CALL.as_bytes(), b"7", b"\"\xff\""], 1, reject_too_big_batch_request(1); "invalid utf8 after excess scalar")]
1347    #[test_case(&[CALL.as_bytes(), b"\"\xff\""], 0, reject_too_big_batch_request(0); "zero limit ignores tail")]
1348    fn batch_limit_preserves_parse_errors(
1349        entries: &[&[u8]],
1350        max_len: usize,
1351        expected: ErrorObject<'_>,
1352    ) {
1353        let body = [b"[".as_slice(), entries.join(b",".as_slice()).as_slice(), b"]"].concat();
1354        assert_eq!(
1355            parse_batch(&body, max_len).unwrap_err().into_json(),
1356            MethodResponse::error(Id::Null, expected).into_json()
1357        );
1358    }
1359
1360    #[test_case(b"[]", 0; "empty batch")]
1361    #[test_case(b"[{\"jsonrpc\":\"2.0\",\"method\":\"m\"}]", 1; "notification")]
1362    fn batch_at_limit_is_accepted(body: &[u8], max_len: usize) {
1363        assert_eq!(parse_batch(body, max_len).unwrap().len(), max_len);
1364    }
1365
1366    #[tokio::test]
1367    async fn unlimited_batch_holds_what_fits_as_valid_requests() {
1368        const MAX_REQUEST_SIZE: u32 = 1_000;
1369        let max_len = MAX_REQUEST_SIZE as usize / (SHORTEST_BATCH_REQUEST.len() + 1);
1370        let batch = |entry: &str, len: usize| format!("[{}]", vec![entry; len].join(","));
1371        let service =
1372            &RpcService::without_subscriptions(Methods::new(), usize::MAX, ConnectionId::default());
1373        let call = |body: String| async move {
1374            handle_rpc_call(
1375                body.as_bytes(),
1376                false,
1377                BatchRequestConfig::Unlimited,
1378                MAX_REQUEST_SIZE,
1379                service,
1380            )
1381            .await
1382        };
1383
1384        // The longest batch of valid requests within the request size limit is accepted.
1385        let longest = batch(SHORTEST_BATCH_REQUEST, max_len);
1386        assert!(longest.len() <= MAX_REQUEST_SIZE as usize);
1387        assert!(batch(SHORTEST_BATCH_REQUEST, max_len + 1).len() > MAX_REQUEST_SIZE as usize);
1388        assert!(call(longest).await.as_error_code().is_none());
1389
1390        // Shorter entries that aren't requests can't make the batch longer.
1391        let invalid = batch("0", max_len + 1);
1392        assert!(invalid.len() <= MAX_REQUEST_SIZE as usize);
1393        assert_eq!(
1394            call(invalid).await.into_json(),
1395            MethodResponse::error(Id::Null, reject_too_big_batch_request(max_len)).into_json()
1396        );
1397    }
1398}