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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::coroutine::suspender::Suspender;
use crate::coroutine::{Coroutine, CoroutineState};
use crate::scheduler::listener::Listener;
use corosensei::stack::DefaultStack;
use corosensei::ScopedCoroutine;
use once_cell::sync::Lazy;
use open_coroutine_queue::{LocalQueue, WorkStealQueue};
use open_coroutine_timer::TimerList;
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::time::Duration;
use uuid::Uuid;

pub mod listener;

/// 源协程
#[allow(dead_code)]
type RootCoroutine<'a> = ScopedCoroutine<'a, (), (), (), DefaultStack>;

/// 用户协程
pub type SchedulableCoroutine = Coroutine<'static, (), (), usize>;

static QUEUE: Lazy<WorkStealQueue<SchedulableCoroutine>> = Lazy::new(WorkStealQueue::default);

static mut SUSPEND_TABLE: Lazy<TimerList<SchedulableCoroutine>> = Lazy::new(TimerList::new);

static mut SYSTEM_CALL_TABLE: Lazy<HashMap<&str, SchedulableCoroutine>> = Lazy::new(HashMap::new);

#[allow(dead_code)]
static mut COPY_STACK_TABLE: Lazy<HashMap<&str, SchedulableCoroutine>> = Lazy::new(HashMap::new);

static mut RESULT_TABLE: Lazy<HashMap<&str, SchedulableCoroutine>> = Lazy::new(HashMap::new);

#[repr(C)]
#[derive(Debug)]
pub struct Scheduler {
    name: &'static str,
    ready: LocalQueue<'static, SchedulableCoroutine>,
    listeners: RefCell<VecDeque<Box<dyn Listener>>>,
}

impl Drop for Scheduler {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            assert!(
                self.ready.is_empty(),
                "there are still tasks to be carried out !"
            );
        }
    }
}

impl Scheduler {
    #[must_use]
    pub fn new() -> Self {
        Self::with_name(Box::from(Uuid::new_v4().to_string()))
    }

    pub fn with_name(name: Box<str>) -> Self {
        Scheduler {
            name: Box::leak(name),
            ready: QUEUE.local_queue(),
            listeners: RefCell::default(),
        }
    }

    #[must_use]
    pub fn current<'s>() -> Option<&'s Scheduler> {
        if let Some(current) = SchedulableCoroutine::current() {
            if let Some(scheduler) = current.get_scheduler() {
                return Some(unsafe { &*scheduler });
            }
        }
        None
    }

    pub fn submit(
        &self,
        f: impl FnOnce(&Suspender<'_, (), ()>, ()) -> usize + 'static,
        stack_size: Option<usize>,
    ) -> std::io::Result<&'static str> {
        let coroutine = SchedulableCoroutine::new(
            Box::from(format!("{}|{}", self.name, Uuid::new_v4())),
            f,
            stack_size.unwrap_or(crate::coroutine::default_stack_size()),
        )?;
        assert_eq!(
            CoroutineState::Created,
            coroutine.set_state(CoroutineState::Ready)
        );
        let co_name = Box::leak(Box::from(coroutine.get_name()));
        self.on_create(&coroutine);
        self.ready.push_back(coroutine);
        Ok(co_name)
    }

    fn check_ready(&self) {
        unsafe {
            for _ in 0..SUSPEND_TABLE.len() {
                if let Some(entry) = SUSPEND_TABLE.front() {
                    let exec_time = entry.get_time();
                    if open_coroutine_timer::now() < exec_time {
                        break;
                    }
                    //移动至"就绪"队列
                    if let Some(mut entry) = SUSPEND_TABLE.pop_front() {
                        for _ in 0..entry.len() {
                            if let Some(coroutine) = entry.pop_front() {
                                let old = coroutine.set_state(CoroutineState::Ready);
                                match old {
                                    CoroutineState::Suspend(_) => {}
                                    _ => panic!("{} unexpected state {old}", coroutine.get_name()),
                                };
                                //把到时间的协程加入就绪队列
                                self.ready.push_back(coroutine);
                            }
                        }
                    }
                }
            }
        }
    }

    pub fn try_schedule(&self) {
        _ = self.try_timeout_schedule(Duration::MAX.as_secs());
    }

    pub fn try_timed_schedule(&self, time: Duration) -> u64 {
        self.try_timeout_schedule(open_coroutine_timer::get_timeout_time(time))
    }

