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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use pendulum::Pendulum;
use futures::Stream;
use std::sync::atomic::{Ordering, AtomicUsize};
use pendulum::Token;
use error::{PendulumResult, PendulumErrorKind, PendulumError};
use std::collections::HashMap;
use std::thread::Thread;
use std::sync::Arc;
use std::thread;
use futures::Poll;
use futures::Future;
use futures::Async;
use futures::task::{self, Task};
use std::time::Instant;
use std::time::Duration;
use crossbeam::sync::SegQueue;
const DEFAULT_CHANNEL_CAPACITY: usize = 128;
pub struct TimerBuilder {
channel_capacity: usize
}
impl TimerBuilder {
pub fn with_channel_capacity(mut self, capacity: usize) -> TimerBuilder {
self.channel_capacity = capacity;
self
}
pub fn channel_capacity(&self) -> usize {
self.channel_capacity
}
pub fn build<P>(self, pendulum: P) -> Timer
where P: Pendulum<TimerItem> + Send + 'static {
Timer::new(self, pendulum)
}
}
impl Default for TimerBuilder {
fn default() -> TimerBuilder {
TimerBuilder{ channel_capacity: DEFAULT_CHANNEL_CAPACITY }
}
}
pub struct TimedOut;
#[derive(Debug, PartialEq, Eq)]
pub enum TimeoutStatus<T> {
Original(T),
TimedOut
}
impl<T> From<TimedOut> for TimeoutStatus<T> {
fn from(_: TimedOut) -> TimeoutStatus<T> {
TimeoutStatus::TimedOut
}
}
pub struct Timeout<F> {
opt_sleep: Option<Sleep>,
future: F
}
impl<F> Future for Timeout<F> where F: Future, F::Error: From<TimedOut> {
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let opt_poll_result = self.opt_sleep.as_mut().map(Future::poll);
match opt_poll_result {
Some(Ok(Async::Ready(()))) => {
self.opt_sleep.take();
Err(TimedOut.into())
},
Some(_) => {
self.future.poll()
},
None => {
Err(TimedOut.into())
}
}
}
}
pub struct TimeoutStream<S> {
sleep: Sleep,
stream: S
}
impl<S> Stream for TimeoutStream<S> where S: Stream, S::Error: From<TimedOut> {
type Item = S::Item;
type Error = S::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let sleep_result = self.sleep.poll();
match sleep_result {
Ok(Async::Ready(())) => {
Err(TimedOut.into())
},
_ => self.stream.poll()
}
}
}
pub struct Heartbeat<S> {
sleep: Sleep,
stream: S
}
impl<S> Stream for Heartbeat<S> where S: Stream, S::Item: From<TimedOut> {
type Item = S::Item;
type Error = S::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let sleep_result = self.sleep.poll();
match sleep_result {
Ok(Async::Ready(())) => {
self.sleep.restart();
Ok(Async::Ready(Some(TimedOut.into())))
},
_ => self.stream.poll()
}
}
}
pub struct SleepStream {
sleep: Sleep
}
impl SleepStream {
fn new(sleep: Sleep) -> SleepStream {
SleepStream{ sleep: sleep }
}
}
impl Stream for SleepStream {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Option<()>, ()> {
let poll_result = self.sleep.poll();
if let Ok(Async::Ready(())) = poll_result {
self.sleep.restart();
}
poll_result.map(|async| async.map(Option::Some))
}
}
pub struct Sleep {
mapping: usize,
duration: Duration,
started: Instant,
sent_task: Option<Task>,
futures: Timer
}
impl Sleep {
fn new(mapping: usize, duration: Duration, futures: Timer) -> Sleep {
Sleep{ mapping: mapping, duration: duration, started: Instant::now(), sent_task: None, futures: futures }
}
fn restart(&mut self) {
self.sent_task = None;
self.started = Instant::now();
}
}
impl Future for Sleep {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
if Instant::now().duration_since(self.started) >= self.duration {
return Ok(Async::Ready(()))
}
let should_send_create = self.sent_task.as_ref()
.map(|task| !task.will_notify_current())
.unwrap_or(true);
if should_send_create {
let sent = self.futures.inner.try_push_create_timer(CreateTimeout{
mapping: self.mapping, duration: self.duration, started: self.started, task: task::current() });
if !sent {
warn!("Couldnt Send a Create Timeout Request From Sleep; Backing Thread May Be Running Slow");
task::current().notify();
} else {
self.sent_task = Some(task::current());
self.futures.thread.unpark();
}
}
Ok(Async::NotReady)
}
}
impl Drop for Sleep {
fn drop(&mut self) {
if self.sent_task.is_some() {
let sent = self.futures.inner.try_push_delete_timer(DeleteTimeout{ mapping: self.mapping });
if !sent {
warn!("Couldnt Send A Delete Timeout Request From Sleep; Backing Thread May Be Running Slow");
self.futures.inner.return_mapping(self.mapping);
} else {
self.futures.thread.unpark();
}
} else {
self.futures.inner.return_mapping(self.mapping);
}
}
}
#[derive(Clone)]
pub struct Timer {
inner: Arc<InnerTimer>,
thread: Arc<Thread>,
max_timeout: Duration
}
impl Timer {
pub fn new<P>(builder: TimerBuilder, pendulum: P) -> Timer
where P: Pendulum<TimerItem> + Send + 'static {
let inner = Arc::new(InnerTimer::new(pendulum.max_capacity(), builder.channel_capacity()));
let max_timeout = pendulum.max_timeout();
let thread_inner = inner.clone();
let thread_handle = thread::spawn(move || run_pendulum_timer(thread_inner, pendulum)).thread().clone();
Timer{ inner: inner, thread: Arc::new(thread_handle), max_timeout: max_timeout }
}
pub fn sleep(&self, duration: Duration) -> PendulumResult<Sleep, ()> {
self.validate_request(duration).map(|mapping| {
Sleep::new(mapping, duration, self.clone())
})
}
pub fn sleep_stream(&self, duration: Duration) -> PendulumResult<SleepStream, ()> {
self.sleep(duration).map(SleepStream::new)
}
pub fn timeout<F>(&self, duration: Duration, future: F) -> PendulumResult<Timeout<F>, ()>
where F: Future, F::Error: From<TimedOut> {
self.sleep(duration).map(|sleep| Timeout{ opt_sleep: Some(sleep), future: future })
}
pub fn timeout_stream<S>(&self, duration: Duration, stream: S) -> PendulumResult<TimeoutStream<S>, ()>
where S: Stream, S::Error: From<TimedOut> {
self.sleep(duration).map(|sleep| TimeoutStream{ sleep: sleep, stream: stream })
}
pub fn heartbeat<S>(&self, duration: Duration, stream: S) -> PendulumResult<Heartbeat<S>, ()>
where S: Stream, S::Item: From<TimedOut> {
self.sleep(duration).map(|sleep| Heartbeat{ sleep: sleep, stream: stream })
}
fn validate_request(&self, duration: Duration) -> PendulumResult<usize, ()> {
if duration > self.max_timeout {
Err(PendulumError::new((), PendulumErrorKind::MaxCapacityReached))
} else {
self.inner.try_retrieve_mapping()
.ok_or_else(|| PendulumError::new((), PendulumErrorKind::MaxTimeoutExceeded))
}
}
}
#[derive(Debug)]
pub struct TimerItem {
task: Task,
started: Instant,
duration: Duration,
mapping: usize
}
fn run_pendulum_timer<P>(inner: Arc<InnerTimer>, mut pendulum: P)
where P: Pendulum<TimerItem> {
let mut current_time;
let mut last_tick_time = Instant::now();
let mut leftover_tick = Duration::new(0, 0);
let mut mapping_table: HashMap<usize, Token> = HashMap::with_capacity(pendulum.max_capacity());
loop {
current_time = Instant::now();
let mut duration_since_last_tick = current_time.duration_since(last_tick_time) + leftover_tick;
while duration_since_last_tick >= pendulum.tick_duration() {
duration_since_last_tick -= pendulum.tick_duration();
pendulum.tick();
last_tick_time = current_time;
}
leftover_tick = duration_since_last_tick;
while let Some(request) = inner.try_pop_request() {
match request {
TimeoutRequest::Create(create_request) => {
current_time = Instant::now();
let time_to_schedule = current_time.duration_since(create_request.started);
let real_timeout = create_request.duration.checked_sub(time_to_schedule).unwrap_or(Duration::new(0, 0));
if real_timeout == Duration::new(0, 0) {
create_request.task.notify()
} else {
duration_since_last_tick = current_time.duration_since(last_tick_time) + leftover_tick;
let accurate_real_timeout = real_timeout + duration_since_last_tick;
let item = TimerItem{ task: create_request.task, started: create_request.started,
duration: create_request.duration, mapping: create_request.mapping };
let token = pendulum.insert_timeout(accurate_real_timeout, item)
.expect("pendulum: Failed To Push Timeout Onto Pendulum");
mapping_table.insert(create_request.mapping, token);
}
},
TimeoutRequest::Delete(delete_request) => {
let mapping = delete_request.mapping;
if let Some(token) = mapping_table.remove(&mapping) {
pendulum.remove_timeout(token);
}
inner.return_mapping(delete_request.mapping);
}
}
}
current_time = Instant::now();
while let Some(TimerItem{ task, started, duration, mapping }) = pendulum.expired_timeout() {
let total_time = current_time.duration_since(started);
if total_time < duration {
let requeue_duration = duration - total_time;
warn!("Task Was Ready Before Duration Of {:?} Was Up, Leftover Duration Was {:?}; Re-Queueing", duration, requeue_duration);
let item = TimerItem{ task: task, started: started, duration: duration, mapping: mapping };
let token = pendulum.insert_timeout(requeue_duration, item)
.expect("pendulum: Failed To Re-Push Timeout Onto Pendulum");
mapping_table.insert(mapping, token);
} else {
task.notify()
}
}
let time_to_next_tick = pendulum.tick_duration() - leftover_tick;
thread::park_timeout(time_to_next_tick);
}
}
enum TimeoutRequest {
Create(CreateTimeout),
Delete(DeleteTimeout)
}
struct CreateTimeout {
mapping: usize,
duration: Duration,
started: Instant,
task: Task
}
struct DeleteTimeout {
mapping: usize
}
struct InnerTimer {
mapping_queue: SegQueue<usize>,
request_queue: (SegQueue<TimeoutRequest>, AtomicUsize),
channel_capacity: usize
}
impl InnerTimer {
pub fn new(timer_capacity: usize, channel_capacity: usize) -> InnerTimer {
let mapping_queue = SegQueue::new();
let mut next_mapping = 0;
for _ in 0..timer_capacity {
mapping_queue.push(next_mapping);
next_mapping += 1;
}
InnerTimer{ mapping_queue: mapping_queue, request_queue: (SegQueue::new(), AtomicUsize::new(0)),
channel_capacity: channel_capacity }
}
pub fn channel_capacity(&self) -> usize {
self.channel_capacity
}
pub fn try_retrieve_mapping(&self) -> Option<usize> {
self.mapping_queue.try_pop()
}
pub fn return_mapping(&self, mapping: usize) {
self.mapping_queue.push(mapping)
}
pub fn try_push_create_timer(&self, timer: CreateTimeout) -> bool {
try_push(&self.request_queue.0, &self.request_queue.1, self.channel_capacity(), TimeoutRequest::Create(timer))
}
pub fn try_push_delete_timer(&self, timer: DeleteTimeout) -> bool {
try_push(&self.request_queue.0, &self.request_queue.1, self.channel_capacity(), TimeoutRequest::Delete(timer))
}
pub fn try_pop_request(&self) -> Option<TimeoutRequest> {
self.request_queue.0.try_pop().map(|request| {
self.request_queue.1.fetch_sub(1, Ordering::AcqRel);
request
})
}
}
fn try_push<T>(queue: &SegQueue<T>, len: &AtomicUsize, capacity: usize, item: T) -> bool {
let queue_size = len.fetch_add(1, Ordering::AcqRel);
if queue_size >= capacity {
len.fetch_sub(1, Ordering::Relaxed);
false
} else {
queue.push(item);
true
}
}
#[cfg(test)]
mod tests {
use super::{TimerBuilder, TimeoutStatus};
use wheel::HashedWheelBuilder;
use std::time::{Duration};
use futures::{Future, Stream};
use futures::sync::mpsc::{self, UnboundedReceiver};
use futures::future;
#[test]
fn positive_sleep_wakes_on_milli() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let sleep = timer
.sleep(Duration::from_millis(50))
.unwrap();
sleep.wait().unwrap();
}
#[test]
fn positive_sleep_wakes_on_nano() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let sleep = timer
.sleep(Duration::new(0, 1))
.unwrap();
sleep.wait().unwrap();
}
#[test]
fn positive_sleep_wakes_on_zero() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let sleep = timer
.sleep(Duration::new(0, 0))
.unwrap();
sleep.wait().unwrap();
}
#[test]
fn positive_sleep_stream_yields_twice() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let mut stream = timer
.sleep_stream(Duration::from_millis(50))
.unwrap()
.wait();
stream.next().unwrap().unwrap();
stream.next().unwrap().unwrap();
}
#[test]
fn positive_heartbeat_sends_timeout() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let (_send, recv): (_, UnboundedReceiver<TimeoutStatus<()>>) = mpsc::unbounded();
let mut stream = timer
.heartbeat(Duration::from_millis(50), recv)
.unwrap()
.wait();
assert_eq!(TimeoutStatus::TimedOut, stream.next().unwrap().unwrap());
assert_eq!(TimeoutStatus::TimedOut, stream.next().unwrap().unwrap());
}
#[test]
fn positive_heartbeat_sends_item() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let (send, recv): (_, UnboundedReceiver<TimeoutStatus<()>>) = mpsc::unbounded();
send.unbounded_send(TimeoutStatus::Original(())).unwrap();
send.unbounded_send(TimeoutStatus::Original(())).unwrap();
let mut stream = timer
.heartbeat(Duration::from_millis(50), recv)
.unwrap()
.wait();
assert_eq!(TimeoutStatus::Original(()), stream.next().unwrap().unwrap());
assert_eq!(TimeoutStatus::Original(()), stream.next().unwrap().unwrap());
}
#[test]
fn positive_heartbeat_send_item_and_timeout() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let (send, recv): (_, UnboundedReceiver<TimeoutStatus<()>>) = mpsc::unbounded();
send.unbounded_send(TimeoutStatus::Original(())).unwrap();
send.unbounded_send(TimeoutStatus::Original(())).unwrap();
let mut stream = timer
.heartbeat(Duration::from_millis(50), recv)
.unwrap()
.wait();
assert_eq!(TimeoutStatus::Original(()), stream.next().unwrap().unwrap());
assert_eq!(TimeoutStatus::Original(()), stream.next().unwrap().unwrap());
assert_eq!(TimeoutStatus::TimedOut, stream.next().unwrap().unwrap());
}
#[test]
fn positive_timeout_times_out() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let result = timer
.timeout(Duration::from_millis(50), future::empty::<(), TimeoutStatus<()>>())
.unwrap()
.wait();
assert_eq!(TimeoutStatus::TimedOut, result.unwrap_err());
}
#[test]
fn positive_timeout_stream_times_out() {
let timer = TimerBuilder::default()
.build(HashedWheelBuilder::default().build());
let (_send, recv): (_, UnboundedReceiver<()>) = mpsc::unbounded();
let mut stream = timer
.timeout_stream(Duration::from_millis(50), recv.map_err(TimeoutStatus::Original))
.unwrap()
.wait();
assert_eq!(TimeoutStatus::TimedOut, stream.next().unwrap().unwrap_err());
assert_eq!(TimeoutStatus::TimedOut, stream.next().unwrap().unwrap_err());
}
}