Skip to main content

karo_common_rpc/
request.rs

1use bson::Bson;
2use serde::Serialize;
3use tokio::net::UnixStream;
4
5use super::writer::RpcWriter;
6
7/// Incoming message body
8pub enum Body {
9    /// Method call
10    Call(Bson),
11    /// Method subscription
12    Subscription,
13    /// Incoming connection request in a form of UnixStream
14    Fd(String, UnixStream),
15}
16
17/// Client request
18pub struct RpcRequest {
19    /// Message id from the client
20    message_id: i64,
21    /// Writer to repond to the message
22    writer: RpcWriter,
23    /// Requested endpoint name
24    endpoint: String,
25    /// Body. It's an option to allow user to steal body data
26    body: Option<Body>,
27}
28
29impl RpcRequest {
30    pub(crate) fn new(message_id: i64, writer: RpcWriter, endpoint: String, body: Body) -> Self {
31        Self {
32            message_id,
33            writer,
34            endpoint,
35            body: Some(body),
36        }
37    }
38
39    pub fn writer(&self) -> &RpcWriter {
40        &self.writer
41    }
42
43    /// Request body. Moves the body out of the request. Can be used only once
44    /// All subsequent calls will return `None`
45    pub fn take_body(&mut self) -> Option<Body> {
46        self.body.take()
47    }
48
49    /// Requested endpoint
50    pub fn endpoint(&self) -> &String {
51        &self.endpoint
52    }
53
54    /// Respond to the call
55    pub async fn respond<T: Serialize>(&self, data: Result<T, crate::Error>) -> bool {
56        self.writer.respond(self.message_id, data).await
57    }
58
59    /// Respond with FD
60    pub async fn respond_with_fd<T: Serialize>(
61        &self,
62        data: Result<T, crate::Error>,
63        stream: UnixStream,
64    ) -> bool {
65        self.writer
66            .respond_with_fd(self.message_id, data, stream)
67            .await
68    }
69}