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
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate log;

use async_std::net::{TcpStream, ToSocketAddrs};
use async_std::stream;
use async_std::task;
use futures::channel::{mpsc, oneshot};
use futures::lock::Mutex;
use futures::prelude::*;
use futures::select;
use futures::{SinkExt, StreamExt};
use potatonet_common::bus_message::Message;
use potatonet_common::{
    bus_message, Context, Error, LocalServiceId, NodeId, Request, Response, ResponseBytes, Result,
    ServiceId, Topic,
};
use serde::de::DeserializeOwned;
use serde::export::PhantomData;
use serde::Serialize;
use slab::Slab;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

#[async_trait::async_trait]
trait SubCallback: Send {
    async fn notify(&mut self, data: &[u8]);
}

struct SubCallbackAdapter<
    T: Topic,
    F: FnMut(T) -> R + Send + 'static,
    R: Future<Output = ()> + Send + 'static,
> {
    _market: PhantomData<T>,
    f: F,
}

#[async_trait::async_trait]
impl<T, F, R> SubCallback for SubCallbackAdapter<T, F, R>
where
    T: Topic,
    F: FnMut(T) -> R + Send + 'static,
    R: Future<Output = ()> + Send + 'static,
{
    async fn notify(&mut self, data: &[u8]) {
        if let Ok(msg) = T::decode(&data) {
            (self.f)(msg).await;
        }
    }
}

/// 订阅id
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
pub struct SubscribeId(usize);

#[derive(Default)]
struct Inner {
    pending: HashMap<u32, oneshot::Sender<std::result::Result<ResponseBytes, String>>>,
    seq: u32,
    subscribes_set: HashMap<String, usize>,
    subscribes: Slab<(String, Box<dyn SubCallback>)>,
}

/// 客户端
pub struct Client {
    node_id: NodeId,
    tx: mpsc::Sender<bus_message::Message>,
    tx_abort: mpsc::Sender<()>,
    inner: Arc<Mutex<Inner>>,
}

impl Drop for Client {
    fn drop(&mut self) {
        self.tx_abort.try_send(()).ok();
        info!("client closed");
    }
}

impl Client {
    async fn process_incoming_msg(inner: Arc<Mutex<Inner>>, msg: &bus_message::Message) {
        match msg {
            bus_message::Message::Rep { seq, result } => {
                let mut inner = inner.lock().await;
                if let Some(tx) = inner.pending.remove(&seq) {
                    tx.send(result.clone().map(|data| Response::new(data))).ok();
                }
            }
            bus_message::Message::XPublish { topic, data } => {
                let mut inner = inner.lock().await;
                for (_, (sub_topic, f)) in &mut inner.subscribes {
                    if topic == sub_topic.as_str() {
                        f.notify(&data).await;
                    }
                }
            }
            _ => {}
        }
    }

    #[doc(hidden)]
    pub async fn connect_with_notify<A, F, R>(addr: A, mut handle_msg: F) -> Result<Client>
    where
        A: ToSocketAddrs,
        F: FnMut(bus_message::Message) -> R + Send + Sync + 'static,
        R: Future<Output = ()> + Send + 'static,
    {
        let addr = addr.to_socket_addrs().await?.next();
        let stream = match addr {
            Some(addr) => {
                info!("connect to bus. addr={}", addr);
                Arc::new(TcpStream::connect(addr).await?)
            }
            None => bail!("could not resolve to any addresses"),
        };

        // 等待hello消息
        let node_id = match potatonet_common::bus_message::read_one_message(&*stream).await {
            Ok(bus_message::Message::Hello(node_id)) => node_id,
            Ok(msg) => {
                println!("{:?}", msg);
                bail!("invalid response")
            }
            Err(err) => return Err(err),
        };

        let inner: Arc<Mutex<Inner>> = Default::default();

        // 消息发送
        let (tx_incoming_msg, mut rx_incoming_msg) = mpsc::channel(16);
        let (tx_outgoing_msg, rx_outgoing_msg) = mpsc::channel(16);

        let (reader_task, abort_reader) =
            future::abortable(bus_message::read_messages(stream.clone(), tx_incoming_msg));
        let reader_handle = task::spawn(reader_task);

        let (writer_task, abort_writer) =
            future::abortable(bus_message::write_messages(stream.clone(), rx_outgoing_msg));
        let writer_handle = task::spawn(writer_task);

        let (tx_abort, mut rx_abort) = mpsc::channel::<()>(1);

        let fut = {
            let inner = inner.clone();
            let mut tx_outgoing_msg = tx_outgoing_msg.clone();
            async move {
                // 心跳发送定时器
                let mut hb_timer = stream::interval(Duration::from_secs(1)).fuse();

                loop {
                    select! {
                        _ = rx_abort.next() => {
                            // 退出
                            break;
                        }
                        _ = hb_timer.next() => {
                            // 发送心跳
                            if let Err(_) = tx_outgoing_msg.send(bus_message::Message::Ping).await {
                                // 连接已断开
                                break;
                            }
                        }
                        msg = rx_incoming_msg.next() => {
                            if let Some(msg) = msg {
                                Self::process_incoming_msg(inner.clone(), &msg).await;
                                handle_msg(msg).await;
                            } else {
                                // 连接已断开
                                break;
                            }
                        }
                    }
                }

                tx_outgoing_msg.send(bus_message::Message::Bye).await.ok();

                abort_reader.abort();
                abort_writer.abort();
                reader_handle.await.ok();
                writer_handle.await.ok();

                info!("client closed");
            }
        };
        task::spawn(fut);

        Ok(Client {
            node_id,
            tx: tx_outgoing_msg,
            tx_abort,
            inner,
        })
    }

