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
use crate::{App, NodeContext, Request, Response, ResponseBytes};
use anyhow::Result;
use async_std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use async_std::task;
use futures::channel::{mpsc, oneshot};
use futures::future::{AbortHandle, Abortable};
use futures::lock::Mutex;
use futures::prelude::*;
use potatonet_common::bus_message::Message;
use potatonet_common::{bus_message, LocalServiceId, RequestBytes};
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::sync::Arc;

#[derive(Default)]
pub struct Requests {
    pending: HashMap<u32, oneshot::Sender<std::result::Result<ResponseBytes, String>>>,
    seq: u32,
}

impl Requests {
    pub fn add(
        &mut self,
    ) -> (
        u32,
        oneshot::Receiver<std::result::Result<ResponseBytes, String>>,
    ) {
        let (tx, rx) = oneshot::channel();
        self.seq += 1;
        self.pending.insert(self.seq, tx);
        (self.seq, rx)
    }

    pub fn remove(&mut self, seq: u32) {
        self.pending.remove(&seq);
    }
}

pub struct LocalNotify {
    pub from: LocalServiceId,
    pub to: LocalServiceId,
    pub request: RequestBytes,
}

/// 节点构建器
pub struct NodeBuilder {
    bus_addr: Option<SocketAddr>,
    app: App,
    name: Option<String>,
}

impl NodeBuilder {
    pub fn new(app: App) -> Self {
        Self {
            bus_addr: None,
            app,
            name: None,
        }
    }

    /// 消息总线地址
    pub async fn bus_addr<A: ToSocketAddrs>(mut self, addr: A) -> Result<Self> {
        self.bus_addr = addr.to_socket_addrs().await?.next();
        Ok(self)
    }

    /// 节点名称
    pub fn name<N: Into<String>>(mut self, name: N) -> Self {
        self.name = Some(name.into());
        self
    }

