-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
rpc.rs
327 lines (295 loc) · 8.39 KB
/
rpc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
use std::{
collections::HashMap,
sync::{
atomic::{AtomicU32, Ordering},
Arc, Mutex,
},
};
use futures::{
future::{self, BoxFuture},
Future, FutureExt,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tokio::sync::oneshot;
use crate::util::errors::AnyError;
pub type SyncMethod = Arc<dyn Send + Sync + Fn(Option<u32>, &[u8]) -> Option<Vec<u8>>>;
pub type AsyncMethod =
Arc<dyn Send + Sync + Fn(Option<u32>, &[u8]) -> BoxFuture<'static, Option<Vec<u8>>>>;
pub enum Method {
Sync(SyncMethod),
Async(AsyncMethod),
}
/// Serialization is given to the RpcBuilder and defines how data gets serialized
/// when callinth methods.
pub trait Serialization: Send + Sync + 'static {
fn serialize(&self, value: impl Serialize) -> Vec<u8>;
fn deserialize<P: DeserializeOwned>(&self, b: &[u8]) -> Result<P, AnyError>;
}
/// RPC is a basic, transport-agnostic builder for RPC methods. You can
/// register methods to it, then call `.build()` to get a "dispatcher" type.
pub struct RpcBuilder<S, C> {
context: Arc<C>,
serializer: Arc<S>,
methods: HashMap<&'static str, Method>,
}
impl<S: Serialization, C: Send + Sync + 'static> RpcBuilder<S, C> {
/// Creates a new empty RPC builder.
pub fn new(serializer: S, context: C) -> Self {
Self {
context: Arc::new(context),
serializer: Arc::new(serializer),
methods: HashMap::new(),
}
}
/// Registers a synchronous rpc call that returns its result directly.
pub fn register_sync<P, R, F>(&mut self, method_name: &'static str, callback: F)
where
P: DeserializeOwned,
R: Serialize,
F: Fn(P, &C) -> Result<R, AnyError> + Send + Sync + 'static,
{
let serial = self.serializer.clone();
let context = self.context.clone();
self.methods.insert(
method_name,
Method::Sync(Arc::new(move |id, body| {
let param = match serial.deserialize::<RequestParams<P>>(body) {
Ok(p) => p,
Err(err) => {
return id.map(|id| {
serial.serialize(&ErrorResponse {
id,
error: ResponseError {
code: 0,
message: format!("{:?}", err),
},
})
})
}
};
match callback(param.params, &context) {
Ok(result) => id.map(|id| serial.serialize(&SuccessResponse { id, result })),
Err(err) => id.map(|id| {
serial.serialize(&ErrorResponse {
id,
error: ResponseError {
code: -1,
message: format!("{:?}", err),
},
})
}),
}
})),
);
}
/// Registers an async rpc call that returns a Future.
pub fn register_async<P, R, Fut, F>(&mut self, method_name: &'static str, callback: F)
where
P: DeserializeOwned + Send + 'static,
R: Serialize + Send + Sync + 'static,
Fut: Future<Output = Result<R, AnyError>> + Send,
F: (Fn(P, Arc<C>) -> Fut) + Clone + Send + Sync + 'static,
{
let serial = self.serializer.clone();
let context = self.context.clone();
self.methods.insert(
method_name,
Method::Async(Arc::new(move |id, body| {
let param = match serial.deserialize::<RequestParams<P>>(body) {
Ok(p) => p,
Err(err) => {
return future::ready(id.map(|id| {
serial.serialize(&ErrorResponse {
id,
error: ResponseError {
code: 0,
message: format!("{:?}", err),
},
})
}))
.boxed();
}
};
let callback = callback.clone();
let serial = serial.clone();
let context = context.clone();
let fut = async move {
match callback(param.params, context).await {
Ok(result) => {
id.map(|id| serial.serialize(&SuccessResponse { id, result }))
}
Err(err) => id.map(|id| {
serial.serialize(&ErrorResponse {
id,
error: ResponseError {
code: -1,
message: format!("{:?}", err),
},
})
}),
}
};
fut.boxed()
})),
);
}
/// Builds into a usable, sync rpc dispatcher.
pub fn build(self) -> RpcDispatcher<S, C> {
RpcDispatcher {
i: Arc::new(self),
calls: Arc::new(std::sync::Mutex::new(HashMap::new())),
}
}
}
type DispatchMethod = Box<dyn Send + Sync + FnOnce(Outcome)>;
/// Dispatcher returned from a Builder that provides a transport-agnostic way to
/// deserialize and handle RPC calls. This structure may get more advanced as
/// time goes on...
pub struct RpcDispatcher<S, C> {
i: Arc<RpcBuilder<S, C>>,
calls: Arc<Mutex<HashMap<u32, DispatchMethod>>>,
}
impl<S, C> Clone for RpcDispatcher<S, C> {
fn clone(&self) -> Self {
RpcDispatcher {
i: self.i.clone(),
calls: self.calls.clone(),
}
}
}
static MESSAGE_ID_COUNTER: AtomicU32 = AtomicU32::new(0);
fn next_message_id() -> u32 {
MESSAGE_ID_COUNTER.fetch_add(1, Ordering::SeqCst)
}
trait AssertIsSync: Sync {}
impl<S: Serialization, C: Send + Sync> AssertIsSync for RpcDispatcher<S, C> {}
impl<S: Serialization, C: Send + Sync> RpcDispatcher<S, C> {
/// Enqueues an outbound call, returning the bytes that should be sent to make it run.
#[allow(dead_code)]
pub async fn call<M, A, R>(
&self,
method: M,
params: A,
) -> (Vec<u8>, oneshot::Receiver<Result<R, ResponseError>>)
where
M: Into<String>,
A: Serialize,
R: DeserializeOwned + Send + 'static,
{
let (tx, rx) = oneshot::channel();
let id = next_message_id();
let body = self.i.serializer.serialize(&FullRequest {
id: Some(id),
method: method.into(),
params,
});
let serializer = self.i.serializer.clone();
self.calls.lock().unwrap().insert(
id,
Box::new(move |body| {
match body {
Outcome::Error(e) => tx.send(Err(e)).ok(),
Outcome::Success(r) => match serializer.deserialize::<SuccessResponse<R>>(&r) {
Ok(r) => tx.send(Ok(r.result)).ok(),
Err(err) => tx
.send(Err(ResponseError {
code: 0,
message: err.to_string(),
}))
.ok(),
},
};
}),
);
(body, rx)
}
/// Runs the incoming request, returning the result of the call synchronously
/// or in a future. (The caller can then decide whether to run the future
/// sequentially in its receive loop, or not.)
///
/// The future or return result will be optional bytes that should be sent
/// back to the socket.
pub fn dispatch(&self, body: &[u8]) -> MaybeSync {
let partial = match self.i.serializer.deserialize::<PartialIncoming>(body) {
Ok(b) => b,
Err(_err) => return MaybeSync::Sync(None),
};
let id = partial.id;
if let Some(method_name) = partial.method {
let method = self.i.methods.get(method_name.as_str());
match method {
Some(Method::Sync(callback)) => MaybeSync::Sync(callback(id, body)),
Some(Method::Async(callback)) => MaybeSync::Future(callback(id, body)),
None => MaybeSync::Sync(id.map(|id| {
self.i.serializer.serialize(&ErrorResponse {
id,
error: ResponseError {
code: -1,
message: format!("Method not found: {}", method_name),
},
})
})),
}
} else if let Some(err) = partial.error {
if let Some(cb) = self.calls.lock().unwrap().remove(&id.unwrap()) {
cb(Outcome::Error(err));
}
MaybeSync::Sync(None)
} else if partial.result.is_some() {
if let Some(cb) = self.calls.lock().unwrap().remove(&id.unwrap()) {
cb(Outcome::Success(body.to_vec()));
}
MaybeSync::Sync(None)
} else {
MaybeSync::Sync(None)
}
}
pub fn context(&self) -> Arc<C> {
self.i.context.clone()
}
}
/// Approximate shape that is used to determine what kind of data is incoming.
#[derive(Deserialize)]
struct PartialIncoming {
pub id: Option<u32>,
pub method: Option<String>,
pub error: Option<ResponseError>,
pub result: Option<()>,
}
#[derive(Serialize)]
struct FullRequest<P> {
pub id: Option<u32>,
pub method: String,
pub params: P,
}
#[derive(Deserialize)]
struct RequestParams<P> {
pub params: P,
}
#[derive(Serialize, Deserialize)]
struct SuccessResponse<T> {
pub id: u32,
pub result: T,
}
#[derive(Serialize, Deserialize)]
struct ErrorResponse {
pub id: u32,
pub error: ResponseError,
}
#[derive(Serialize, Deserialize)]
pub struct ResponseError {
pub code: i32,
pub message: String,
}
enum Outcome {
Success(Vec<u8>),
Error(ResponseError),
}
pub enum MaybeSync {
Future(BoxFuture<'static, Option<Vec<u8>>>),
Sync(Option<Vec<u8>>),
}