bitwarden_ipc/
ipc_client_ext.rs1use bitwarden_threading::cancellation_token::CancellationToken;
2use serde::{Serialize, de::DeserializeOwned};
3
4use crate::{
5 RpcHandler,
6 broadcast::{BroadcastGroup, EndpointSendResult},
7 endpoint::Endpoint,
8 error::{BroadcastError, RequestError, SubscribeError},
9 ipc_client::IpcClientTypedSubscription,
10 ipc_client_trait::IpcClient,
11 message::{OutgoingMessage, PayloadTypeName, TypedOutgoingMessage},
12 rpc::{
13 error::RpcError,
14 request::RpcRequest,
15 request_message::{RPC_REQUEST_PAYLOAD_TYPE_NAME, RpcRequestMessage},
16 response_message::IncomingRpcResponseMessage,
17 },
18 serde_utils,
19 timeline::{self, Duration, Entry, Track},
20};
21
22pub trait IpcClientExt: IpcClient {
28 fn register_rpc_handler<H>(&self, handler: H) -> impl std::future::Future<Output = ()> + Send
32 where
33 H: RpcHandler + Send + Sync + 'static,
34 {
35 async move {
36 self.register_rpc_handler_erased(H::Request::NAME, Box::new(handler))
37 .await;
38 }
39 }
40
41 fn send_typed<Payload>(
43 &self,
44 payload: Payload,
45 destination: Endpoint,
46 ) -> impl std::future::Future<Output = Result<(), RequestError>> + Send
47 where
48 Payload: Serialize + PayloadTypeName + Send,
49 {
50 async move {
51 let message = TypedOutgoingMessage {
52 payload,
53 destination,
54 }
55 .try_into()
56 .map_err(|e: serde_utils::DeserializeError| {
57 RequestError::Rpc(RpcError::RequestSerialization(e.to_string()))
58 })?;
59
60 self.send(message).await.map_err(RequestError::from)
61 }
62 }
63
64 fn broadcast_typed<Payload>(
67 &self,
68 payload: Payload,
69 group: BroadcastGroup,
70 ) -> impl std::future::Future<Output = Result<Vec<EndpointSendResult>, BroadcastError>> + Send
71 where
72 Payload: Serialize + PayloadTypeName + Send,
73 {
74 async move {
75 let payload =
76 serde_utils::to_vec(&payload).map_err(|e: serde_utils::SerializeError| {
77 BroadcastError::Serialization(e.to_string())
78 })?;
79
80 self.broadcast(group, payload, Some(Payload::PAYLOAD_TYPE_NAME.to_owned()))
81 .await
82 }
83 }
84
85 fn subscribe_typed<Payload>(
88 &self,
89 ) -> impl std::future::Future<
90 Output = Result<IpcClientTypedSubscription<Payload>, SubscribeError>,
91 > + Send
92 where
93 Payload: DeserializeOwned + PayloadTypeName,
94 {
95 async move {
96 Ok(IpcClientTypedSubscription::new(
97 self.subscribe(Some(Payload::PAYLOAD_TYPE_NAME.to_owned()))
98 .await?,
99 ))
100 }
101 }
102
103 fn request<Request>(
112 &self,
113 request: Request,
114 destination: Endpoint,
115 cancellation_token: Option<CancellationToken>,
116 ) -> impl std::future::Future<Output = Result<Request::Response, RequestError>> + Send
117 where
118 Request: RpcRequest + Send,
119 Request::Response: Send,
120 {
121 async move {
122 let _span = timeline::span(Track::Requests, Duration::Actual, || Entry {
123 name: Request::NAME.to_owned(),
124 properties: vec![("Destination", format!("{destination:?}"))],
125 });
126
127 let request_payload = RpcRequestMessage::new(request);
128
129 let mut response_subscription = self
134 .subscribe(Some(request_payload.response_topic.clone()))
135 .await?;
136
137 let payload = serde_utils::to_vec(&request_payload)
140 .map_err(|e| RequestError::Rpc(RpcError::RequestSerialization(e.to_string())))?;
141 let message = OutgoingMessage {
142 payload,
143 destination: destination.clone(),
144 topic: Some(RPC_REQUEST_PAYLOAD_TYPE_NAME.to_owned()),
145 };
146
147 self.send(message).await.map_err(RequestError::from)?;
148
149 let received = loop {
153 let received = response_subscription
154 .receive(cancellation_token.clone())
155 .await
156 .map_err(|e| RequestError::Receive(e.into()))?;
157
158 if received.source.to_endpoint() == destination {
159 break received;
160 }
161
162 tracing::warn!(
163 source = ?received.source,
164 ?destination,
165 "Ignoring RPC response from a source other than the request destination"
166 );
167 };
168
169 let response: IncomingRpcResponseMessage<Request::Response> =
170 serde_utils::from_slice(&received.payload).map_err(|e| {
171 RequestError::Rpc(RpcError::ResponseDeserialization(e.to_string()))
172 })?;
173
174 Ok(response.result?)
175 }
176 }
177}
178
179impl<T: IpcClient + ?Sized> IpcClientExt for T {}