Skip to main content

krossbar_rpc/
request.rs

1use std::fmt::{Debug, Formatter, Result as FmtResult};
2
3use bson::Bson;
4use serde::Serialize;
5use tokio::net::UnixStream;
6
7use super::writer::RpcWriter;
8
9/// Incoming message body
10#[derive(Debug)]
11pub enum Body {
12    /// One way message
13    Message(Bson),
14    /// Method call
15    Call(Bson),
16    /// Method subscription
17    Subscription,
18    /// Incoming connection request in a form of UnixStream
19    Fd {
20        client_name: String,
21        target_name: String,
22        stream: UnixStream,
23    },
24}
25
26/// Client request
27pub struct RpcRequest {
28    /// Message id from the client
29    message_id: i64,
30    /// Writer to repond to the message
31    writer: RpcWriter,
32    /// Requested endpoint name
33    endpoint: String,
34    /// Body. It's an option to allow user to steal body data
35    body: Option<Body>,
36}
37
38impl RpcRequest {
39    pub(crate) fn new(message_id: i64, writer: RpcWriter, endpoint: String, body: Body) -> Self {
40        Self {
41            message_id,
42            writer,
43            endpoint,
44            body: Some(body),
45        }
46    }
47
48    pub fn message_id(&self) -> i64 {
49        self.message_id
50    }
51
52    /// Writer to write response into
53    pub fn writer(&self) -> &RpcWriter {
54        &self.writer
55    }
56
57    /// Verbose peer name
58    pub fn peer_name(&self) -> &str {
59        self.writer.peer_name()
60    }
61
62    /// Request body. Moves the body out of the request. Can be used only once
63    /// All subsequent calls will return `None`
64    pub fn take_body(&mut self) -> Option<Body> {
65        self.body.take()
66    }
67
68    /// Peek request body
69    pub fn body(&self) -> &Option<Body> {
70        &self.body
71    }
72
73    /// Requested endpoint
74    pub fn endpoint(&self) -> &String {
75        &self.endpoint
76    }
77
78    /// Respond to the call
79    pub async fn respond<T: Serialize>(&self, data: Result<T, crate::Error>) -> bool {
80        self.writer.respond(self.message_id, data).await
81    }
82
83    /// Respond with FD
84    pub async fn respond_with_fd<T: Serialize>(
85        &self,
86        data: Result<T, crate::Error>,
87        stream: UnixStream,
88    ) -> bool {
89        self.writer
90            .respond_with_fd(self.message_id, data, stream)
91            .await
92    }
93}
94
95impl Debug for RpcRequest {
96    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
97        write!(
98            f,
99            "RpcRequest {{ message_id: {}, endpoint: \"{}\", body: {:?} }}",
100            self.message_id, self.endpoint, self.body
101        )
102    }
103}