timer-deque-rs 0.7.0

A OS based timer and timer queue which implements timeout queues of different types.
Documentation
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
/*-
 * timer-deque-rs - a Rust crate which provides timer and timer queues based on target OS
 *  functionality.
 * 
 * Copyright (C) 2025 Aleksandr Morozov alex@nixd.org
 *  4neko.org alex@4neko.org
 * 
 * The timer-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::{cell::OnceCell, fmt, os::fd::{AsFd, RawFd}, sync::{Arc, Weak}};

use nix::{errno::Errno, sys::eventfd::EventFd};

use crate::
{
    FdTimerCom, 
    TimerReadRes, error::{TimerErrorType, TimerResult}, map_timer_err, timer_portable::{TimerFd, portable_error::TimerPortableErr, timer::{FdTimerMarker, FdTimerRead}}
};

#[cfg(target_os = "linux")]
pub use super::linux::timer_poll::TimerEventWatch;

#[cfg(target_os = "linux")]
pub type DefaultEventWatch = TimerEventWatch;

#[cfg(
    any(
        target_os = "freebsd",
        target_os = "dragonfly",
        target_os = "netbsd",
        target_os = "openbsd",
        target_os = "macos",
    )
)]
pub use super::bsd::TimerEventWatch;

#[cfg(any(
    target_os = "freebsd",
    target_os = "dragonfly",
    target_os = "netbsd",
    target_os = "openbsd",
    target_os = "macos",
))]
pub type DefaultEventWatch = TimerEventWatch;

/// A `poll` result.
/// 
/// `0` - [TimerFd] is a source of the event.
#[derive(Debug, PartialEq, Eq)]
pub enum PollEventType
{
    /// An event from timer. It contains a [TimerReadRes] which is received
    /// from `read()`.
    TimerRes(RawFd, TimerReadRes<u64>),

    /// Sub error which occured during `read()` or any operation on timer's 
    /// FD.
    SubError(RawFd, TimerPortableErr)
}

impl fmt::Display for PollEventType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::TimerRes(timer, res) => 
                write!(f, "timer {}, res: {}", timer, res),
            Self::SubError(timer, err) => 
                write!(f, "timer {}, error: {}", timer, err)
        }
    }
}

impl PollEventType
{
    /// Returns reference to error description.
    pub 
    fn get_err(&self) -> Option<&TimerPortableErr>
    {
        let Self::SubError(_, err) = self
        else { return None };

        return Some(err);
    }
}

/// A wrapper which provides a funtionality for the [TimerPoll].
/// 
/// A [TimerFd] should be wrapped into this instance and a poll
/// instance is attached during wrapping.
/// 
/// By calling [drop], the timer is automatically removed from the
/// `poller` and timer will be destructed too. 
/// The same situation happens if [SyncTimerFd::detach_timer]
/// is called, but the timer instance is returned.
#[derive(Debug)]
pub struct PolledTimerFd<T: FdTimerMarker>
{
    /// A timer instance. This is any timer which implements
    /// [FdTimerMarker] trait. The `Option`` is needed to overcome 
    /// problem with `drop` and fields moving.
    arc_timer: OnceCell<T>,

    /// A [Weak] back-reference to the [DefaultEventWatch] i.e 
    /// `poller`. Used to deregester the timer instance from
    /// `poller`. This was intentionaly made as a weak reference
    /// because if the poll instance will be removed, the `drop`
    /// or other thread will be able to detect that.
    poll_back_ref: Weak<DefaultEventWatch>
}

impl<T: FdTimerMarker> fmt::Display for PolledTimerFd<T> 
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "timer: {}, poll: {}", 
            self.arc_timer.get().unwrap(), 
            self.poll_back_ref.upgrade().map_or("poll instance removed".into(), |f| f.to_string())
        )
    }
}

impl<T: FdTimerMarker> Eq for PolledTimerFd<T>  {}

impl<T: FdTimerMarker> PartialEq for PolledTimerFd<T>  
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self.arc_timer == other.arc_timer;
    }
}

impl<T: FdTimerMarker> PartialEq<RawFd> for PolledTimerFd<T>  
{
    fn eq(&self, other: &RawFd) -> bool 
    {
        return self.arc_timer.get().map_or(false, |f| f == other);
    }
}

impl<T: FdTimerMarker> PartialEq<str> for PolledTimerFd<T>  
{
    fn eq(&self, other: &str) -> bool 
    {
        return self.arc_timer.get().map_or(false, |f| f.as_ref() == other);
    }
}

impl<T: FdTimerMarker> AsRef<str> for PolledTimerFd<T>  
{
    fn as_ref(&self) -> &str 
    {
        return self.arc_timer.get().unwrap().as_ref().as_ref();
    }
}


impl<T: FdTimerMarker> Ord for PolledTimerFd<T>  
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering 
    {
        return self.arc_timer.get().unwrap().as_raw_fd().cmp(&other.arc_timer.get().unwrap().as_raw_fd());
    }
}

impl<T: FdTimerMarker> PartialOrd for PolledTimerFd <T> 
{
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> 
    {
        return Some(self.cmp(other));
    }
}

impl<T: FdTimerMarker> Drop for PolledTimerFd<T>  
{
    fn drop(&mut self) 
    {
        let Some(t) = self.arc_timer.take()
        else { return };

        let Some(poll_ref) = self.poll_back_ref.upgrade()
        else { return };

        // deregester
        let _ = poll_ref.delete(&t);
    }
}

impl<T: FdTimerMarker> PolledTimerFd<T>  
{
    /// Attaches timer `T` to the provided [TimerPoll] instance and regesters
    /// the timer in the `poll` instance returning an error type in case of
    /// any errors.
    /// 
    /// # Arguments
    /// 
    /// * `timer` - `T` a timer instance which implements [FdTimerMarker]
    /// 
    /// * `poll` - a [TimerPoll] to which the timer will be added.
    /// 
    /// # Errors
    /// 
    /// * [TimerErrorType::EPoll] - error generated by the EPoll, KQueue, Poll, etc
    /// 
    /// * [TimerErrorType::Duplicate] - a duplicate record i.e FD already presents on the list 
    fn attached_timer(timer: T, poll: Weak<DefaultEventWatch>) -> TimerResult<Self> 
    {
        let once = OnceCell::new();
        once.get_or_init(|| timer);

        return Ok(
            Self
            {
                arc_timer:
                    once,
                poll_back_ref: 
                    poll
            }
        );
    }

    /// Removes the timer from the `poll` instance and releases the 
    /// timer instance.
    /// 
    /// In case, if it is not possible to relese the timer, the
    /// [Result::Err] is returnes with `Self`. Otherwise, a `T` is
    /// returned.
    pub 
    fn detach_timer(mut self) -> Result<T, Self>
    {
        // check if there are more than 2 strong references. This 
        // method needs improvement or disallow to clone the timer
        // outside of crate.
        if self.arc_timer.get().unwrap().get_strong_count() > 2
        {
            return Err(self);
        }

        if let Some(poll_ref) = self.poll_back_ref.upgrade()
        {
            let _ = poll_ref.delete(self.arc_timer.get().unwrap().as_fd());
        }

        let timer = self.arc_timer.take().unwrap();        

        return Ok(timer);
    }

    /// Checks if `poll` instance still presents. It can not verify if
    /// `poll` operates normally. Just checks if current instance is attached to
    /// the instance which is valid.
    pub 
    fn is_poll_valid(&self) -> bool
    {
        return self.poll_back_ref.upgrade().is_some();
    }

    /// Returns the reference to the inner timer.
    pub 
    fn get_inner(&self) -> &T
    {
        return self.arc_timer.get().unwrap();
    }

    // Returns the mutable reference to the inner timer.
    pub 
    fn get_inner_mut(&mut self) -> &mut T
    {
        return self.arc_timer.get_mut().unwrap();
    }
}


/// A standart functions for each timer.
pub trait TimerPollOps
{
    /// Creates new default instance.
    /// 
    /// # Returns
    /// 
    /// A [TimerResult] is returned with instance on success.
    fn new() -> TimerResult<Self> where Self: Sized;

    /// Adds the timer to the event monitor. It accepts any reference to instance which
    /// implements [AsFd] and it is not limited specificly to timers. Maybe later this
    /// behaviour will me modified.
    /// 
    /// # Arguments
    /// 
    /// * `timer` - TimerFd
    /// 
    /// # Returns
    /// 
    /// A [TimerResult] i.e [Result] is returned with error description in case of error.
    fn add(&self, timer: TimerFd) -> TimerResult<()>;

    /// Removes the specific timer's FD from the event monitor.
    /// 
    /// # Arguments
    /// 
    /// * `timer` - `T` where impl [AsTimerFd] a timer instance. 
    /// 
    /// # Returns
    /// 
    /// A [TimerResult] i.e [Result] is returned with error description in case of error.
    fn delete<FD: AsFd>(&self, timer: FD) -> TimerResult<()>;

    /// Polls the event monitor for events. Depending on the `timeout` the behaviour will
    /// be different.
    /// 
    /// 
    /// # Arguments
    /// 
    /// * `timeout` - poll timeout. If set to [Option::None] will block the current thread.
    ///     If set to [Option::Some] with inner value `0` will return immidiatly. The 
    ///     timeout is set in `miliseconds`.
    /// 
    /// # Returns 
    /// 
    /// A [TimerResult] i.e [Result] is returned with
    /// 
    /// * [Result::Ok] with the [PollResult] where:
    /// 
    ///     * [PollResult::Some] with the [Vec] with the [RawFd] of the timer's where the event has
    ///         happened.
    /// 
    ///     * [PollResult::None] if no events happened.
    /// 
    ///     * [PollResult::TimerRemoved] if timer was removed during polling operation. Otherwise,
    ///         it will not be returned. If timer was cancelled and another timer times out, the 
    ///         `TimerRemoved` will be supressed in favor of the [PollResult::Some].
    /// 
    /// * [Result::Err] with error description.
    fn poll(&self, timeout: Option<i32>) -> TimerResult<Option<Vec<PollEventType>>>;

    /// Returns the amount of timer's FDs
    fn get_count(&self) -> usize;

    /// Provides a [Weak] reference to the wakeup [EventFd].
    fn get_poll_interruptor(&self) -> PollInterrupt;

    /// Attempts to interrupt the poll operaiton. If successfull returns `true`.
    fn interrupt_poll(&self) -> bool;
}

#[derive(Debug)]
pub struct PollInterruptAq(Arc<EventFd>);

impl PollInterruptAq
{
    pub 
    fn interrupt(&self) -> TimerResult<()>
    {
        return 
            self
                .0
                .write(1)
                .map_err(|e|
                    map_timer_err!(TimerErrorType::EPoll(e), "can not interrupt POLL!")
                )
                .map(|_| ());
    }

    pub 
    fn interrupt_drop(self) -> TimerResult<()>
    {
        return 
            self.interrupt();
    }
}

// todo 
#[derive(Debug, Clone)]
pub struct PollInterrupt(Weak<EventFd>);

impl PollInterrupt
{
    pub 
    fn new(ev_weak: Weak<EventFd>) -> Self
    {
        return Self(ev_weak);
    }

    pub 
    fn aquire(&self) -> TimerResult<PollInterruptAq>
    {
        return 
            self
                .0
                .upgrade()
                .ok_or_else(||
                    map_timer_err!(TimerErrorType::EPoll(Errno::EINVAL), "timer poll has gone and not active!")
                )
                .map(|v| PollInterruptAq(v));
    }
}

/// A main instance which initializes the event listeners from the registered
/// timers.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct TimerPoll(Arc<DefaultEventWatch>);

impl fmt::Display for TimerPoll
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "{}", self.0.as_ref())
    }
}

impl TimerPoll
{
    #[inline] 
    fn get_timer(&self) -> &DefaultEventWatch
    {
        return &self.0;
    }

    /// Creates new instance of the event listener.
    pub 
    fn new() -> TimerResult<Self>
    {
        return Ok( Self( Arc::new(DefaultEventWatch::new()?) ) );
    }

    pub(super)
    fn downgrade(&self) -> Weak<DefaultEventWatch>
    {
        return Arc::downgrade(&self.0);
    }

    /// Adds the timer to the event monitor. It accepts any reference to instance which
    /// implements [AsFd] and it is not limited specificly to timers. Maybe later this
    /// behaviour will me modified.
    /// 
    /// # Arguments
    /// 
    /// * `timer` - `T` where impl [AsTimerFd] a timer instance. The provided
    ///     FD will be polled for [EpollFlags::EPOLLIN] event types. 
    ///     The FD of the timer should be inited as non-blocking, but if it is not, 
    ///     the function attepts to switch the mode. It will not be restored when
    ///     the timer will be removed from `Self`.
    /// 
    /// # Returns
    /// 
    /// A [TimerResult] i.e [Result] is returned with error description in case of error.
    pub  
    fn add<T: FdTimerMarker>(&self, timer: T) -> TimerResult<PolledTimerFd<T>>
    {
        let timer_fd: TimerFd = timer.clone_timer();

        // check if FD is non blocking, if not set nonblocking
        let timer_fd_status = 
            timer_fd
                .get_timer()
                .is_nonblocking()
                .map_err(|e| 
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), 
                        "timer: '{}', is_nonblocking error: '{}'", timer_fd, e)
                )?;

        if timer_fd_status == false
        {
            // set nonblocking
            timer_fd
                .get_timer()
                .set_nonblocking(true)
                .map_err(|e| 
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), 
                        "timer: '{}', set_nonblocking error: '{}'", timer_fd, e)
                )?
        }
        
        self.get_timer().add(timer.clone_timer())?;

        return PolledTimerFd::attached_timer(timer, self.downgrade());
    }

    /// Polls the event monitor for events. Depending on the `timeout` the behaviour will
    /// be different.
    /// 
    /// # Arguments
    /// 
    /// * `timeout` - poll timeout. If set to [Option::None] will block the current thread.
    ///     If set to [Option::Some] with inner value `0` will return immidiatly. The 
    ///     timeout is set in `miliseconds`.
    /// 
    /// # Returns 
    /// 
    /// A [TimerResult] i.e [Result] is returned with
    /// 
    /// * [Result::Ok] with the [Option] where:
    /// 
    ///     * [Option::Some] with the [Vec] with the [RawFd] of the timer's where the event has
    ///         happened.
    /// 
    ///     * [Option::None] if no events happened.
    /// 
    /// * [Result::Err] with error description.
    #[inline]
    pub  
    fn poll(&self, timeout: Option<i32>) -> TimerResult<Option<Vec<PollEventType>>>
    {
        return self.get_timer().poll(timeout);
    }

    #[inline]
    pub 
    fn get_poll_interruptor(&self) -> PollInterrupt
    {
        return self.get_timer().get_poll_interruptor();
    }

    #[inline]
    pub 
    fn interrupt_poll(&self) -> bool 
    {
        return self.get_timer().interrupt_poll();
    }
}


#[cfg(test)]
mod tests
{
    use std::{borrow::Cow, os::fd::AsRawFd};

    use crate::{common, timer_portable::{timer::{AbsoluteTime, TimerFd}, TimerExpMode, TimerFlags, TimerType}, FdTimerCom, RelativeTime, TimerPoll};

    use super::*;

    #[test]
    fn test_kqueue()
    {

        let timer1 =
            TimerFd::new("test".into(), TimerType::CLOCK_REALTIME, TimerFlags::TFD_NONBLOCK)
                .unwrap();

        let poll = TimerPoll::new().unwrap();

        let polled_timer1 = poll.add(timer1).unwrap();

        let tss_set = AbsoluteTime::now().add_sec(2);
        let tss_tm = TimerExpMode::<AbsoluteTime>::OneShot { timeout: tss_set };

        polled_timer1.get_inner().get_timer().set_time(tss_tm).unwrap();

        let res =poll.poll(None).unwrap();

        assert_eq!(res.is_some(), true);
        assert_eq!(res.as_ref().unwrap().len(), 1);
        assert_eq!(res.unwrap()[0], PollEventType::TimerRes(polled_timer1.get_inner().as_raw_fd(), crate::TimerReadRes::Ok(1)));
    }

    #[test]
    fn test_kqueue_1()
    {
        let ts = common::get_current_timestamp();

        let timer1 =
            TimerFd::new(Cow::Borrowed("test1"), TimerType::CLOCK_REALTIME, TimerFlags::TFD_NONBLOCK)
                .unwrap();

        let timer1_time =
            TimerExpMode::<AbsoluteTime>::new_oneshot(AbsoluteTime::from(ts) + RelativeTime::new_time(2, 0));

        let timer2 =
            TimerFd::new(Cow::Borrowed("test2"), TimerType::CLOCK_REALTIME, TimerFlags::TFD_NONBLOCK)
                .unwrap();

        let timer2_time =
            TimerExpMode::<AbsoluteTime>::new_oneshot(AbsoluteTime::from(ts) + RelativeTime::new_time(3, 0));



        let poll = TimerPoll::new().unwrap();

        let timer1 = poll.add(timer1).unwrap();
        let timer2 = poll.add(timer2).unwrap();

        timer1.get_inner().get_timer().set_time(timer1_time).unwrap();
        timer2.get_inner().get_timer().set_time(timer2_time).unwrap();


        let res = poll.poll(None).unwrap();

        println!("{:?}", res);

        for i in res.unwrap()
        {
            println!("{:?}", i);
        }

        let res = poll.poll(None);

        println!("{:?}", res);

        let res = poll.poll(Some(1000));

        println!("{:?}", res);

        drop(timer2);
    }
}