forked from rsocket/rsocket-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.rs
282 lines (243 loc) · 8.4 KB
/
client.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
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use futures::{future, FutureExt, Sink, SinkExt, Stream, StreamExt};
use tokio::sync::{mpsc, Mutex, Notify};
use crate::error::{RSocketError, ERR_CONN_CLOSED};
use crate::frame::{self, Frame};
use crate::payload::{Payload, SetupPayload, SetupPayloadBuilder};
use crate::runtime;
use crate::spi::{ClientResponder, Flux, RSocket};
use crate::transport::{
self, Connection, DuplexSocket, FrameSink, FrameStream, ClientRequester, Splitter, Transport,
};
use crate::Result;
#[derive(Clone)]
pub struct Client {
closed: Arc<Notify>,
requester: ClientRequester,
closing: mpsc::Sender<()>,
}
pub struct ClientBuilder<T, C> {
transport: Option<T>,
setup: SetupPayloadBuilder,
responder: Option<ClientResponder>,
closer: Option<Box<dyn FnMut() + Send + Sync>>,
mtu: usize,
_c: PhantomData<C>,
}
impl<T, C> ClientBuilder<T, C>
where
T: Send + Sync + Transport<Conn = C>,
C: Send + Sync + Connection,
{
pub(crate) fn new() -> ClientBuilder<T, C> {
ClientBuilder {
transport: None,
responder: None,
setup: SetupPayload::builder(),
closer: None,
mtu: 0,
_c: PhantomData,
}
}
pub fn fragment(mut self, mtu: usize) -> Self {
if mtu > 0 && mtu < transport::MIN_MTU {
warn!("invalid fragment mtu: at least {}!", transport::MIN_MTU)
} else {
self.mtu = mtu;
}
self
}
pub fn transport(mut self, transport: T) -> Self {
self.transport = Some(transport);
self
}
pub fn setup(mut self, setup: Payload) -> Self {
let (d, m) = setup.split();
self.setup = self.setup.set_data_bytes(d);
self.setup = self.setup.set_metadata_bytes(m);
self
}
pub fn keepalive(
mut self,
tick_period: Duration,
ack_timeout: Duration,
missed_acks: u64,
) -> Self {
self.setup = self
.setup
.set_keepalive(tick_period, ack_timeout, missed_acks);
self
}
pub fn mime_type(
mut self,
metadata_mime_type: impl Into<String>,
data_mime_type: impl Into<String>,
) -> Self {
self = self.metadata_mime_type(metadata_mime_type);
self = self.data_mime_type(data_mime_type);
self
}
pub fn data_mime_type(mut self, mime_type: impl Into<String>) -> Self {
self.setup = self.setup.set_data_mime_type(mime_type);
self
}
pub fn metadata_mime_type(mut self, mime_type: impl Into<String>) -> Self {
self.setup = self.setup.set_metadata_mime_type(mime_type);
self
}
pub fn acceptor(mut self, acceptor: ClientResponder) -> Self {
self.responder = Some(acceptor);
self
}
pub fn on_close(mut self, callback: Box<dyn FnMut() + Sync + Send>) -> Self {
self.closer = Some(callback);
self
}
}
impl<T, C> ClientBuilder<T, C>
where
T: Send + Sync + Transport<Conn = C> + 'static,
C: Send + Sync + Connection + 'static,
{
pub async fn start(mut self) -> Result<Client> {
let tp: T = self.transport.take().expect("missint transport");
let splitter = if self.mtu == 0 {
None
} else {
Some(Splitter::new(self.mtu))
};
let (snd_tx, mut snd_rx) = mpsc::unbounded_channel::<Frame>();
let cloned_snd_tx = snd_tx.clone();
let mut socket = DuplexSocket::new(1, snd_tx, splitter);
let requester = socket.client_requester();
if let Some(f) = self.responder {
let responder = f();
socket.bind_responder(responder).await;
}
let conn = tp.connect().await?;
let (mut sink, mut stream) = conn.split();
let setup = self.setup.build();
// begin write loop
let tick_period = setup.keepalive_interval();
runtime::spawn(async move {
loop {
// send keepalive if timeout
match tokio::time::timeout(tick_period, snd_rx.recv()).await {
Ok(Some(frame)) => {
if let frame::Body::Error(e) = frame.get_body_ref() {
if e.get_code() == ERR_CONN_CLOSED {
break;
}
}
if let Err(e) = sink.send(frame).await {
error!("write frame failed: {}", e);
break;
}
}
Ok(None) => break,
Err(_) => {
// keepalive
let keepalive_frame =
frame::Keepalive::builder(0, Frame::FLAG_RESPOND).build();
if let Err(e) = sink.send(keepalive_frame).await {
error!("write frame failed: {}", e);
break;
}
}
}
}
});
// begin read loop
let closer = self.closer.take();
let close_notify = Arc::new(Notify::new());
let close_notify_clone = close_notify.clone();
let (closing, mut closing_rx) = mpsc::channel::<()>(1);
let (read_tx, mut read_rx) = mpsc::unbounded_channel::<Frame>();
// read frames from stream, then writes into channel
runtime::spawn(async move {
loop {
tokio::select! {
res = stream.next() => {
match res {
Some(next) => match next {
Ok(frame) => {
if let Err(e) = read_tx.send(frame) {
error!("forward frame failed: {}", e);
break;
}
}
Err(e) => {
error!("read frame failed: {}", e);
break;
}
}
None => break,
}
}
_ = closing_rx.recv() => {
break
}
}
}
});
socket.setup(setup).await?;
// process frames
runtime::spawn(async move {
while let Some(next) = read_rx.recv().await {
if let Err(e) = socket.dispatch(next, None).await {
error!("dispatch frame failed: {}", e);
break;
}
}
// workaround: send a notify frame that the connection has been closed.
let close_frame = frame::Error::builder(0, 0)
.set_code(ERR_CONN_CLOSED)
.build();
if let Err(e) = cloned_snd_tx.send(close_frame) {
debug!("send close notify frame failed: {}", e);
}
// notify client closed
close_notify_clone.notify_one();
// invoke on_close handler
if let Some(mut invoke) = closer {
invoke();
}
});
Ok(Client::new(requester, close_notify, closing))
}
}
impl Client {
fn new(requester: ClientRequester, closed: Arc<Notify>, closing: mpsc::Sender<()>) -> Client {
Client {
requester,
closed,
closing,
}
}
pub async fn wait_for_close(self) {
self.closed.notified().await
}
}
#[async_trait]
impl RSocket for Client {
async fn metadata_push(&self, req: Payload) -> Result<()> {
self.requester.metadata_push(req).await
}
async fn fire_and_forget(&self, req: Payload) -> Result<()> {
self.requester.fire_and_forget(req).await
}
async fn request_response(&self, req: Payload) -> Result<Option<Payload>> {
self.requester.request_response(req).await
}
fn request_stream(&self, req: Payload) -> Flux<Result<Payload>> {
self.requester.request_stream(req)
}
fn request_channel(&self, reqs: Flux<Result<Payload>>) -> Flux<Result<Payload>> {
self.requester.request_channel(reqs)
}
}