ntex_io/
timer.rs

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
#![allow(clippy::mutable_key_type)]
use std::collections::{BTreeMap, VecDeque};
use std::{cell::Cell, cell::RefCell, ops, rc::Rc, time::Duration, time::Instant};

use ntex_util::time::{now, sleep, Seconds};
use ntex_util::{spawn, HashSet};

use crate::{io::IoState, IoRef};

const CAP: usize = 64;
const SEC: Duration = Duration::from_secs(1);

thread_local! {
    static TIMER: Inner = Inner {
        running: Cell::new(false),
        base: Cell::new(Instant::now()),
        current: Cell::new(0),
        storage: RefCell::new(InnerMut {
            cache: VecDeque::with_capacity(CAP),
            notifications: BTreeMap::default(),
        })
    }
}

#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct TimerHandle(u32);

impl TimerHandle {
    pub const ZERO: TimerHandle = TimerHandle(0);

    pub fn is_set(&self) -> bool {
        self.0 != 0
    }

    pub fn remains(&self) -> Seconds {
        TIMER.with(|timer| {
            let cur = timer.current.get();
            if self.0 <= cur {
                Seconds::ZERO
            } else {
                Seconds((self.0 - cur) as u16)
            }
        })
    }

    pub fn instant(&self) -> Instant {
        TIMER.with(|timer| timer.base.get() + Duration::from_secs(self.0 as u64))
    }
}

impl ops::Add<Seconds> for TimerHandle {
    type Output = TimerHandle;

    #[inline]
    fn add(self, other: Seconds) -> TimerHandle {
        TimerHandle(self.0 + other.0 as u32)
    }
}

struct Inner {
    running: Cell<bool>,
    base: Cell<Instant>,
    current: Cell<u32>,
    storage: RefCell<InnerMut>,
}

struct InnerMut {
    cache: VecDeque<HashSet<Rc<IoState>>>,
    notifications: BTreeMap<u32, HashSet<Rc<IoState>>>,
}

impl InnerMut {
    fn unregister(&mut self, hnd: TimerHandle, io: &IoRef) {
        if let Some(states) = self.notifications.get_mut(&hnd.0) {
            states.remove(&io.0);
        }
    }
}

pub(crate) fn unregister(hnd: TimerHandle, io: &IoRef) {
    TIMER.with(|timer| {
        timer.storage.borrow_mut().unregister(hnd, io);
    })
}

pub(crate) fn update(hnd: TimerHandle, timeout: Seconds, io: &IoRef) -> TimerHandle {
    TIMER.with(|timer| {
        let new_hnd = timer.current.get() + timeout.0 as u32;
        if hnd.0 == new_hnd || hnd.0 == new_hnd + 1 {
            hnd
        } else {
            timer.storage.borrow_mut().unregister(hnd, io);
            register(timeout, io)
        }
    })
}

pub(crate) fn register(timeout: Seconds, io: &IoRef) -> TimerHandle {
    TIMER.with(|timer| {
        // setup current delta
        if !timer.running.get() {
            let current = (now() - timer.base.get()).as_secs() as u32;
            timer.current.set(current);
            log::debug!(
                "{}: Timer driver does not run, current: {}",
                io.tag(),
                current
            );
        }

        let hnd = {
            let hnd = timer.current.get() + timeout.0 as u32;
            let mut inner = timer.storage.borrow_mut();

            // insert key
            if let Some(item) = inner.notifications.range_mut(hnd..hnd + 1).next() {
                item.1.insert(io.0.clone());
                *item.0
            } else {
                let mut items = inner.cache.pop_front().unwrap_or_default();
                items.insert(io.0.clone());
                inner.notifications.insert(hnd, items);
                hnd
            }
        };

        if !timer.running.get() {
            timer.running.set(true);

            #[allow(clippy::let_underscore_future)]
            let _ = spawn(async move {
                let guard = TimerGuard;
                loop {
                    sleep(SEC).await;
                    let stop = TIMER.with(|timer| {
                        let current = timer.current.get();
                        timer.current.set(current + 1);

                        // notify io dispatcher
                        let mut inner = timer.storage.borrow_mut();
                        while let Some(key) = inner.notifications.keys().next() {
                            let key = *key;
                            if key <= current {
                                let mut items = inner.notifications.remove(&key).unwrap();
                                items.drain().for_each(|st| st.notify_timeout());
                                if inner.cache.len() <= CAP {
                                    inner.cache.push_back(items);
                                }
                            } else {
                                break;
                            }
                        }

                        // new tick
                        if inner.notifications.is_empty() {
                            timer.running.set(false);
                            true
                        } else {
                            false
                        }
                    });

                    if stop {
                        break;
                    }
                }
                drop(guard);
            });
        }

        TimerHandle(hnd)
    })
}

struct TimerGuard;

impl Drop for TimerGuard {
    fn drop(&mut self) {
        TIMER.with(|timer| {
            timer.running.set(false);
            timer.storage.borrow_mut().notifications.clear();
        })
    }
}