    pub fn try_timeout_schedule(&self, timeout_time: u64) -> u64 {
        loop {
            let left_time = timeout_time.saturating_sub(open_coroutine_timer::now());
            if left_time == 0 {
                return 0;
            }
            self.check_ready();
            match self.ready.pop_front() {
                Some(mut coroutine) => {
                    _ = coroutine.set_scheduler(self);
                    cfg_if::cfg_if! {
                        if #[cfg(all(unix, feature = "preemptive-schedule"))] {
                            let start = open_coroutine_timer::get_timeout_time(Duration::from_millis(10));
                            crate::monitor::Monitor::add_task(start, Some(&coroutine));
                        }
                    }
                    match coroutine.resume() {
                        CoroutineState::Suspend(timestamp) => {
                            self.on_suspend(&coroutine);
                            if timestamp > 0 {
                                //挂起协程到时间轮
                                unsafe { SUSPEND_TABLE.insert(timestamp, coroutine) };
                            } else {
                                //放入就绪队列尾部
                                self.ready.push_back(coroutine);
                            }
                        }
                        CoroutineState::SystemCall(syscall_name) => {
                            self.on_syscall(&coroutine, syscall_name);
                            //挂起协程到系统调用表
                            let co_name = Box::leak(Box::from(coroutine.get_name()));
                            unsafe {
                                assert!(SYSTEM_CALL_TABLE.insert(co_name, coroutine).is_none());
                            }
                        }
                        CoroutineState::CopyStack => {
                            todo!()
                        }
                        CoroutineState::Finished => {
                            self.on_finish(&coroutine);
                            let name = Box::leak(Box::from(coroutine.get_name()));
                            _ = unsafe { RESULT_TABLE.insert(name, coroutine) };
                        }
                        _ => unreachable!("should never execute to here"),
                    };
                    cfg_if::cfg_if! {
                        if #[cfg(all(unix, feature = "preemptive-schedule"))] {
                            //还没执行到10ms就主动yield或者执行完毕了,此时需要清理任务
                            //否则下一个协程执行不到10ms就会被抢占调度
                            crate::monitor::Monitor::clean_task(start);
                        }
                    }
                }
                None => return left_time,
            }
        }
    }

    pub fn add_listener(&self, listener: impl Listener + 'static) {
        loop {
            if let Ok(mut listeners) = self.listeners.try_borrow_mut() {
                listeners.push_back(Box::new(listener));
                return;
            }
        }
    }

    fn on_create(&self, coroutine: &SchedulableCoroutine) {
        for listener in self.listeners.borrow().iter() {
            listener.on_create(coroutine);
        }
    }

    fn on_suspend(&self, coroutine: &SchedulableCoroutine) {
        for listener in self.listeners.borrow().iter() {
            listener.on_suspend(coroutine);
        }
    }

    fn on_syscall(&self, coroutine: &SchedulableCoroutine, syscall_name: &str) {
        for listener in self.listeners.borrow().iter() {
            listener.on_syscall(coroutine, syscall_name);
        }
    }

    fn on_finish(&self, coroutine: &SchedulableCoroutine) {
        for listener in self.listeners.borrow().iter() {
            listener.on_finish(coroutine);
        }
    }

    //只有框架级crate才需要使用此方法
    pub fn resume_syscall(&self, co_name: &'static str) {
        unsafe {
            if let Some(coroutine) = SYSTEM_CALL_TABLE.remove(&co_name) {
                self.ready.push_back(coroutine);
            }
        }
    }

    pub fn get_result(co_name: &'static str) -> Option<SchedulableCoroutine> {
        unsafe { RESULT_TABLE.remove(&co_name) }
    }
}

impl Default for Scheduler {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple() {
        let scheduler = Scheduler::new();
        _ = scheduler.submit(
            |_, _| {
                println!("1");
                1
            },
            None,
        );
        _ = scheduler.submit(
            |_, _| {
                println!("2");
                2
            },
            None,
        );
        scheduler.try_schedule();
    }

    #[test]
    fn test_backtrace() {
        let scheduler = Scheduler::new();
        _ = scheduler.submit(|_, _| 1, None);
        _ = scheduler.submit(
            |_, _| {
                println!("{:?}", backtrace::Backtrace::new());
                2
            },
            None,
        );
        scheduler.try_schedule();
    }

    #[test]
    fn with_suspend() {
        let scheduler = Scheduler::new();
        _ = scheduler.submit(
            |suspender, _| {
                println!("[coroutine1] suspend");
                suspender.suspend();
                println!("[coroutine1] back");
                1
            },
            None,
        );
        _ = scheduler.submit(
            |suspender, _| {
                println!("[coroutine2] suspend");
                suspender.suspend();
                println!("[coroutine2] back");
                2
            },
            None,
        );
        scheduler.try_schedule();
    }

    #[test]
    fn with_delay() {
        let scheduler = Scheduler::new();
        _ = scheduler.submit(
            |suspender, _| {
                println!("[coroutine] delay");
                suspender.delay(Duration::from_millis(100));
                println!("[coroutine] back");
                1
            },
            None,
        );
        scheduler.try_schedule();
        std::thread::sleep(Duration::from_millis(100));
        scheduler.try_schedule();
    }

    #[cfg(feature = "preemptive-schedule")]
    #[test]
    fn preemptive_schedule() -> std::io::Result<()> {
        use std::sync::{Arc, Condvar, Mutex};
        static mut TEST_FLAG1: bool = true;
        static mut TEST_FLAG2: bool = true;
        let pair = Arc::new((Mutex::new(true), Condvar::new()));
        let pair2 = Arc::clone(&pair);
        let handler = std::thread::Builder::new()
            .name("test_preemptive_schedule".to_string())
            .spawn(move || {
                let scheduler = Box::leak(Box::new(Scheduler::new()));
                _ = scheduler.submit(
                    |_, _| {
                        unsafe {
                            while TEST_FLAG1 {
                                _ = libc::usleep(10_000);
                            }
                        }
                        1
                    },
                    None,
                );
                _ = scheduler.submit(
                    |_, _| {
                        unsafe {
                            while TEST_FLAG2 {
                                _ = libc::usleep(10_000);
                            }
                        }
                        unsafe { TEST_FLAG1 = false };
                        2
                    },
                    None,
                );
                _ = scheduler.submit(
                    |_, _| {
                        unsafe { TEST_FLAG2 = false };
                        3
                    },
                    None,
                );
                scheduler.try_schedule();

                let (lock, cvar) = &*pair2;
                let mut pending = lock.lock().unwrap();
                *pending = false;
                // notify the condvar that the value has changed.
                cvar.notify_one();
            })
            .expect("failed to spawn thread");

        // wait for the thread to start up
        let (lock, cvar) = &*pair;
        let result = cvar
            .wait_timeout_while(
                lock.lock().unwrap(),
                Duration::from_millis(3000),
                |&mut pending| pending,
            )
            .unwrap();
        if result.1.timed_out() {
            Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "preemptive schedule failed",
            ))
        } else {
            unsafe {
                handler.join().unwrap();
                assert!(!TEST_FLAG1);
            }
            Ok(())
        }
    }
}