Expand description
Contains the ServerBuilder for configuring and launching servers.
This module provides the ServerBuilder for configuring and launching multiple RPC servers
from a single service implementation.
When you use multi-rpc, your single service object is shared across all the different
protocol servers you enable (e.g., tarpc, REST, jsonrpsee). To make this safe and efficient,
we rely on two key synchronization primitives: Arc and Mutex.
§Arc for Shared Ownership
The std::sync::Arc (Atomically Reference Counted) enables your single service instance to be
owned by multiple server tasks simultaneously. When you launch a server for a protocol, it
receives a clone of the Arc, giving it a reference to the same underlying service. This
prevents the need to duplicate your service’s state for each server and ensures all requests
are handled by the same, consistent logic.
§Mutex for Thread-Safe Access
The tokio::sync::Mutex provides exclusive, thread-safe access to your service object.
While Arc allows multiple threads to own a reference, it doesn’t prevent them from
trying to modify the data at the same time. The Mutex ensures that only one server
task can access or modify the service’s state at any given moment. This is crucial for
methods that take &mut self as it prevents data races and keeps your application’s
state consistent. We use the tokio version of Mutex because it works seamlessly
with asynchronous code, allowing locks to be held across .await points without blocking
the entire thread.
§Using ServerBuilder
You use the ServerBuilder to set up your server:
- Create a new builder with your service object.
- Use
add_protocolto specify the protocols and network addresses for each server you want to run. - Call
build()to create the servers. - Finally, call
run()on the resultingServerRunnerto start listening for requests.