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
use crate::prelude::*;
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd, Reverse};
use std::collections::BinaryHeap;
use std::sync::Arc;
#[derive(Default, Eq, Debug, Copy, Clone)]
pub(crate) struct RecycleUnit {
deadline: u64,
task_id: u64,
record_id: i64,
}
impl RecycleUnit {
pub(crate) fn new(deadline: u64, task_id: u64, record_id: i64) -> Self {
RecycleUnit {
deadline,
task_id,
record_id,
}
}
}
impl Ord for RecycleUnit {
fn cmp(&self, other: &Self) -> Ordering {
self.deadline.cmp(&other.deadline)
}
}
impl PartialOrd for RecycleUnit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for RecycleUnit {
fn eq(&self, other: &Self) -> bool {
self.deadline == other.deadline
}
}
#[derive(Debug)]
pub(crate) struct RecyclingBins {
recycle_unit_heap: AsyncMutex<BinaryHeap<Reverse<RecycleUnit>>>,
recycle_unit_sources: AsyncReceiver<RecycleUnit>,
timer_event_sender: TimerEventSender,
runtime_kind: RuntimeKind,
}
impl RecyclingBins {
pub(crate) fn new(
recycle_unit_sources: AsyncReceiver<RecycleUnit>,
timer_event_sender: TimerEventSender,
runtime_kind: RuntimeKind,
) -> Self {
let recycle_unit_heap: AsyncMutex<BinaryHeap<Reverse<RecycleUnit>>> =
AsyncMutex::new(BinaryHeap::new());
let recycle_unit_sources = recycle_unit_sources;
RecyclingBins {
recycle_unit_heap,
recycle_unit_sources,
timer_event_sender,
runtime_kind,
}
}
pub(crate) async fn recycle(self: Arc<Self>) {
loop {
let mut recycle_unit_heap = self.recycle_unit_heap.lock().await;
let now: u64 = timestamp();
let mut duration: Option<Duration> = None;
for _ in 0..200 {
if let Some(recycle_flag) = recycle_unit_heap.peek().map(|r| r.0.deadline <= now) {
if !recycle_flag {
duration = recycle_unit_heap
.peek()
.map(|r| r.0.deadline - now)
.map(Duration::from_secs);
break;
}
if let Some(recycle_unit) = recycle_unit_heap.pop().map(|v| v.0) {
self.send_timer_event(TimerEvent::TimeoutTask(
recycle_unit.task_id,
recycle_unit.record_id,
))
.await;
}
} else {
break;
}
}
drop(recycle_unit_heap);
self.yield_for_while(duration).await;
}
}
pub(crate) async fn send_timer_event(&self, event: TimerEvent) {
self.timer_event_sender
.send(event)
.await
.unwrap_or_else(|e| error!(" `send_timer_event` : {}", e));
}
pub(crate) async fn add_recycle_unit(self: Arc<Self>) {
'loopLayer: loop {
for _ in 0..200 {
match self.recycle_unit_sources.recv().await {
Ok(recycle_unit) => {
let mut recycle_unit_heap = self.recycle_unit_heap.lock().await;
recycle_unit_heap.push(Reverse(recycle_unit));
}
Err(_) => {
break 'loopLayer;
}
}
}
yield_now().await;
}
}
pub(crate) async fn yield_for_while(&self, duration: Option<Duration>) {
let duration = duration.unwrap_or_else(|| Duration::from_secs(3));
match self.runtime_kind {
RuntimeKind::Smol => {
AsyncTimer::after(duration).await;
}
RuntimeKind::Tokio => {
sleep_by_tokio(duration).await;
}
}
}
}
mod tests {
#[allow(unused_imports)]
use anyhow::Result as AnyResult;
#[test]
fn test_task_valid() -> AnyResult<()> {
use super::{timestamp, RecycleUnit, RecyclingBins, RuntimeKind, TimerEvent};
use smol::{
block_on,
channel::{unbounded, TryRecvError},
future::FutureExt,
};
use std::{
sync::Arc,
thread::{park_timeout, spawn as thread_spawn},
time::Duration,
};
let (timer_event_sender, timer_event_receiver) = unbounded::<TimerEvent>();
let (recycle_unit_sender, recycle_unit_receiver) = unbounded::<RecycleUnit>();
let recycling_bins = Arc::new(RecyclingBins::new(
recycle_unit_receiver,
timer_event_sender,
RuntimeKind::Smol,
));
thread_spawn(move || {
block_on(async {
recycling_bins
.clone()
.recycle()
.or(recycling_bins.add_recycle_unit())
.await;
})
});
let deadline = timestamp() + 5;
for i in 1..10 {
recycle_unit_sender.try_send(RecycleUnit::new(deadline, i, (i * i) as i64))?;
}
park_timeout(Duration::new(2, 0));
if let Err(e) = timer_event_receiver.try_recv() {
assert_eq!(e, TryRecvError::Empty);
}
park_timeout(Duration::from_secs(4));
for _ in 1..10 {
assert!(dbg!(timer_event_receiver.try_recv()).is_ok());
}
Ok(())
}
}