Skip to main content

reifydb_runtime/actor/timers/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use std::{
5	fmt,
6	fmt::Debug,
7	sync::{
8		Arc,
9		atomic::{AtomicBool, AtomicU64, Ordering},
10	},
11};
12
13#[cfg(reifydb_target = "dst")]
14pub(crate) mod dst;
15#[cfg(reifydb_target = "native")]
16pub mod scheduler;
17#[cfg(reifydb_target = "wasi")]
18pub(crate) mod wasi;
19#[cfg(reifydb_target = "wasm")]
20pub(crate) mod wasm;
21
22#[cfg(reifydb_target = "wasi")]
23use wasi::drain_expired_timers as wasi_drain;
24
25#[derive(Clone)]
26pub struct TimerHandle {
27	id: u64,
28	cancelled: Arc<AtomicBool>,
29}
30
31impl TimerHandle {
32	pub(crate) fn new(id: u64) -> Self {
33		Self {
34			id,
35			cancelled: Arc::new(AtomicBool::new(false)),
36		}
37	}
38
39	pub fn cancel(&self) -> bool {
40		self.cancelled.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok()
41	}
42
43	pub fn is_cancelled(&self) -> bool {
44		self.cancelled.load(Ordering::SeqCst)
45	}
46
47	pub fn id(&self) -> u64 {
48		self.id
49	}
50
51	pub(crate) fn cancelled_flag(&self) -> Arc<AtomicBool> {
52		self.cancelled.clone()
53	}
54}
55
56impl Debug for TimerHandle {
57	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58		f.debug_struct("TimerHandle").field("id", &self.id).field("cancelled", &self.is_cancelled()).finish()
59	}
60}
61
62static TIMER_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
63
64pub(crate) fn next_timer_id() -> u64 {
65	TIMER_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
66}
67
68#[cfg(reifydb_target = "wasi")]
69pub fn drain_expired_timers() {
70	wasi_drain();
71}
72
73#[cfg(not(reifydb_target = "wasi"))]
74pub fn drain_expired_timers() {}