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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
use crate::{
message::{BidiStreaming, ClientStreaming, Msg, Rpc, ServerStreaming},
ChannelTypes, LocalAddr, ServerChannel, Service,
};
use futures::{channel::oneshot, task, task::Poll, Future, FutureExt, SinkExt, Stream, StreamExt};
use pin_project::pin_project;
use std::{error, fmt, fmt::Debug, marker::PhantomData, pin::Pin, result};
#[derive(Debug)]
pub struct RpcServer<S: Service, C: ChannelTypes> {
channel: C::ServerChannel<S::Req, S::Res>,
}
impl<S: Service, C: ChannelTypes> Clone for RpcServer<S, C> {
fn clone(&self) -> Self {
Self {
channel: self.channel.clone(),
}
}
}
impl<S: Service, C: ChannelTypes> RpcServer<S, C> {
pub fn new(channel: C::ServerChannel<S::Req, S::Res>) -> Self {
Self { channel }
}
pub fn local_addr(&self) -> &[LocalAddr] {
self.channel.local_addr()
}
}
impl<S: Service, C: ChannelTypes> RpcServer<S, C> {
pub async fn accept_one(
&self,
) -> result::Result<(S::Req, (C::SendSink<S::Res>, C::RecvStream<S::Req>)), RpcServerError<C>>
where
C::RecvStream<S::Req>: Unpin,
{
let mut channel = self
.channel
.accept_bi()
.await
.map_err(RpcServerError::AcceptBiError)?;
let request: S::Req = channel
.1
.next()
.await
.ok_or(RpcServerError::EarlyClose)?
.map_err(RpcServerError::RecvError)?;
Ok((request, channel))
}
pub async fn rpc_map_err<M, F, Fut, T, R, E1, E2>(
&self,
req: M,
chan: (C::SendSink<S::Res>, C::RecvStream<S::Req>),
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: Msg<S, Pattern = Rpc, Response = result::Result<R, E2>>,
F: FnOnce(T, M) -> Fut,
Fut: Future<Output = result::Result<R, E1>>,
E2: From<E1>,
T: Send + 'static,
{
let fut = |target: T, msg: M| async move {
let res: Result<R, E1> = f(target, msg).await;
let res: Result<R, E2> = res.map_err(E2::from);
res
};
self.rpc(req, chan, target, fut).await
}
pub async fn rpc<M, F, Fut, T>(
&self,
req: M,
chan: (C::SendSink<S::Res>, C::RecvStream<S::Req>),
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: Msg<S, Pattern = Rpc>,
F: FnOnce(T, M) -> Fut,
Fut: Future<Output = M::Response>,
T: Send + 'static,
{
let (mut send, mut recv) = chan;
let cancel = recv
.next()
.map(|_| RpcServerError::UnexpectedUpdateMessage::<C>);
race2(cancel.map(Err), async move {
let res = f(target, req).await;
let res: S::Res = res.into();
send.send(res).await.map_err(RpcServerError::SendError)
})
.await
}
pub async fn client_streaming<M, F, Fut, T>(
&self,
req: M,
c: (C::SendSink<S::Res>, C::RecvStream<S::Req>),
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: Msg<S, Pattern = ClientStreaming>,
F: FnOnce(T, M, UpdateStream<S, C, M>) -> Fut + Send + 'static,
Fut: Future<Output = M::Response> + Send + 'static,
T: Send + 'static,
{
let (mut send, recv) = c;
let (updates, read_error) = UpdateStream::new(recv);
race2(read_error.map(Err), async move {
let res = f(target, req, updates).await;
let res: S::Res = res.into();
send.send(res).await.map_err(RpcServerError::SendError)
})
.await
}
pub async fn bidi_streaming<M, F, Str, T>(
&self,
req: M,
c: (C::SendSink<S::Res>, C::RecvStream<S::Req>),
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: Msg<S, Pattern = BidiStreaming>,
F: FnOnce(T, M, UpdateStream<S, C, M>) -> Str + Send + 'static,
Str: Stream<Item = M::Response> + Send + 'static,
T: Send + 'static,
{
let (mut send, recv) = c;
let (updates, read_error) = UpdateStream::new(recv);
let responses = f(target, req, updates);
race2(read_error.map(Err), async move {
tokio::pin!(responses);
while let Some(response) = responses.next().await {
let response: S::Res = response.into();
send.send(response)
.await
.map_err(RpcServerError::SendError)?;
}
Ok(())
})
.await
}
pub async fn server_streaming<M, F, Str, T>(
&self,
req: M,
c: (C::SendSink<S::Res>, C::RecvStream<S::Req>),
target: T,
f: F,
) -> result::Result<(), RpcServerError<C>>
where
M: Msg<S, Pattern = ServerStreaming>,
F: FnOnce(T, M) -> Str + Send + 'static,
Str: Stream<Item = M::Response> + Send + 'static,
T: Send + 'static,
{
let (mut send, mut recv) = c;
let cancel = recv
.next()
.map(|_| RpcServerError::UnexpectedUpdateMessage::<C>);
race2(cancel.map(Err), async move {
let responses = f(target, req);
tokio::pin!(responses);
while let Some(response) = responses.next().await {
let response: S::Res = response.into();
send.send(response)
.await
.map_err(RpcServerError::SendError)?;
}
Ok(())
})
.await
}
}
#[pin_project]
pub struct UpdateStream<S: Service, C: ChannelTypes, M: Msg<S>>(
#[pin] C::RecvStream<S::Req>,
Option<oneshot::Sender<RpcServerError<C>>>,
PhantomData<M>,
);
impl<S: Service, C: ChannelTypes, M: Msg<S>> UpdateStream<S, C, M> {
fn new(recv: C::RecvStream<S::Req>) -> (Self, UnwrapToPending<RpcServerError<C>>) {
let (error_send, error_recv) = oneshot::channel();
let error_recv = UnwrapToPending(error_recv);
(Self(recv, Some(error_send), PhantomData), error_recv)
}
}
impl<S: Service, C: ChannelTypes, M: Msg<S>> Stream for UpdateStream<S, C, M> {
type Item = M::Update;
fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
match this.0.poll_next_unpin(cx) {
Poll::Ready(Some(msg)) => match msg {
Ok(msg) => match M::Update::try_from(msg) {
Ok(msg) => Poll::Ready(Some(msg)),
Err(_cause) => {
if let Some(tx) = this.1.take() {
let _ = tx.send(RpcServerError::UnexpectedUpdateMessage);
}
Poll::Pending
}
},
Err(cause) => {
if let Some(tx) = this.1.take() {
let _ = tx.send(RpcServerError::RecvError(cause));
}
Poll::Pending
}
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
pub enum RpcServerError<C: ChannelTypes> {
AcceptBiError(C::AcceptBiError),
EarlyClose,
UnexpectedStartMessage,
RecvError(C::RecvError),
SendError(C::SendError),
UnexpectedUpdateMessage,
}
impl<C: ChannelTypes> fmt::Debug for RpcServerError<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::AcceptBiError(arg0) => f.debug_tuple("AcceptBiError").field(arg0).finish(),
Self::EarlyClose => write!(f, "EarlyClose"),
Self::RecvError(arg0) => f.debug_tuple("RecvError").field(arg0).finish(),
Self::SendError(arg0) => f.debug_tuple("SendError").field(arg0).finish(),
Self::UnexpectedStartMessage => f.debug_tuple("UnexpectedStartMessage").finish(),
Self::UnexpectedUpdateMessage => f.debug_tuple("UnexpectedStartMessage").finish(),
}
}
}
impl<C: ChannelTypes> fmt::Display for RpcServerError<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl<C: ChannelTypes> error::Error for RpcServerError<C> {}
struct UnwrapToPending<T>(oneshot::Receiver<T>);
impl<T> Future for UnwrapToPending<T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
match self.0.poll_unpin(cx) {
Poll::Ready(Ok(x)) => Poll::Ready(x),
Poll::Ready(Err(_)) => Poll::Pending,
Poll::Pending => Poll::Pending,
}
}
}
async fn race2<T, A: Future<Output = T>, B: Future<Output = T>>(f1: A, f2: B) -> T {
tokio::select! {
x = f1 => x,
x = f2 => x,
}
}
pub async fn run_server_loop<S, C, T, F, Fut>(
_service_type: S,
_channel_type: C,
conn: C::ServerChannel<S::Req, S::Res>,
target: T,
mut handler: F,
) -> Result<(), RpcServerError<C>>
where
S: Service,
C: ChannelTypes,
T: Clone + Send + 'static,
F: FnMut(RpcServer<S, C>, S::Req, (C::SendSink<S::Res>, C::RecvStream<S::Req>), T) -> Fut
+ Send
+ 'static,
Fut: Future<Output = Result<RpcServer<S, C>, RpcServerError<C>>> + Send + 'static,
{
let mut server = RpcServer::<S, C>::new(conn);
loop {
let (req, chan) = server.accept_one().await?;
let target = target.clone();
server = handler(server, req, chan, target).await?;
}
}