    /// 运行节点
    pub async fn run(self) -> Result<()> {
        // 连接到消息总线
        let stream = TcpStream::connect(
            self.bus_addr
                .unwrap_or_else(|| "127.0.0.1:39901".parse().unwrap()),
        )
        .await?;

        // 发送hello消息,并等待服务响应
        let name = self
            .name
            .unwrap_or_else(|| names::Generator::default().next().unwrap());
        bus_message::write_message(&stream, &bus_message::Message::RegisterNode(name.clone()))
            .await?;
        let node_id = match bus_message::read_message(&stream).await {
            Ok(bus_message::Message::NodeRegistered(node_id)) => node_id,
            res => {
                println!("{:?}", res);
                bail!("unable connect to bus")
            }
        };
        info!("bus connected. node_id={}", node_id);

        // 创建接收和发送消息任务
        let (abort_handle, abort_registration) = AbortHandle::new_pair();
        let (mut tx, mut rx) = mpsc::channel(16);
        let stream = Arc::new(stream);

        // 发送任务
        let send_handle = task::spawn({
            let stream = stream.clone();
            async move {
                while let Some(msg) = rx.next().await {
                    if let Err(_) = bus_message::write_message(&*stream, &msg).await {
                        return;
                    }
                }
            }
        });

        let app = Arc::new(self.app);
        let requests = Arc::new(Mutex::new(Requests::default()));

        // 处理本地通知消息
        // 同一个节点的服务发送给另一个服务的通知发送到该队列,避免循环通知出现的栈溢出问题
        let (tx_local_notify, rx_local_notify) = mpsc::unbounded::<LocalNotify>();
        let local_notify_fut = {
            let app = app.clone();
            let requests = requests.clone();
            let tx = tx.clone();
            let abort_handle = abort_handle.clone();
            let tx_local_notify = tx_local_notify.clone();
            async move {
                rx_local_notify
                    .for_each_concurrent(4, |notify| {
                        async {
                            if let Some((service_name, init, service)) =
                                app.services.get(notify.to.to_u32() as usize)
                            {
                                if init.load(Ordering::Relaxed) {
                                    service
                                        .notify(
                                            &NodeContext {
                                                from: Some(notify.from.to_global(node_id)),
                                                service_name,
                                                node_id,
                                                local_service_id: notify.to,
                                                app: &app,
                                                tx: tx.clone(),
                                                tx_local_notify: tx_local_notify.clone(),
                                                requests: requests.clone(),
                                                abort_handle: abort_handle.clone(),
                                            },
                                            notify.request,
                                        )
                                        .await;
                                }
                            }
                        }
                    })
                    .await;
            }
        };
        let (abort_ln_handle, abort_ln_registration) = AbortHandle::new_pair();
        let local_notify_handle =
            task::spawn(Abortable::new(local_notify_fut, abort_ln_registration));

        // 处理消息
        let recv_handle = task::spawn({
            let app = app.clone();
            let requests = requests.clone();
            let tx = tx.clone();
            let tx_local_notify = tx_local_notify.clone();
            let abort_handle = abort_handle.clone();
            Abortable::new(
                async move {
                    while let Ok(msg) = bus_message::read_message(&*stream).await {
                        match msg {
                            bus_message::Message::XReq {
                                from,
                                to,
                                seq,
                                method,
                                data,
                            } => {
                                task::spawn({
                                    let app = app.clone();
                                    let abort_handle = abort_handle.clone();
                                    let mut tx = tx.clone();
                                    let tx_local_notify = tx_local_notify.clone();
                                    let requests = requests.clone();

                                    async move {
                                        if let Some((service_name, init, service)) =
                                            app.services.get(to.to_u32() as usize)
                                        {
                                            if init.load(Ordering::Relaxed) {
                                                let res = service
                                                    .call(
                                                        &NodeContext {
                                                            from,
                                                            service_name,
                                                            node_id,
                                                            local_service_id: to,
                                                            app: &app,
                                                            tx: tx.clone(),
                                                            tx_local_notify: tx_local_notify
                                                                .clone(),
                                                            requests,
                                                            abort_handle,
                                                        },
                                                        Request::new(method, data),
                                                    )
                                                    .await;
                                                tx.send(bus_message::Message::Rep {
                                                    seq,
                                                    result: res
                                                        .map(|resp| resp.data)
                                                        .map_err(|err| err.to_string()),
                                                })
                                                .await
                                                .ok();
                                            } else {
                                                tx.send(bus_message::Message::Rep {
                                                    seq,
                                                    result: Err(
                                                        "service not initialized".to_string()
                                                    ),
                                                })
                                                .await
                                                .ok();
                                            }
                                        } else {
                                            tx.send(bus_message::Message::Rep {
                                                seq,
                                                result: Err("service not found".to_string()),
                                            })
                                            .await
                                            .ok();
                                        }
                                    }
                                });
                            }
                            bus_message::Message::Rep { seq, result } => {
                                if let Some(tx) = requests.lock().await.pending.remove(&seq) {
                                    tx.send(result.map(|data| Response::new(data))).ok();
                                }
                            }
                            bus_message::Message::Notify {
                                from,
                                to_service,
                                method,
                                data,
                            } => {
                                task::spawn({
                                    let app = app.clone();
                                    let abort_handle = abort_handle.clone();
                                    let tx = tx.clone();
                                    let tx_local_notify = tx_local_notify.clone();
                                    let requests = requests.clone();

                                    async move {
                                        if let Some(lid) = app.services_map.get(&to_service) {
                                            if let Some((service_name, init, service)) =
                                                app.services.get(lid.to_u32() as usize)
                                            {
                                                if init.load(Ordering::Relaxed) {
                                                    service
                                                        .notify(
                                                            &NodeContext {
                                                                from,
                                                                service_name,
                                                                node_id,
                                                                local_service_id: *lid,
                                                                app: &app,
                                                                tx: tx.clone(),
                                                                tx_local_notify: tx_local_notify
                                                                    .clone(),
                                                                requests,
                                                                abort_handle,
                                                            },
                                                            Request::new(method, data),
                                                        )
                                                        .await;
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                            bus_message::Message::Event { event } => {
                                task::spawn({
                                    let app = app.clone();
                                    let abort_handle = abort_handle.clone();
                                    let tx = tx.clone();
                                    let tx_local_notify = tx_local_notify.clone();
                                    let requests = requests.clone();

                                    async move {
                                        for (idx, (service_name, init, service)) in
                                            app.services.iter().enumerate()
                                        {
                                            if init.load(Ordering::Relaxed) {
                                                service
                                                        .event(
                                                            &NodeContext {
                                                                from: None,
                                                                service_name,
                                                                node_id,
                                                                local_service_id: LocalServiceId::from_u32(
                                                                    idx as u32,
                                                                ),
                                                                app: &app,
                                                                tx: tx.clone(),
                                                                tx_local_notify: tx_local_notify.clone(),
                                                                requests: requests.clone(),
                                                                abort_handle: abort_handle.clone(),
                                                            },
                                                            &event,
                                                        )
                                                        .await;
                                            }
                                        }
                                    }
                                });
                            }
                            _ => {}
                        }
                    }
                },
                abort_registration,
            )
        });

        // 开始所有服务
        for (idx, (service_name, init, service)) in app.services.iter().enumerate() {
            info!("start service. name={}", service_name);
            let lid = LocalServiceId::from_u32(idx as u32);
            service
                .start(&NodeContext {
                    from: None,
                    service_name,
                    node_id,
                    local_service_id: lid,
                    app: &app,
                    tx: tx.clone(),
                    tx_local_notify: tx_local_notify.clone(),
                    requests: requests.clone(),
                    abort_handle: abort_handle.clone(),
                })
                .await;
            init.store(true, Ordering::Relaxed);

            // 注册服务
            tx.send(bus_message::Message::RegisterService {
                name: service_name.clone(),
                id: lid,
            })
            .await
            .ok();
        }

        recv_handle.await.ok();
        tx.send(Message::UnregisterNode).await.ok();
        drop(tx);
        drop(tx_local_notify);
        abort_ln_handle.abort();
        local_notify_handle.await.ok();
        send_handle.await;
        Ok(())
    }
}