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
#![allow(dead_code)]
use crate::error::Error;
use crate::inter::EventHandle;
use async_recursion::async_recursion;
use std::any::Any;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use tokio::time::Duration;

const MSGDEFAULT: &'static str = "wd-event-default-error";

#[derive(Clone)]
pub struct Context {
    max_cycle: u32,
    //true 异步执行,不再关心返回结果,false:同步执行
    is_async: Arc<AtomicBool>,
    //事件执行计数,如果超过最大值则报错,避免进入无限循环
    count: Arc<AtomicU32>,
    //向事件系统交互,是否停止后续事件
    status: Arc<AtomicBool>,
    delay: std::time::Duration,
    messages: Arc<RwLock<HashMap<String, Arc<dyn Any + Send + Sync>>>>,
    pub(crate) middle: Arc<Mutex<Vec<Arc<dyn EventHandle + Send + Sync>>>>,
    pub(crate) list: Arc<Mutex<Vec<Arc<dyn EventHandle + Send + Sync>>>>,
}
unsafe impl Send for Context {}
unsafe impl Sync for Context {}

impl Context {
    pub fn new() -> Self {
        Context {
            max_cycle: 0,
            is_async: Arc::new(AtomicBool::new(false)),
            count: Arc::new(AtomicU32::new(0)),
            status: Arc::new(AtomicBool::new(true)),
            delay: std::time::Duration::from_millis(0),
            messages: Arc::new(RwLock::new(HashMap::new())),
            middle: Arc::new(Mutex::new(vec![])),
            list: Arc::new(Mutex::new(vec![])),
        }
    }
    pub fn try_share(self) ->Self{
        if self.load_count() == 0 {
            return self
        }
        let mut ctx = Self::new();
        ctx.max_cycle = self.max_cycle;
        ctx.is_async = self.is_async.clone();
        ctx.count = Arc::new(AtomicU32::new(0));
        ctx.status = self.status.clone();
        ctx.delay  = self.delay.clone();
        ctx.messages = self.messages.clone();
        return ctx
    }
    // pub async fn new_msg<V:Any>(msg:V)->Self{
    //     let ctx = Self::new();
    //     ctx.set(MSGDEFAULT,msg).await;
    //     return ctx
    // }
    pub fn set_timeout(mut self, t: std::time::Duration) -> Self {
        self.delay = t;
        self
    }
    // pub async fn get_msg<T: Any>(&self)->Option<Arc<T>>{
    //     self.get(&MSGDEFAULT).await
    // }
    pub fn timeout(&self) -> Duration {
        self.delay.clone()
    }
    pub async fn set<K: ToString, V: Any + Send + Sync>(&self, key: K, value: V) {
        let arc_value = Arc::new(value);
        let mut res = self.messages.write().await;
        let msgs = res.deref_mut();
        let key = key.to_string();
        msgs.insert(key, Arc::new(arc_value));
    }

    /// 获取指定类型的数据,该类型需要实现Clone
    ///
    /// ```rust
    /// let value:&str = match ctx.get_value("haha"){
    ///     Some(s)=>{s}
    ///     None=>{"haha"}
    /// };
    ///```
    pub async fn copy<K: ToString, T: Clone + Any>(&self, key: K) -> Option<T> {
        if let Some(s) = self.get::<_, T>(key).await {
            let c = (s.deref()).clone();
            return Some(c);
        }
        return None;
    }
    pub async fn get<K: ToString, T: Any>(&self, key: K) -> Option<Arc<T>> {
        if let Some(s) = self.get_raw(&key.to_string()).await {
            let ss = s.clone();
            if let Some(a) = ss.downcast_ref::<Arc<T>>() {
                return Some(a.clone());
            };
        }
        return None;
    }
    pub fn abort(&self) {
        self.set_status(false);
    }
    pub async fn error(&self) -> Option<Error> {
        self.copy::<_, Error>(MSGDEFAULT).await
    }

    #[async_recursion]
    pub async fn next(self) -> Context {
        let mut ctx = self;
        if !ctx.get_status() {
            ctx.set_error(Error::Abort).await;
            return ctx;
        }
        if ctx.add_count(1) > ctx.get_max_cycle() {
            ctx.set_error(Error::CycleTransfinite).await;
            return ctx;
        }
        let call = ctx.pop_middle_event().await;
        if let Some(s) = call {
            ctx = s.handle(ctx).await;
        } else {
            let opt_ctx = ctx.pop_list_event().await;
            if let Some(s) = opt_ctx {
                ctx = s.handle(ctx).await;
                ctx = ctx.next().await;
            }
        }
        return ctx;
    }
    pub(crate) async fn get_raw<K: ToString>(&self, key: &K) -> Option<Arc<dyn Any>> {
        let res = self.messages.read().await;
        let msgs = res.deref();
        let key = key.to_string();
        match msgs.get(&key) {
            Some(s) => return Some(s.clone()),
            None => None,
        }
    }

    pub(crate) async fn set_error(&self, err: Error) {
        self.set(MSGDEFAULT, err).await;
    }
    /// 在顺序执行的事件中,如果检测到状态失败,则不再执行后续回调
    pub(crate) fn set_status(&self, status: bool) {
        self.status.store(status, Ordering::Relaxed);
    }
    pub(crate) fn get_status(&self) -> bool {
        return self.status.load(Ordering::Relaxed);
    }
    pub(crate) async fn pop_middle_event(&self) -> Option<Arc<dyn EventHandle + Send + Sync>> {
        let mut middle = self.middle.lock().await;
        middle.pop()
    }
    pub(crate) async fn push_middle_event(&self, event: Arc<dyn EventHandle + Send + Sync>) {
        let mut middle = self.middle.lock().await;
        middle.push(event);
    }
    pub(crate) async fn pop_list_event(&self) -> Option<Arc<dyn EventHandle + Send + Sync>> {
        let mut middle = self.list.lock().await;
        middle.pop()
    }
    pub(crate) async fn push_list_event(&self, event: Arc<dyn EventHandle + Send + Sync>) {
        let mut middle = self.list.lock().await;
        middle.push(event);
    }
    pub(crate) fn set_async(&self, status: bool) {
        self.is_async.store(status, Ordering::Relaxed);
    }
    pub(crate) fn get_run(&self) -> bool {
        return self.is_async.load(Ordering::Relaxed);
    }
    pub(crate) fn set_max_cycle(&mut self, max: u32) {
        self.max_cycle = max;
    }
    pub(crate) fn get_max_cycle(&mut self) -> u32 {
        self.max_cycle
    }
    pub(crate) fn load_count(&self) -> u32 {
        self.count.load(Ordering::Relaxed)
    }
    pub(crate) fn add_count(&self, i: u32) -> u32 {
        self.count.fetch_add(i, Ordering::Relaxed)
    }
    pub(crate) fn sub_count(&self, i: u32) -> u32 {
        self.count.fetch_sub(i, Ordering::Relaxed)
    }
}