Skip to main content

reth_ipc/server/
mod.rs

1//! JSON-RPC IPC server implementation
2
3use crate::{
4    server::connection::{IpcConn, IpcConnDriver, JsonRpcStream},
5    stream_codec::StreamCodec,
6};
7use futures_util::future::Either;
8use interprocess::local_socket::{
9    tokio::prelude::{LocalSocketListener, LocalSocketStream},
10    traits::tokio::Listener,
11    GenericFilePath, ListenerOptions, ToFsName,
12};
13use jsonrpsee::{
14    core::{server::ConnectionId, TEN_MB_SIZE_BYTES},
15    server::{
16        accept_error_backoff, handle_rpc_call, middleware::rpc::RpcServiceT, stop_channel,
17        BatchRequestConfig, ConnectionGuard, ConnectionPermit, IdProvider, RandomIntegerIdProvider,
18        ServerHandle, StopHandle,
19    },
20    types::{error::reject_too_big_request, Id},
21    BoundedSubscriptions, MethodResponse, MethodSink, Methods,
22};
23use std::{
24    future::Future,
25    io,
26    pin::{pin, Pin},
27    sync::Arc,
28    task::{Context, Poll},
29};
30use tokio::{
31    io::{AsyncRead, AsyncWrite, AsyncWriteExt},
32    sync::{mpsc, oneshot},
33};
34use tokio_util::task::AbortOnDropHandle;
35use tower::{layer::util::Identity, Layer, Service};
36use tracing::{instrument, trace, warn, Instrument};
37
38#[cfg(unix)]
39use interprocess::os::unix::local_socket::ListenerOptionsExt;
40#[cfg(unix)]
41use std::os::unix::fs::PermissionsExt;
42
43pub use jsonrpsee::server::middleware::rpc::{RpcService, RpcServiceBuilder};
44
45mod connection;
46
47/// Number of messages a connection buffers before backpressure kicks in.
48const MESSAGE_BUFFER_CAPACITY: usize = 1024;
49
50/// Ipc Server implementation
51///
52/// This is an adapted `jsonrpsee` Server, but for `Ipc` connections.
53pub struct IpcServer<RpcMiddleware = Identity> {
54    /// The endpoint we listen for incoming transactions
55    endpoint: String,
56    id_provider: Arc<dyn IdProvider>,
57    cfg: Settings,
58    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
59}
60
61impl<RpcMiddleware> IpcServer<RpcMiddleware> {
62    /// Returns the configured endpoint
63    pub fn endpoint(&self) -> String {
64        self.endpoint.clone()
65    }
66}
67
68impl<RpcMiddleware> IpcServer<RpcMiddleware>
69where
70    RpcMiddleware: Layer<RpcService> + Clone + Send + 'static,
71    RpcMiddleware::Service: RpcServiceT + Send + Sync + 'static,
72{
73    /// Start responding to connections requests.
74    ///
75    /// This will run on the tokio runtime until the server is stopped or the `ServerHandle` is
76    /// dropped.
77    ///
78    /// Returns an error if the endpoint cannot be opened or the requested Unix socket permissions
79    /// cannot be parsed or applied before serving requests.
80    ///
81    /// ```
82    /// use jsonrpsee::RpcModule;
83    /// use reth_ipc::server::Builder;
84    /// async fn run_server() -> Result<(), Box<dyn core::error::Error + Send + Sync>> {
85    ///     let server = Builder::default().build("/tmp/my-uds".into());
86    ///     let mut module = RpcModule::new(());
87    ///     module.register_method("say_hello", |_, _| "lo")?;
88    ///     let handle = server.start(module).await?;
89    ///
90    ///     // In this example we don't care about doing shutdown so let's it run forever.
91    ///     // You may use the `ServerHandle` to shut it down or manage it yourself.
92    ///     let server = tokio::spawn(handle.stopped());
93    ///     server.await.unwrap();
94    ///     Ok(())
95    /// }
96    /// ```
97    pub async fn start(
98        mut self,
99        methods: impl Into<Methods>,
100    ) -> Result<ServerHandle, IpcServerStartError> {
101        let methods = methods.into();
102
103        let (stop_handle, server_handle) = stop_channel();
104
105        // use a signal channel to wait until we're ready to accept connections
106        let (tx, rx) = oneshot::channel();
107
108        match self.cfg.tokio_runtime.take() {
109            Some(rt) => rt.spawn(self.start_inner(methods, stop_handle, tx)),
110            None => tokio::spawn(self.start_inner(methods, stop_handle, tx)),
111        };
112        rx.await.expect("channel is open")?;
113
114        Ok(server_handle)
115    }
116
117    async fn start_inner(
118        self,
119        methods: Methods,
120        stop_handle: StopHandle,
121        on_ready: oneshot::Sender<Result<(), IpcServerStartError>>,
122    ) {
123        trace!(endpoint = ?self.endpoint, "starting ipc server");
124
125        let listener =
126            match self.endpoint.as_str().to_fs_name::<GenericFilePath>().and_then(|name| {
127                // Unlinks an existing endpoint only after binding to it fails, so earlier errors
128                // such as an unsupported mode leave it in place.
129                let options = ListenerOptions::new().name(name).try_overwrite(true);
130
131                #[cfg(unix)]
132                let mode = self
133                    .cfg
134                    .ipc_socket_permissions
135                    .as_deref()
136                    .map(|permissions| {
137                        let mode = u32::from_str_radix(
138                            permissions.strip_prefix("0o").unwrap_or(permissions),
139                            8,
140                        )
141                        .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
142                        if mode > 0o7777 {
143                            return Err(io::Error::new(
144                                io::ErrorKind::InvalidInput,
145                                format!("IPC socket permissions `{permissions}` exceed 0o7777"),
146                            ));
147                        }
148                        Ok(mode)
149                    })
150                    .transpose()?;
151
152                #[cfg(unix)]
153                let options = if let Some(mode) = mode {
154                    // Set the mode before bind/listen so connections cannot bypass it during
155                    // startup. The range check keeps the cast lossless where `mode_t` is `u16`.
156                    options.mode(mode as _)
157                } else {
158                    options
159                };
160
161                let listener = options.create_tokio()?;
162
163                #[cfg(unix)]
164                if let Some(mode) = mode {
165                    // Binding can further restrict the requested mode through the process umask.
166                    std::fs::set_permissions(
167                        &self.endpoint,
168                        std::fs::Permissions::from_mode(mode),
169                    )?;
170                }
171
172                Ok(listener)
173            }) {
174                Ok(listener) => listener,
175                Err(err) => {
176                    on_ready
177                        .send(Err(IpcServerStartError {
178                            endpoint: self.endpoint.clone(),
179                            source: err,
180                        }))
181                        .ok();
182                    return;
183                }
184            };
185
186        // signal that we're ready to accept connections
187        on_ready.send(Ok(())).ok();
188
189        let connection_guard = ConnectionGuard::new(self.cfg.max_connections as usize);
190
191        let stopped = stop_handle.clone().shutdown();
192        let mut stopped = pin!(stopped);
193
194        let (drop_on_completion, mut process_connection_awaiter) = mpsc::channel::<()>(1);
195
196        trace!("accepting ipc connections");
197        loop {
198            match try_accept_conn(&listener, stopped).await {
199                AcceptConnection::Established { local_socket_stream, stop } => {
200                    let Some(conn_permit) = connection_guard.try_acquire() else {
201                        let _ = (&local_socket_stream)
202                            .write_all(b"Too many connections. Please try again later.")
203                            .await;
204                        stopped = stop;
205                        continue;
206                    };
207
208                    let max_conns = connection_guard.max_connections();
209                    let curr_conns = max_conns - connection_guard.available_connections();
210                    trace!("Accepting new connection {}/{}", curr_conns, max_conns);
211
212                    process_connection(ProcessConnection {
213                        rpc_middleware: self.rpc_middleware.clone(),
214                        conn_permit,
215                        conn_id: ConnectionId::next_unique().0,
216                        server_cfg: self.cfg.clone(),
217                        stop_handle: stop_handle.clone(),
218                        drop_on_completion: drop_on_completion.clone(),
219                        methods: methods.clone(),
220                        id_provider: self.id_provider.clone(),
221                        local_socket_stream,
222                    });
223
224                    stopped = stop;
225                }
226                AcceptConnection::Shutdown => {
227                    break;
228                }
229                AcceptConnection::Err((err, stop)) => {
230                    tracing::error!(%err, "Failed accepting a new IPC connection");
231                    let Some(stop) = accept_error_backoff(&err, stop).await else { break };
232                    stopped = stop;
233                }
234            }
235        }
236
237        // Drop the last Sender
238        drop(drop_on_completion);
239
240        // Once this channel is closed it is safe to assume that all connections have been
241        // gracefully shutdown
242        while process_connection_awaiter.recv().await.is_some() {
243            // Generally, messages should not be sent across this channel,
244            // but we'll loop here to wait for `None` just to be on the safe side
245        }
246    }
247}
248
249enum AcceptConnection<S> {
250    Shutdown,
251    Established { local_socket_stream: LocalSocketStream, stop: S },
252    Err((io::Error, S)),
253}
254
255async fn try_accept_conn<S>(listener: &LocalSocketListener, stopped: S) -> AcceptConnection<S>
256where
257    S: Future + Unpin,
258{
259    // `select` polls its first argument first and returns as soon as that one is ready, so the
260    // stop signal has to come first: with `accept` first, a listener that keeps returning without
261    // ever pending starves the stop signal and the server can no longer be stopped.
262    match futures_util::future::select(stopped, pin!(listener.accept())).await {
263        Either::Left(_) => AcceptConnection::Shutdown,
264        Either::Right((res, stop)) => match res {
265            Ok(local_socket_stream) => AcceptConnection::Established { local_socket_stream, stop },
266            Err(e) => AcceptConnection::Err((e, stop)),
267        },
268    }
269}
270
271impl<RpcMiddleware> std::fmt::Debug for IpcServer<RpcMiddleware> {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        f.debug_struct("IpcServer")
274            .field("endpoint", &self.endpoint)
275            .field("cfg", &self.cfg)
276            .field("id_provider", &self.id_provider)
277            .finish()
278    }
279}
280
281/// Error thrown when server couldn't be started.
282#[derive(Debug, thiserror::Error)]
283#[error("failed to listen on ipc endpoint `{endpoint}`: {source}")]
284pub struct IpcServerStartError {
285    endpoint: String,
286    #[source]
287    source: io::Error,
288}
289
290/// Data required by the server to handle requests received via an IPC connection
291#[derive(Debug)]
292struct ServiceData<S> {
293    /// RPC service of the connection.
294    rpc_service: S,
295    /// Connection Permit.
296    _conn_permit: ConnectionPermit,
297    /// Maximum size in bytes of a request.
298    max_request_body_size: u32,
299}
300
301/// Turns raw IPC messages into serialized JSON-RPC responses.
302///
303/// Every call runs in its own task, so the connection's state is shared behind an [`Arc`].
304#[derive(Debug)]
305struct TowerServiceNoHttp<S> {
306    inner: Arc<ServiceData<S>>,
307}
308
309impl<S> Service<String> for TowerServiceNoHttp<S>
310where
311    S: RpcServiceT + Send + Sync + 'static,
312{
313    /// The response of a handled RPC call
314    ///
315    /// This is an `Option` because subscriptions and call responses are handled differently.
316    /// This will be `Some` for calls, and `None` for subscriptions and notifications, because the
317    /// subscription response will be emitted via the `method_sink`.
318    type Response = Option<String>;
319
320    type Error = Box<dyn core::error::Error + Send + Sync + 'static>;
321
322    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
323
324    /// Opens door for back pressure implementation.
325    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
326        Poll::Ready(Ok(()))
327    }
328
329    fn call(&mut self, request: String) -> Self::Future {
330        trace!(request_bytes = request.len(), "Received IPC request");
331
332        let max_request_body_size = self.inner.max_request_body_size;
333        let conn = self.inner.clone();
334        // an ipc connection needs to handle read+write concurrently
335        // even if the underlying rpc handler spawns the actual work or is does a lot of async any
336        // additional overhead performed by `handle_request` can result in I/O latencies, for
337        // example tracing calls are relatively CPU expensive on serde::serialize alone, moving this
338        // work to a separate task takes the pressure off the connection so all concurrent responses
339        // are also serialized concurrently and the connection can focus on read+write
340        //
341        // The connection drops its pending calls when it closes, so the call must not outlive the
342        // returned future, otherwise it keeps running without anyone waiting for the response.
343        let f = AbortOnDropHandle::new(tokio::task::spawn(async move {
344            let rp = if request.len() > max_request_body_size as usize {
345                MethodResponse::error(Id::Null, reject_too_big_request(max_request_body_size))
346            } else {
347                let is_single = request.chars().find_map(|c| match c {
348                    '{' => Some(true),
349                    '[' => Some(false),
350                    _ => None,
351                });
352                handle_rpc_call(
353                    request.as_bytes(),
354                    is_single.unwrap_or(true),
355                    BatchRequestConfig::Unlimited,
356                    max_request_body_size,
357                    &conn.rpc_service,
358                )
359                .await
360            };
361            // IPC writes a response as one message, so a streamed one is buffered.
362            let rp = rp.buffer().await;
363            drop(conn);
364
365            (rp.is_method_call() || rp.is_batch()).then(|| rp.into_json())
366        }));
367
368        Box::pin(async move {
369            // Call panics are answered by the call itself. Anything left here has no request id to
370            // respond to, and the connection writes errors verbatim, which would corrupt the
371            // stream.
372            Ok(f.await.unwrap_or_else(|err| {
373                warn!(%err, "IPC call task failed");
374                None
375            }))
376        })
377    }
378}
379
380struct ProcessConnection<RpcMiddleware> {
381    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
382    conn_permit: ConnectionPermit,
383    conn_id: usize,
384    server_cfg: Settings,
385    stop_handle: StopHandle,
386    drop_on_completion: mpsc::Sender<()>,
387    methods: Methods,
388    id_provider: Arc<dyn IdProvider>,
389    local_socket_stream: LocalSocketStream,
390}
391
392/// Spawns the IPC connection onto a new task
393#[instrument(name = "connection", skip_all, fields(conn_id = %params.conn_id), level = "TRACE")]
394fn process_connection<RpcMiddleware>(params: ProcessConnection<RpcMiddleware>)
395where
396    RpcMiddleware: Layer<RpcService> + Send + 'static,
397    RpcMiddleware::Service: RpcServiceT + Send + Sync + 'static,
398{
399    let ProcessConnection {
400        rpc_middleware,
401        conn_permit,
402        conn_id,
403        server_cfg,
404        stop_handle,
405        drop_on_completion,
406        id_provider,
407        methods,
408        local_socket_stream,
409    } = params;
410
411    let codec =
412        StreamCodec::stream_incoming().with_max_length(server_cfg.max_request_body_size as usize);
413    let ipc = IpcConn(tokio_util::codec::Decoder::framed(codec, local_socket_stream));
414
415    let (tx, rx) = mpsc::channel::<String>(MESSAGE_BUFFER_CAPACITY);
416    let method_sink = MethodSink::new_with_limit(tx, server_cfg.max_response_body_size);
417    let rpc_service = rpc_middleware.service(RpcService::new(
418        methods,
419        server_cfg.max_response_body_size as usize,
420        conn_id.into(),
421        BoundedSubscriptions::new(server_cfg.max_subscriptions_per_connection),
422        method_sink,
423        id_provider,
424    ));
425    let service = TowerServiceNoHttp {
426        inner: Arc::new(ServiceData {
427            rpc_service,
428            _conn_permit: conn_permit,
429            max_request_body_size: server_cfg.max_request_body_size,
430        }),
431    };
432
433    // `#[instrument]` only spans this function, so the connection span is carried into the task.
434    tokio::spawn(
435        async {
436            to_ipc_service(ipc, service, stop_handle, rx).await;
437            drop(drop_on_completion)
438        }
439        .in_current_span(),
440    );
441}
442
443async fn to_ipc_service<S, T>(
444    ipc: IpcConn<JsonRpcStream<T>>,
445    service: S,
446    stop_handle: StopHandle,
447    rx: mpsc::Receiver<String>,
448) where
449    S: Service<String, Response = Option<String>> + Send + 'static,
450    S::Error: Into<Box<dyn core::error::Error + Send + Sync>>,
451    S::Future: Send + Unpin,
452    T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
453{
454    let conn = IpcConnDriver {
455        conn: ipc,
456        service,
457        pending_calls: Default::default(),
458        items: Default::default(),
459        messages: rx,
460    };
461    let stopped = stop_handle.shutdown();
462
463    tokio::select! {
464        _ = conn => {}
465        _ = stopped => {}
466    }
467}
468
469/// JSON-RPC IPC server settings.
470#[derive(Debug, Clone)]
471pub struct Settings {
472    /// Maximum size in bytes of a request.
473    max_request_body_size: u32,
474    /// Maximum size in bytes of a response.
475    max_response_body_size: u32,
476    /// Maximum number of incoming connections allowed.
477    max_connections: u32,
478    /// Maximum number of subscriptions per connection.
479    max_subscriptions_per_connection: u32,
480    /// Custom tokio runtime to run the server on.
481    tokio_runtime: Option<tokio::runtime::Handle>,
482    /// The permissions to create the IPC socket with.
483    ipc_socket_permissions: Option<String>,
484}
485
486impl Default for Settings {
487    fn default() -> Self {
488        Self {
489            max_request_body_size: TEN_MB_SIZE_BYTES,
490            max_response_body_size: TEN_MB_SIZE_BYTES,
491            max_connections: 100,
492            max_subscriptions_per_connection: 1024,
493            tokio_runtime: None,
494            ipc_socket_permissions: None,
495        }
496    }
497}
498
499/// Builder to configure and create a JSON-RPC server
500#[derive(Debug)]
501pub struct Builder<RpcMiddleware> {
502    settings: Settings,
503    /// Subscription ID provider.
504    id_provider: Arc<dyn IdProvider>,
505    rpc_middleware: RpcServiceBuilder<RpcMiddleware>,
506}
507
508impl Default for Builder<Identity> {
509    fn default() -> Self {
510        Self {
511            settings: Settings::default(),
512            id_provider: Arc::new(RandomIntegerIdProvider),
513            rpc_middleware: RpcServiceBuilder::new(),
514        }
515    }
516}
517
518impl<RpcMiddleware> Builder<RpcMiddleware> {
519    /// Set the maximum size of a request body in bytes. Default is 10 MiB.
520    pub const fn max_request_body_size(mut self, size: u32) -> Self {
521        self.settings.max_request_body_size = size;
522        self
523    }
524
525    /// Set the maximum size of a response body in bytes. Default is 10 MiB.
526    pub const fn max_response_body_size(mut self, size: u32) -> Self {
527        self.settings.max_response_body_size = size;
528        self
529    }
530
531    /// Set the maximum number of connections allowed. Default is 100.
532    pub const fn max_connections(mut self, max: u32) -> Self {
533        self.settings.max_connections = max;
534        self
535    }
536
537    /// Set the maximum number of subscriptions per connection. Default is 1024.
538    pub const fn max_subscriptions_per_connection(mut self, max: u32) -> Self {
539        self.settings.max_subscriptions_per_connection = max;
540        self
541    }
542
543    /// Configure a custom [`tokio::runtime::Handle`] to run the server on.
544    ///
545    /// Default: [`tokio::spawn`]
546    pub fn custom_tokio_runtime(mut self, rt: tokio::runtime::Handle) -> Self {
547        self.settings.tokio_runtime = Some(rt);
548        self
549    }
550
551    /// Sets the permissions for the IPC socket file.
552    ///
553    /// On Unix, accepts an octal mode up to `0o7777` with an optional `0o` prefix. Invalid modes or
554    /// failures to apply them cause [`IpcServer::start`] to return an error. This includes
555    /// platforms that do not support setting socket permissions before binding. `None` uses the
556    /// system's umask. Ignored on non-Unix platforms.
557    pub fn set_ipc_socket_permissions(mut self, permissions: Option<String>) -> Self {
558        self.settings.ipc_socket_permissions = permissions;
559        self
560    }
561
562    /// Configure custom `subscription ID` provider for the server to use
563    /// to when getting new subscription calls.
564    ///
565    /// You may choose static dispatch or dynamic dispatch because
566    /// `IdProvider` is implemented for `Box<T>`.
567    ///
568    /// Default: [`RandomIntegerIdProvider`].
569    ///
570    /// # Examples
571    ///
572    /// ```rust
573    /// use jsonrpsee::server::RandomStringIdProvider;
574    /// use reth_ipc::server::Builder;
575    ///
576    /// // static dispatch
577    /// let builder1 = Builder::default().set_id_provider(RandomStringIdProvider::new(16));
578    ///
579    /// // or dynamic dispatch
580    /// let builder2 = Builder::default().set_id_provider(Box::new(RandomStringIdProvider::new(16)));
581    /// ```
582    pub fn set_id_provider<I: IdProvider + 'static>(mut self, id_provider: I) -> Self {
583        self.id_provider = Arc::new(id_provider);
584        self
585    }
586
587    /// Enable middleware that is invoked on every JSON-RPC call.
588    ///
589    /// The middleware itself is very similar to the `tower middleware` but
590    /// it has a different service trait which takes &self instead &mut self
591    /// which means that you can't use built-in middleware from tower.
592    ///
593    /// Another consequence of `&self` is that you must wrap any of the middleware state in
594    /// a type which is Send and provides interior mutability such `Arc<Mutex>`.
595    ///
596    /// The builder itself exposes a similar API as the [`tower::ServiceBuilder`]
597    /// where it is possible to compose layers to the middleware.
598    pub fn set_rpc_middleware<T>(self, rpc_middleware: RpcServiceBuilder<T>) -> Builder<T> {
599        Builder { settings: self.settings, id_provider: self.id_provider, rpc_middleware }
600    }
601
602    /// Finalize the configuration of the server. Consumes the [`Builder`].
603    pub fn build(self, endpoint: String) -> IpcServer<RpcMiddleware> {
604        IpcServer {
605            endpoint,
606            cfg: self.settings,
607            id_provider: self.id_provider,
608            rpc_middleware: self.rpc_middleware,
609        }
610    }
611}
612
613#[cfg(test)]
614#[expect(missing_docs)]
615pub fn dummy_name() -> String {
616    use rand::Rng;
617    let num: u64 = rand::rng().random();
618    format!(r"/tmp/my-uds-{num}")
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624    use futures::{future::select, StreamExt};
625    use interprocess::local_socket::traits::tokio::Stream as _;
626    use jsonrpsee::{
627        core::{
628            middleware::{Batch, BatchEntry, Notification},
629            server::PendingSubscriptionAcceptError,
630        },
631        types::{
632            error::{OVERSIZED_RESPONSE_CODE, OVERSIZED_RESPONSE_MSG, TOO_MANY_SUBSCRIPTIONS_CODE},
633            ErrorCode, Request,
634        },
635        PendingSubscriptionSink, RpcModule, SubscriptionMessage,
636    };
637    use reth_tracing::init_test_tracing;
638    use serde_json::{json, Value};
639    use std::{
640        pin::pin,
641        sync::atomic::{AtomicUsize, Ordering},
642        time::Duration,
643    };
644    use tokio::sync::{broadcast, mpsc};
645    use tokio_stream::wrappers::BroadcastStream;
646    use tokio_util::codec::FramedRead;
647
648    /// Raw JSON-RPC client that talks to the server over the IPC socket.
649    struct TestClient {
650        recv: FramedRead<LocalSocketStream, StreamCodec>,
651        next_id: u64,
652    }
653
654    impl TestClient {
655        async fn connect(endpoint: &str) -> Self {
656            let name = endpoint.to_fs_name::<GenericFilePath>().unwrap();
657            let stream = LocalSocketStream::connect(name).await.unwrap();
658            Self { recv: FramedRead::new(stream, StreamCodec::stream_incoming()), next_id: 0 }
659        }
660
661        /// Sends a call and returns its response, or `None` if the server closed the
662        /// connection.
663        async fn call(&mut self, method: &str, params: Value) -> Option<Value> {
664            let request = self.request(method, params);
665            self.send(request).await.ok()?;
666            self.recv().await
667        }
668
669        /// Returns the request object for a call with a fresh id.
670        fn request(&mut self, method: &str, params: Value) -> Value {
671            self.next_id += 1;
672            json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params})
673        }
674
675        async fn send(&self, msg: Value) -> io::Result<()> {
676            let mut send = self.recv.get_ref();
677            send.write_all(msg.to_string().as_bytes()).await
678        }
679
680        /// Returns the next message from the server, or `None` if the connection is closed.
681        async fn recv(&mut self) -> Option<Value> {
682            let msg = self.recv.next().await?.ok()?;
683            Some(serde_json::from_str(&msg).unwrap())
684        }
685    }
686
687    /// Returns the error code of a response, or `None` if it succeeded.
688    fn error_code(response: &Value) -> Option<i64> {
689        response.get("error").map(|err| err["code"].as_i64().unwrap())
690    }
691
692    #[cfg(unix)]
693    use std::{os::unix::net::UnixListener, path::Path};
694
695    #[tokio::test]
696    #[cfg(unix)]
697    async fn test_ipc_socket_permissions() {
698        for (permissions, mode) in
699            [("0777", 0o777), ("600", 0o600), ("0600", 0o600), ("0o600", 0o600)]
700        {
701            let endpoint = dummy_name();
702            let server = Builder::default()
703                .set_ipc_socket_permissions(Some(permissions.to_string()))
704                .build(endpoint.clone());
705            match server.start(RpcModule::new(())).await {
706                Ok(handle) if !cfg!(target_os = "macos") => {
707                    let actual = std::fs::metadata(&endpoint).unwrap().permissions().mode();
708                    assert_eq!(actual & 0o777, mode);
709                    handle.stop().unwrap();
710                    tokio::time::timeout(Duration::from_secs(5), handle.stopped()).await.unwrap();
711                }
712                Err(error)
713                    if !cfg!(any(
714                        target_os = "linux",
715                        target_os = "android",
716                        target_os = "openbsd"
717                    )) =>
718                {
719                    assert_eq!(error.source.kind(), io::ErrorKind::Unsupported, "{mode:o}");
720                    assert_eq!(error.endpoint, endpoint);
721                    assert!(!Path::new(&endpoint).exists());
722                }
723                result => panic!("Unexpected IPC startup result: {result:?}"),
724            }
725        }
726    }
727
728    async fn pipe_from_stream_with_bounded_buffer(
729        pending: PendingSubscriptionSink,
730        stream: BroadcastStream<usize>,
731    ) -> Result<(), Box<dyn core::error::Error + Send + Sync>> {
732        let sink = pending.accept().await.unwrap();
733        let closed = sink.closed();
734
735        let mut closed = pin!(closed);
736        let mut stream = pin!(stream);
737
738        loop {
739            match select(closed, stream.next()).await {
740                // subscription closed or stream is closed.
741                Either::Left((_, _)) | Either::Right((None, _)) => break Ok(()),
742
743                // received new item from the stream.
744                Either::Right((Some(Ok(item)), c)) => {
745                    let raw_value = serde_json::value::to_raw_value(&item)?;
746                    let notif = SubscriptionMessage::from(raw_value);
747
748                    // NOTE: this will block until there a spot in the queue
749                    // and you might want to do something smarter if it's
750                    // critical that "the most recent item" must be sent when it is produced.
751                    if sink.send(notif).await.is_err() {
752                        break Ok(());
753                    }
754
755                    closed = c;
756                }
757
758                // Send back the error.
759                Either::Right((Some(Err(e)), _)) => break Err(e.into()),
760            }
761        }
762    }
763
764    // Naive example that broadcasts the produced values to all active subscribers.
765    fn produce_items(tx: broadcast::Sender<usize>) {
766        for c in 1..=100 {
767            std::thread::sleep(std::time::Duration::from_millis(1));
768            let _ = tx.send(c);
769        }
770    }
771
772    #[tokio::test]
773    async fn can_set_the_max_response_body_size() {
774        // init_test_tracing();
775        let endpoint = &dummy_name();
776        let server = Builder::default().max_response_body_size(100).build(endpoint.clone());
777        let mut module = RpcModule::new(());
778        module.register_method("anything", |_, _| "a".repeat(101)).unwrap();
779        let handle = server.start(module).await.unwrap();
780        tokio::spawn(handle.stopped());
781
782        let mut client = TestClient::connect(endpoint).await;
783        let response = client.call("anything", json!([])).await.unwrap();
784        assert!(response["error"]["data"].as_str().unwrap().contains("Exceeded max limit of"));
785    }
786
787    #[tokio::test]
788    async fn can_set_the_max_request_body_size() {
789        init_test_tracing();
790        let endpoint = &dummy_name();
791        let server = Builder::default().max_request_body_size(100).build(endpoint.clone());
792        let mut module = RpcModule::new(());
793        module.register_method("anything", |_, _| "succeed").unwrap();
794        let handle = server.start(module).await.unwrap();
795        tokio::spawn(handle.stopped());
796
797        let mut client = TestClient::connect(endpoint).await;
798        let response = client.call("anything", json!(["a".repeat(101)])).await;
799        assert!(response.is_none_or(|response| error_code(&response).is_some()));
800
801        // The batch is more than 100 bytes.
802        let mut client = TestClient::connect(endpoint).await;
803        let batch = (0..3).map(|_| client.request("anything", json!([]))).collect();
804        client.send(Value::Array(batch)).await.unwrap();
805        let response = client.recv().await;
806        assert!(response.is_none_or(|response| error_code(&response).is_some()));
807    }
808
809    #[tokio::test]
810    async fn can_set_max_connections() {
811        init_test_tracing();
812
813        let endpoint = &dummy_name();
814        let server = Builder::default().max_connections(2).build(endpoint.clone());
815        let mut module = RpcModule::new(());
816        module.register_method("anything", |_, _| "succeed").unwrap();
817        let handle = server.start(module).await.unwrap();
818        tokio::spawn(handle.stopped());
819
820        let mut client1 = TestClient::connect(endpoint).await;
821        let mut client2 = TestClient::connect(endpoint).await;
822        let mut client3 = TestClient::connect(endpoint).await;
823
824        assert_eq!(client1.call("anything", json!([])).await.unwrap()["result"], "succeed");
825        assert_eq!(client2.call("anything", json!([])).await.unwrap()["result"], "succeed");
826        // Third connection is rejected
827        assert!(client3.call("anything", json!([])).await.is_none());
828
829        // Decrement connection count
830        drop(client2);
831        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
832
833        // Can connect again
834        let mut client4 = TestClient::connect(endpoint).await;
835        assert_eq!(client4.call("anything", json!([])).await.unwrap()["result"], "succeed");
836    }
837
838    #[tokio::test(flavor = "multi_thread")]
839    async fn test_pending_call_aborted_on_disconnect() {
840        init_test_tracing();
841
842        let endpoint = &dummy_name();
843        let server = Builder::default().build(endpoint.clone());
844        let (started_tx, started_rx) = oneshot::channel::<()>();
845        let (dropped_tx, dropped_rx) = oneshot::channel::<()>();
846        let mut module = RpcModule::new(std::sync::Mutex::new(Some((started_tx, dropped_tx))));
847        module
848            .register_async_method("hang", |_, ctx| async move {
849                // `dropped_tx` is dropped together with the call
850                let (started_tx, _dropped_tx) = ctx.lock().unwrap().take().unwrap();
851                let _ = started_tx.send(());
852                std::future::pending::<()>().await;
853                "unreachable"
854            })
855            .unwrap();
856        let handle = server.start(module).await.unwrap();
857        tokio::spawn(handle.stopped());
858
859        let mut client = TestClient::connect(endpoint).await;
860        tokio::select! {
861            _ = client.call("hang", json!([])) => panic!("call completed"),
862            _ = started_rx => {}
863        }
864        drop(client);
865
866        let dropped = tokio::time::timeout(std::time::Duration::from_secs(5), dropped_rx).await;
867        assert!(dropped.is_ok(), "call kept running after the connection closed");
868    }
869
870    #[tokio::test]
871    async fn test_panicking_call_returns_internal_error() {
872        init_test_tracing();
873
874        let endpoint = &dummy_name();
875        let server = Builder::default().build(endpoint.clone());
876        let mut module = RpcModule::new(());
877        module
878            .register_async_method("maybe_panic", |params, _| async move {
879                assert!(!params.one::<bool>().unwrap(), "requested panic");
880                "ok"
881            })
882            .unwrap();
883        let handle = server.start(module).await.unwrap();
884        tokio::spawn(handle.stopped());
885
886        let mut client = TestClient::connect(endpoint).await;
887        let response = client.call("maybe_panic", json!([true])).await.unwrap();
888        assert_eq!(
889            error_code(&response),
890            Some(ErrorCode::InternalError.code().into()),
891            "{response}"
892        );
893
894        let batch = vec![
895            client.request("maybe_panic", json!([true])),
896            client.request("maybe_panic", json!([false])),
897        ];
898        client.send(Value::Array(batch)).await.unwrap();
899        let responses = client.recv().await.unwrap();
900        assert_eq!(error_code(&responses[0]), Some(ErrorCode::InternalError.code().into()));
901        assert_eq!(responses[1]["result"], "ok");
902    }
903
904    #[tokio::test]
905    async fn test_invalid_id_is_not_a_notification() {
906        let endpoint = &dummy_name();
907        let server = Builder::default().build(endpoint.clone());
908        let mut module = RpcModule::new(());
909        module.register_method("anything", |_, _| "ok").unwrap();
910        let handle = server.start(module).await.unwrap();
911        tokio::spawn(handle.stopped());
912
913        let mut client = TestClient::connect(endpoint).await;
914        client.send(json!({"jsonrpc": "2.0", "method": "anything", "id": {}})).await.unwrap();
915        // The message used to be treated as a notification and left unanswered.
916        let response = tokio::time::timeout(std::time::Duration::from_secs(5), client.recv())
917            .await
918            .expect("message with an invalid id was not answered")
919            .unwrap();
920        assert_eq!(
921            response,
922            json!({
923                "jsonrpc": "2.0",
924                "id": null,
925                "error": {"code": ErrorCode::InvalidRequest.code(), "message": "Invalid request"},
926            })
927        );
928    }
929
930    #[tokio::test]
931    async fn test_rpc_request() {
932        init_test_tracing();
933        let endpoint = &dummy_name();
934        let server = Builder::default().build(endpoint.clone());
935        let mut module = RpcModule::new(());
936        let msg = r#"{"jsonrpc":"2.0","id":83,"result":"0x7a69"}"#;
937        module.register_method("eth_chainId", move |_, _| msg).unwrap();
938        let handle = server.start(module).await.unwrap();
939        tokio::spawn(handle.stopped());
940
941        let mut client = TestClient::connect(endpoint).await;
942        let response = client.call("eth_chainId", json!([])).await.unwrap();
943        assert_eq!(response["result"], msg);
944    }
945
946    #[tokio::test]
947    async fn test_batch_request() {
948        let endpoint = &dummy_name();
949        let server = Builder::default().build(endpoint.clone());
950        let mut module = RpcModule::new(());
951        module.register_method("anything", |_, _| "ok").unwrap();
952        let handle = server.start(module).await.unwrap();
953        tokio::spawn(handle.stopped());
954
955        let mut client = TestClient::connect(endpoint).await;
956        let batch = (0..3).map(|_| client.request("anything", json!([]))).collect();
957        client.send(Value::Array(batch)).await.unwrap();
958        let responses = client.recv().await.unwrap();
959        let results =
960            responses.as_array().unwrap().iter().map(|r| &r["result"]).collect::<Vec<_>>();
961        assert_eq!(results, vec!["ok", "ok", "ok"]);
962    }
963
964    #[tokio::test]
965    async fn test_ipc_modules() {
966        reth_tracing::init_test_tracing();
967        let endpoint = &dummy_name();
968        let server = Builder::default().build(endpoint.clone());
969        let mut module = RpcModule::new(());
970        let msg = r#"{"admin":"1.0","debug":"1.0","engine":"1.0","eth":"1.0","ethash":"1.0","miner":"1.0","net":"1.0","rpc":"1.0","txpool":"1.0","web3":"1.0"}"#;
971        module.register_method("rpc_modules", move |_, _| msg).unwrap();
972        let handle = server.start(module).await.unwrap();
973        tokio::spawn(handle.stopped());
974
975        let mut client = TestClient::connect(endpoint).await;
976        let response = client.call("rpc_modules", json!([])).await.unwrap();
977        assert_eq!(response["result"], msg);
978    }
979
980    #[tokio::test(flavor = "multi_thread")]
981    async fn test_rpc_subscription() {
982        let endpoint = &dummy_name();
983        let server = Builder::default().build(endpoint.clone());
984        let (tx, _rx) = broadcast::channel::<usize>(16);
985
986        let mut module = RpcModule::new(tx.clone());
987        std::thread::spawn(move || produce_items(tx));
988
989        module
990            .register_subscription(
991                "subscribe_hello",
992                "s_hello",
993                "unsubscribe_hello",
994                |_, pending, tx| async move {
995                    let rx = tx.subscribe();
996                    let stream = BroadcastStream::new(rx);
997                    pipe_from_stream_with_bounded_buffer(pending, stream).await?;
998                    Ok(())
999                },
1000            )
1001            .unwrap();
1002
1003        let handle = server.start(module).await.unwrap();
1004        tokio::spawn(handle.stopped());
1005
1006        let mut client = TestClient::connect(endpoint).await;
1007        let response = client.call("subscribe_hello", json!([])).await.unwrap();
1008        let sub_id = response["result"].clone();
1009
1010        for _ in 0..16 {
1011            let notification = client.recv().await.unwrap();
1012            assert_eq!(notification["method"], "s_hello");
1013            assert_eq!(notification["params"]["subscription"], sub_id);
1014            assert!(notification["params"]["result"].is_u64());
1015        }
1016    }
1017
1018    #[tokio::test(flavor = "multi_thread")]
1019    async fn test_unread_subscription_is_bounded() {
1020        let endpoint = &dummy_name();
1021        let server = Builder::default().build(endpoint.clone());
1022        let sent = Arc::new(AtomicUsize::new(0));
1023        let mut module = RpcModule::new(sent.clone());
1024        module
1025            .register_subscription(
1026                "subscribe_flood",
1027                "s_flood",
1028                "unsubscribe_flood",
1029                |_, pending, sent| async move {
1030                    let sink = pending.accept().await?;
1031                    let msg = serde_json::value::to_raw_value(&"x".repeat(1024)).unwrap();
1032                    while sink.send(msg.clone()).await.is_ok() {
1033                        sent.fetch_add(1, Ordering::Relaxed);
1034                    }
1035                    Ok(())
1036                },
1037            )
1038            .unwrap();
1039        let handle = server.start(module).await.unwrap();
1040        tokio::spawn(handle.stopped());
1041
1042        let mut client = TestClient::connect(endpoint).await;
1043        client.call("subscribe_flood", json!([])).await.unwrap();
1044
1045        // The client doesn't read, so the connection's queues fill up and the subscription stalls.
1046        tokio::time::sleep(Duration::from_millis(500)).await;
1047        let stalled = sent.load(Ordering::Relaxed);
1048        tokio::time::sleep(Duration::from_millis(200)).await;
1049        assert_eq!(sent.load(Ordering::Relaxed), stalled);
1050        assert!(stalled < 3 * MESSAGE_BUFFER_CAPACITY, "{stalled} messages queued");
1051
1052        // Reading again lets the subscription continue.
1053        tokio::time::timeout(Duration::from_secs(10), async {
1054            while sent.load(Ordering::Relaxed) == stalled {
1055                assert_eq!(client.recv().await.unwrap()["method"], "s_flood");
1056            }
1057        })
1058        .await
1059        .unwrap();
1060    }
1061
1062    #[tokio::test(flavor = "multi_thread")]
1063    async fn test_max_subscriptions_per_connection() {
1064        let endpoint = &dummy_name();
1065        let server = Builder::default().max_subscriptions_per_connection(1).build(endpoint.clone());
1066        let mut module = RpcModule::new(());
1067        module
1068            .register_subscription(
1069                "subscribe_hello",
1070                "s_hello",
1071                "unsubscribe_hello",
1072                |_, pending, _| async move {
1073                    let Ok(sink) = pending.accept().await else { return };
1074                    sink.closed().await;
1075                },
1076            )
1077            .unwrap();
1078        let handle = server.start(module).await.unwrap();
1079        tokio::spawn(handle.stopped());
1080
1081        let mut client = TestClient::connect(endpoint).await;
1082        let response = client.call("subscribe_hello", json!([])).await.unwrap();
1083        assert_eq!(error_code(&response), None, "{response}");
1084        let response = client.call("subscribe_hello", json!([])).await.unwrap();
1085        assert_eq!(error_code(&response), Some(TOO_MANY_SUBSCRIPTIONS_CODE.into()), "{response}");
1086    }
1087
1088    #[tokio::test(flavor = "multi_thread")]
1089    async fn test_oversized_subscription_response_returns_error() {
1090        let endpoint = &dummy_name();
1091        let server = Builder::default()
1092            .max_response_body_size(100)
1093            .max_subscriptions_per_connection(1)
1094            .build(endpoint.clone());
1095        let (tx, mut accepted) = mpsc::unbounded_channel();
1096        let mut module = RpcModule::new(tx);
1097        module
1098            .register_subscription(
1099                "subscribe_hello",
1100                "s_hello",
1101                "unsubscribe_hello",
1102                |_, pending, ctx| async move {
1103                    match pending.accept().await {
1104                        Ok(sink) => {
1105                            ctx.send(Ok(())).unwrap();
1106                            sink.closed().await;
1107                        }
1108                        Err(err) => ctx.send(Err(err)).unwrap(),
1109                    }
1110                },
1111            )
1112            .unwrap();
1113        let handle = server.start(module).await.unwrap();
1114        tokio::spawn(handle.stopped());
1115
1116        let mut client = TestClient::connect(endpoint).await;
1117        // The subscribe acknowledgement echoes the request id, so it does not fit into 100 bytes.
1118        let id = "a".repeat(100);
1119        client
1120            .send(json!({"jsonrpc": "2.0", "id": id, "method": "subscribe_hello", "params": []}))
1121            .await
1122            .unwrap();
1123        let response = client.recv().await.unwrap();
1124        assert_eq!(
1125            response,
1126            json!({
1127                "jsonrpc": "2.0",
1128                "id": id,
1129                "error": {
1130                    "code": OVERSIZED_RESPONSE_CODE,
1131                    "message": OVERSIZED_RESPONSE_MSG,
1132                    "data": "Exceeded max limit of 100",
1133                },
1134            })
1135        );
1136        let result = tokio::time::timeout(Duration::from_secs(5), accepted.recv()).await.unwrap();
1137        assert!(matches!(result, Some(Err(PendingSubscriptionAcceptError))), "{result:?}");
1138
1139        // The failed subscription must not keep the connection's only subscription slot.
1140        let response = client.call("subscribe_hello", json!([])).await.unwrap();
1141        assert_eq!(error_code(&response), None, "{response}");
1142        let result = tokio::time::timeout(Duration::from_secs(5), accepted.recv()).await.unwrap();
1143        assert!(matches!(result, Some(Ok(()))), "{result:?}");
1144    }
1145
1146    #[tokio::test]
1147    async fn test_rpc_middleware() {
1148        #[derive(Clone)]
1149        struct ModifyRequestIf<S>(S);
1150
1151        impl<S> RpcServiceT for ModifyRequestIf<S>
1152        where
1153            S: Send + Sync + RpcServiceT,
1154        {
1155            fn call<'a>(
1156                &self,
1157                mut req: Request<'a>,
1158            ) -> impl Future<Output = MethodResponse> + Send + 'a {
1159                // Re-direct all calls that isn't `say_hello` to `say_goodbye`
1160                if req.method == "say_hello" {
1161                    req.method = "say_goodbye".into();
1162                } else if req.method == "say_goodbye" {
1163                    req.method = "say_hello".into();
1164                }
1165
1166                self.0.call(req)
1167            }
1168
1169            fn batch<'a>(
1170                &self,
1171                mut batch: Batch<'a>,
1172            ) -> impl Future<Output = MethodResponse> + Send + 'a {
1173                for call in batch.iter_mut() {
1174                    match call {
1175                        Ok(BatchEntry::Call(req)) => {
1176                            if req.method == "say_hello" {
1177                                req.method = "say_goodbye".into();
1178                            } else if req.method == "say_goodbye" {
1179                                req.method = "say_hello".into();
1180                            }
1181                        }
1182                        Ok(BatchEntry::Notification(n)) => {
1183                            if n.method == "say_hello" {
1184                                n.method = "say_goodbye".into();
1185                            } else if n.method == "say_goodbye" {
1186                                n.method = "say_hello".into();
1187                            }
1188                        }
1189                        // Invalid request, we don't care about it.
1190                        Err(_err) => {}
1191                    }
1192                }
1193
1194                self.0.batch(batch)
1195            }
1196
1197            fn notification<'a>(
1198                &self,
1199                mut n: Notification<'a>,
1200            ) -> impl Future<Output = MethodResponse> + Send + 'a {
1201                if n.method == "say_hello" {
1202                    n.method = "say_goodbye".into();
1203                } else if n.method == "say_goodbye" {
1204                    n.method = "say_hello".into();
1205                }
1206                self.0.notification(n)
1207            }
1208        }
1209
1210        reth_tracing::init_test_tracing();
1211        let endpoint = &dummy_name();
1212
1213        let rpc_middleware = RpcServiceBuilder::new().layer_fn(ModifyRequestIf);
1214        let server = Builder::default().set_rpc_middleware(rpc_middleware).build(endpoint.clone());
1215
1216        let mut module = RpcModule::new(());
1217        let goodbye_msg = r#"{"jsonrpc":"2.0","id":1,"result":"goodbye"}"#;
1218        let hello_msg = r#"{"jsonrpc":"2.0","id":2,"result":"hello"}"#;
1219        module.register_method("say_hello", move |_, _| hello_msg).unwrap();
1220        module.register_method("say_goodbye", move |_, _| goodbye_msg).unwrap();
1221        let handle = server.start(module).await.unwrap();
1222        tokio::spawn(handle.stopped());
1223
1224        let mut client = TestClient::connect(endpoint).await;
1225        let say_hello_response = client.call("say_hello", json!([])).await.unwrap();
1226        let say_goodbye_response = client.call("say_goodbye", json!([])).await.unwrap();
1227
1228        assert_eq!(say_hello_response["result"], goodbye_msg);
1229        assert_eq!(say_goodbye_response["result"], hello_msg);
1230    }
1231
1232    #[tokio::test]
1233    async fn test_rpc_middleware_is_built_once_per_connection() {
1234        let endpoint = &dummy_name();
1235
1236        let built = Arc::new(AtomicUsize::new(0));
1237        let rpc_middleware = RpcServiceBuilder::new().layer_fn({
1238            let built = built.clone();
1239            move |service| {
1240                built.fetch_add(1, Ordering::Relaxed);
1241                service
1242            }
1243        });
1244        let server = Builder::default().set_rpc_middleware(rpc_middleware).build(endpoint.clone());
1245
1246        let mut module = RpcModule::new(());
1247        module.register_method("say_hello", |_, _| "hello").unwrap();
1248        let handle = server.start(module).await.unwrap();
1249        tokio::spawn(handle.stopped());
1250
1251        for connections in 1..=2 {
1252            let mut client = TestClient::connect(endpoint).await;
1253            for _ in 0..2 {
1254                let response = client.call("say_hello", json!([])).await.unwrap();
1255                assert_eq!(response["result"], "hello");
1256            }
1257            assert_eq!(built.load(Ordering::Relaxed), connections);
1258        }
1259    }
1260
1261    #[tokio::test]
1262    #[cfg(unix)]
1263    async fn invalid_ipc_socket_permissions() {
1264        for permissions in
1265            ["not-octal", "", "0o", "888", "0o0o600", "60o00", "100000000000", "10000"]
1266        {
1267            let endpoint = dummy_name();
1268            let server = Builder::default()
1269                .set_ipc_socket_permissions(Some(permissions.to_string()))
1270                .build(endpoint.clone());
1271
1272            let error = server.start(RpcModule::new(())).await.unwrap_err();
1273            assert_eq!(error.source.kind(), io::ErrorKind::InvalidInput, "{permissions}");
1274            assert_eq!(error.endpoint, endpoint);
1275            assert!(!Path::new(&endpoint).exists());
1276        }
1277    }
1278
1279    #[tokio::test]
1280    #[cfg(unix)]
1281    async fn invalid_ipc_permissions_preserve_existing_endpoint() {
1282        for (permissions, kind) in [
1283            ("not-octal", io::ErrorKind::InvalidInput),
1284            #[cfg(target_os = "macos")]
1285            ("0600", io::ErrorKind::Unsupported),
1286        ] {
1287            let endpoint = dummy_name();
1288            let _listener = ListenerOptions::new()
1289                .name(endpoint.as_str().to_fs_name::<GenericFilePath>().unwrap())
1290                .create_tokio()
1291                .unwrap();
1292            let server = Builder::default()
1293                .set_ipc_socket_permissions(Some(permissions.to_string()))
1294                .build(endpoint.clone());
1295
1296            let error = server.start(RpcModule::new(())).await.unwrap_err();
1297            assert_eq!(error.source.kind(), kind, "{permissions}");
1298            assert_eq!(error.endpoint, endpoint);
1299            assert!(Path::new(&endpoint).exists());
1300        }
1301    }
1302
1303    #[tokio::test]
1304    #[cfg(unix)]
1305    async fn replaces_stale_ipc_endpoint() {
1306        let endpoint = dummy_name();
1307        drop(UnixListener::bind(&endpoint).unwrap());
1308        assert!(Path::new(&endpoint).exists());
1309
1310        let handle =
1311            Builder::default().build(endpoint.clone()).start(RpcModule::new(())).await.unwrap();
1312        handle.stop().unwrap();
1313        tokio::time::timeout(Duration::from_secs(5), handle.stopped()).await.unwrap();
1314    }
1315}