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
//! # 链路驱动层
//!
//! 链路驱动层(link)规定了链路实例(Link)

#![no_std]
#![feature(const_btree_new)]

extern crate alloc;
pub mod consts;

use alloc::sync::{Arc, Weak};
use core::fmt;
use core::sync::atomic::{AtomicUsize, Ordering};
use futures_intrusive::channel::shared::*;
use spin::Once;
use spin::{Mutex, RwLock};
cfg_if::cfg_if! {
    if #[cfg(feature = "role_center")] {
        use alloc::collections::BTreeMap;
    } else{
        use crate::consts::LINKS_LEN;
        use fixed_queue::LinearMap;
        type BTreeMap<K, V> = LinearMap<K, V, LINKS_LEN>;
    }
}

type DestroyCallback = fn(link: &Link);
static LINKS: RwLock<BTreeMap<Link, ()>> = RwLock::new(BTreeMap::new());
static UID_SN: AtomicUsize = AtomicUsize::new(1);
static DESTROY_CB: Once<DestroyCallback> = Once::new();

/// 错误类型
#[derive(Debug)]
pub enum ErrorKind {
    /// 链路不存在
    NotFound,
    /// 链路已断开
    NotConnected,
    /// 发送超时
    TimedOut,
    /// 未知错误
    Unknown,
}
/// 发送Future
pub type ResultSender = GenericOneshotSender<Mutex<()>, Result<(), ErrorKind>>;
pub struct ResultFuture {
    recver: GenericOneshotReceiver<Mutex<()>, Result<(), ErrorKind>>,
}
impl ResultFuture {
    pub fn new() -> (ResultFuture, ResultSender) {
        let (sender, recver) = generic_oneshot_channel();
        let result_future = ResultFuture { recver };
        (result_future, sender)
    }
    pub async fn get_result(self) -> Result<(), ErrorKind> {
        self.recver.receive().await.unwrap()
    }
}

/// 链路驱动接口
pub trait Driver {
    /// 获取自定义标识
    fn name(&self) -> &str;
    /// 数据发送接口
    fn send(self: Arc<Self>, buf: &[u8]) -> ResultFuture;
}

/// 链路实例描述符(Link)
#[derive(Clone)]
pub struct Link {
    /// 链路唯一ID
    uid: usize,
    /// 驱动
    pub driver: Weak<dyn Driver + Send + Sync>,
}
impl PartialEq for Link {
    fn eq(&self, other: &Self) -> bool {
        self.uid == other.uid
    }
}
impl Eq for Link {}
impl PartialOrd for Link {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.uid.cmp(&other.uid))
    }
}
impl Ord for Link {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.uid.cmp(&other.uid)
    }
}
impl fmt::Display for Link {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "link{}", self.uid)
    }
}
impl fmt::Debug for Link {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(driver) = self.driver.upgrade() {
            write!(f, "link{}({})", self.uid, driver.name())
        } else {
            write!(f, "link{}({})", self.uid, "invalid")
        }
    }
}
impl Link {
    /// 通过链路驱动接口(Driver)创建链路实例
    pub fn new(driver: Weak<dyn Driver + Send + Sync>) -> Self {
        let link = Link {
            uid: UID_SN.fetch_add(1, Ordering::Relaxed),
            driver: driver,
        };
        LINKS.write().insert(link.clone(), ());
        link
    }
    /// 销毁链路
    pub fn destroy(&self) {
        LINKS.write().remove(self);
        if let Some(cb) = DESTROY_CB.get() {
            cb(self);
        }
    }
    /// 链路是否有效
    pub fn status(&self) -> Result<(), ErrorKind> {
        if let Some(_) = self.driver.upgrade() {
            return Ok(());
        } else {
            return Err(ErrorKind::NotFound);
        }
    }
    /// 调用链路实例发送负载数据
    pub async fn send(&self, buf: &[u8]) -> Result<(), ErrorKind> {
        if let Some(driver) = self.driver.upgrade() {
            return driver.send(&buf).get_result().await;
        } else {
            return Err(ErrorKind::NotFound);
        }
    }
}

/// 注册链路断开时回调
pub fn on_destroy(cb: DestroyCallback) {
    DESTROY_CB.call_once(|| cb);
}

/// 广播负载数据到链路池中所有链路
pub async fn broadcast(buf: &[u8]) -> Result<(), ()> {
    let mut success: usize = 0;
    for (link, _) in LINKS.read().iter() {
        if let Some(driver) = link.driver.upgrade() {
            if let Ok(_) = driver.send(&buf).get_result().await {
                success += 1;
            }
        } else {
            link.destroy();
        }
    }
    if success == 0 {
        return Err(());
    } else {
        return Ok(());
    }
}