Producing
A producer is the server-side implementation of your RPC API. It receives requests from the consumer, executes the requested methods, and sends responses or stream items back.
Implementing a producer
Suppose you have the following API:
#[api]
pub trait Api {
async fn add_numbers(&self, a: i32, b: i32) -> i32;
#[no_ack]
async fn hello_world(&self);
async fn stream_time(&self, interval: Duration) -> impl Stream<Item = NaiveTime>;
}
You can implement it on any type:
#[derive(Produce)]
pub struct Producer;
impl Producer {
async fn add_numbers(&self, a: i32, b: i32) -> i32 {
a + b
}
async fn hello_world(&self) {
println!("Hello World!");
}
fn stream_time(
&self,
interval: Duration,
) -> impl Stream<Item = NaiveTime> {
// ...
}
}
The Produce derive macro uses the generated impl_produce! macro from #[api] to generate the RPC dispatch implementation.
Note
impl_produce!,Request,Responsemust be in scope for theProducederive macro to work.
It is generated by the#[api]macro alongside theRequest,Response, andConsumertypes.
Why not implement API’s async trait?
dnet deliberately does not expect producers to implement the API trait to avoid current limitations of the Rust’s async traits.
Instead Produce derive macro uses impl_produce! internally to glue itself to methods implemented directly on your type.
Abortable methods
An abortable API method:
#[abortable]
async fn long_task(&self);
expects the producer implementation to have an additional AbortionToken argument:
async fn long_task(
&self,
token: AbortionToken,
) {
// ...
}
The token becomes cancelled when the consumer aborts the request or stream, allowing the producer to stop any ongoing work.
Producing
Once your producer implementation is ready, you can call produce(...) over a dnet transport:
use dnet::rpc::producer::Produce;
use dnet::{codecs::BincodeCodec, tcp::TcpTransport};
let listener = tokio::net::TcpListener::bind(address).await?;
loop {
let (stream, peer) = listener.accept().await?;
let transport = TcpTransport::buffered(stream, BincodeCodec::default());
let producer = Producer::new();
tokio::spawn(async move {
let shutdown = producer
.produce(transport, Default::default(), Default::default())
.await;
tracing::info!("Connection {} finished: {:?}", peer, shutdown);
});
}
Where to go next
Read the Consuming page to learn how to consume the API on the client side.