Skip to main content

reifydb_runtime/actor/timers/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4//! Timer utilities for actors.
5//!
6//! This module provides timer functionality for scheduling messages:
7//! - [`TimerHandle`]: A handle to cancel a scheduled timer
8//! - [`Context::schedule_once`]: Schedule a message to be sent after a delay
9//! - [`Context::schedule_repeat`]: Schedule a message to be sent repeatedly
10//!
11//! # Platform Differences
12//!
13//! - **Native**: Uses a centralized scheduler with a BinaryHeap min-heap
14//! - **WASM**: Uses `setTimeout` and `setInterval` via `web-sys`
15//!
16//! [`Context::schedule_once`]: crate::actor::context::Context::schedule_once
17//! [`Context::schedule_repeat`]: crate::actor::context::Context::schedule_repeat
18
19use std::{
20	fmt,
21	fmt::Debug,
22	sync::{
23		Arc,
24		atomic::{AtomicBool, AtomicU64, Ordering},
25	},
26};
27
28#[cfg(reifydb_target = "native")]
29pub mod scheduler;
30#[cfg(reifydb_target = "wasi")]
31pub(crate) mod wasi;
32#[cfg(reifydb_target = "wasm")]
33pub(crate) mod wasm;
34
35#[cfg(reifydb_target = "wasi")]
36use wasi::drain_expired_timers as wasi_drain;
37
38/// Handle to a scheduled timer.
39///
40/// Can be used to cancel the timer before it fires.
41#[derive(Clone)]
42pub struct TimerHandle {
43	id: u64,
44	cancelled: Arc<AtomicBool>,
45}
46
47impl TimerHandle {
48	pub(crate) fn new(id: u64) -> Self {
49		Self {
50			id,
51			cancelled: Arc::new(AtomicBool::new(false)),
52		}
53	}
54
55	/// Cancel this timer.
56	///
57	/// If the timer hasn't fired yet, it will be cancelled.
58	/// Returns `true` if the timer was successfully cancelled.
59	pub fn cancel(&self) -> bool {
60		self.cancelled.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_ok()
61	}
62
63	/// Check if this timer has been cancelled.
64	pub fn is_cancelled(&self) -> bool {
65		self.cancelled.load(Ordering::SeqCst)
66	}
67
68	/// Get the timer ID.
69	pub fn id(&self) -> u64 {
70		self.id
71	}
72
73	/// Get a clone of the cancelled flag.
74	pub(crate) fn cancelled_flag(&self) -> Arc<AtomicBool> {
75		self.cancelled.clone()
76	}
77}
78
79impl Debug for TimerHandle {
80	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81		f.debug_struct("TimerHandle").field("id", &self.id).field("cancelled", &self.is_cancelled()).finish()
82	}
83}
84
85/// Counter for generating unique timer IDs.
86static TIMER_ID_COUNTER: AtomicU64 = AtomicU64::new(0);
87
88pub(crate) fn next_timer_id() -> u64 {
89	TIMER_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
90}
91
92/// Drain expired timers, firing their callbacks synchronously.
93///
94/// Only meaningful on WASI where timers are queue-based. No-op on native
95/// (thread-based timers) and WASM (JavaScript event loop handles timers).
96#[cfg(reifydb_target = "wasi")]
97pub fn drain_expired_timers() {
98	wasi_drain();
99}
100
101/// Drain expired timers (no-op on this platform).
102#[cfg(not(reifydb_target = "wasi"))]
103pub fn drain_expired_timers() {}