    /// 连接到消息总线
    pub async fn connect<A: ToSocketAddrs>(addr: A) -> Result<Client> {
        Self::connect_with_notify(addr, |_| async move {}).await
    }

    /// 获取当前节点id
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// 注册服务
    pub async fn register_service<N: Into<String>>(&self, name: N, id: LocalServiceId) {
        self.tx
            .clone()
            .send(bus_message::Message::RegisterService {
                name: name.into(),
                id,
            })
            .await
            .ok();
    }

    /// 注销服务
    pub async fn unregister_service(&self, id: LocalServiceId) {
        self.tx
            .clone()
            .send(bus_message::Message::UnregisterService { id })
            .await
            .ok();
    }

    #[doc(hidden)]
    pub async fn send_msg(&self, msg: Message) {
        self.tx.clone().send(msg).await.ok();
    }

    /// 订阅消息
    /// 如果重复订阅,则会按订阅顺序依次触发回调函数,并不会增加数据传输流量
    pub async fn subscribe<T, F, R>(&self, handler: F) -> SubscribeId
    where
        T: Topic,
        F: FnMut(T) -> R + Send + 'static,
        R: Future<Output = ()> + Send + 'static,
    {
        self.subscribe_with_topic(T::name(), handler).await
    }

    /// 订阅指定主题的消息
    pub async fn subscribe_with_topic<T, F, R>(&self, topic: &str, handler: F) -> SubscribeId
    where
        T: Topic,
        F: FnMut(T) -> R + Send + 'static,
        R: Future<Output = ()> + Send + 'static,
    {
        let mut inner = self.inner.lock().await;
        let id = inner.subscribes.insert((
            topic.to_string(),
            Box::new(SubCallbackAdapter {
                _market: PhantomData,
                f: handler,
            }),
        ));
        if let Some(count) = inner.subscribes_set.get_mut(topic) {
            *count += 1;
        } else {
            // 第一次订阅
            inner.subscribes_set.insert(topic.to_string(), 1);
            self.send_msg(bus_message::Message::Subscribe {
                topic: topic.to_string(),
            })
            .await;
        }
        SubscribeId(id)
    }

    /// 取消订阅消息
    pub async fn unsubscribe(&self, id: SubscribeId) {
        let mut inner = self.inner.lock().await;
        if inner.subscribes.contains(id.0 as usize) {
            let (topic, _) = inner.subscribes.remove(id.0 as usize);
            self.send_msg(bus_message::Message::Unsubscribe {
                topic: topic.to_string(),
            })
            .await;
            if let Some(count) = inner.subscribes_set.get_mut(&topic) {
                *count -= 1;
                if *count == 0 {
                    inner.subscribes_set.remove(&topic);
                }
            }
        }
    }
}

#[async_trait::async_trait]
impl Context for Client {
    async fn call<T, R>(&self, service_name: &str, request: Request<T>) -> Result<Response<R>>
    where
        T: Serialize + Send + 'static,
        R: DeserializeOwned + Send + 'static,
    {
        let (seq, rx) = {
            let mut inner = self.inner.lock().await;
            let (tx, rx) = oneshot::channel();

            inner.seq += 1;
            let seq = inner.seq;
            inner.pending.insert(seq, tx);
            (seq, rx)
        };

        let request = request.to_bytes();
        self.tx
            .clone()
            .send(bus_message::Message::Req {
                seq,
                from: LocalServiceId(0),
                to_service: service_name.to_string(),
                method: request.method,
                data: request.data,
            })
            .await
            .ok();

        match async_std::future::timeout(Duration::from_secs(5), rx).await {
            Ok(Ok(Ok(resp))) => Ok(Response::<R>::from_bytes(resp)),
            Ok(Ok(Err(err))) => Err(anyhow!(err)),
            Ok(Err(_)) => {
                let mut inner = self.inner.lock().await;
                inner.pending.remove(&seq);
                Err(Error::Internal.into())
            }
            Err(_) => {
                let mut inner = self.inner.lock().await;
                inner.pending.remove(&seq);
                Err(Error::Timeout.into())
            }
        }
    }

    async fn notify<T: Serialize + Send + 'static>(&self, service_name: &str, request: Request<T>) {
        let request = request.to_bytes();
        self.tx
            .clone()
            .send(bus_message::Message::Notify {
                from: LocalServiceId(0),
                to_service: service_name.to_string(),
                method: request.method,
                data: request.data,
            })
            .await
            .ok();
    }

    async fn notify_to<T: Serialize + Send + 'static>(&self, to: ServiceId, request: Request<T>) {
        let request = request.to_bytes();
        self.tx
            .clone()
            .send(bus_message::Message::NotifyTo {
                from: LocalServiceId(0),
                to,
                method: request.method,
                data: request.data,
            })
            .await
            .ok();
    }

    async fn publish_with_topic<T: Topic>(&self, topic: &str, msg: T) {
        if let Ok(data) = msg.encode() {
            self.tx
                .clone()
                .send(bus_message::Message::Publish {
                    topic: topic.to_string(),
                    data: data.into(),
                })
                .await
                .ok();
        }
    }
}