lib.rs
cdk-rsx/crates/cdk-rsx-timers/src/lib.rs
1//! This library implements multiple and periodic timers on the Internet Computer.2//!3//! # Example4//!5//! ```rust,no_run6//! # use std::time::Duration;7//! # fn main() {8//! cdk_rsx_timers::set_timer(Duration::from_secs(1), async { cdk_rsx::println!("Hello from the future!") });9//! # }10//! ```11//!12//! # Details13//!14//! Timers internally use a bounded-wait self-call for error handling purposes. This is not guaranteed to15//! remain the case in the future, but means that if the system is under heavy load, timers may begin to16//! slow down by a lot as the self-calls begin to time out and the timers are rescheduled for the next global17//! timer tick. This also means that each executed timer incurs the cycle cost of a canister call.18//! A canister that cannot pay for that call keeps its due timers queued and tries again a minute later.19//!20//! <div class="warning">21//!22//! Timers are not persisted across canister upgrades.23//!24//! </div>2526#![warn(27 elided_lifetimes_in_paths,28 missing_debug_implementations,29 missing_docs,30 unsafe_op_in_unsafe_fn,31 clippy::undocumented_unsafe_blocks,32 clippy::missing_safety_doc33)]3435use cdk_rsx_executor::lifecycle::ReclaimableKey as _;36use std::{future::Future, time::Duration};3738use crate::state::{TASKS, TIMERS, Task, Timer};3940mod global_timer;41mod state;42mod timer_executor;4344// The private SDK self-call uses the same canonical method framing as controlled peers.45const TIMER_METHOD_ID: u64 = 0x52535801;46const TIMER_LIMITS: cdk_rsx_wire::Limits = cdk_rsx_wire::Limits {47 bytes: 32,48 allocation: 2048,49 nodes: 32,50 depth: 4,51};5253#[cfg(test)]54#[test]55fn timer_frames_fit_the_compiled_allowance() {56 let request = cdk_rsx_wire::encode_request(TIMER_METHOD_ID, &u64::MAX, TIMER_LIMITS).unwrap();57 assert_eq!(58 cdk_rsx_wire::decode_request(TIMER_METHOD_ID, &request, TIMER_LIMITS),59 Ok(u64::MAX)60 );61 let reply = cdk_rsx_wire::encode_response(TIMER_METHOD_ID, &(), TIMER_LIMITS).unwrap();62 assert_eq!(63 cdk_rsx_wire::decode_response(TIMER_METHOD_ID, &reply, TIMER_LIMITS),64 Ok(())65 );66}6768/// Type returned by the [`set_timer`] and [`set_timer_interval`] functions. Pass to [`clear_timer`] to remove the timer.69#[doc(inline)]70pub use crate::state::TaskId as TimerId;7172/// Sets `future` to be executed later, after `delay`. Panics if `delay` + [`time()`] is more than [`u64::MAX`] nanoseconds.73///74/// To cancel the timer before it executes, pass the returned `TimerId` to [`clear_timer`].75///76/// <div class="warning">77///78/// Timers are not persisted across canister upgrades.79///80/// </div>81///82/// # Examples83///84/// ```no_run85/// # use std::time::Duration;86/// cdk_rsx_timers::set_timer(Duration::from_secs(1), async {87/// cdk_rsx::println!("Hello from the future!");88/// });89/// ```90///91/// [`time()`]: https://docs.rs/ic-cdk/0.20.3/ic_cdk/api/fn.time.html92pub fn set_timer(delay: Duration, future: impl Future<Output = ()> + 'static) -> TimerId {93 let scheduled_time = get_scheduled_time(delay);94 let key = TASKS.with_borrow_mut(|tasks| tasks.insert(Task::Once(Box::pin(future))));95 TIMERS.with_borrow_mut(|timers| timers.push(Timer::new(key, scheduled_time)));96 state::rearm_ic0_timer();97 key98}99100/// Sets `func` to be executed every `interval`. Panics if `interval` + [`time()`] is more than [`u64::MAX`] nanoseconds.101///102/// To cancel the interval timer, pass the returned `TimerId` to [`clear_timer`].103///104/// This is a closure returning a future (`|| async {`), not an async closure (`async || {`). The two syntaxes105/// are interchangeable *if* the closure does not capture anything. If it does, you will need the former syntax,106/// and it is almost certain that either your captures must be Copy or you must use e.g. Rc to share them, because107/// you cannot capture by reference, and referencing an owned capture in a returned async block is not possible.108///109/// <div class="warning">110///111/// Interval timers should be *idempotent* with respect to the canister's state, as during heavy network load,112/// timeouts may result in duplicate execution.113///114/// </div>115///116/// <div class="warning">117///118/// Timers are not persisted across canister upgrades.119///120/// </div>121///122/// # Examples123///124/// ```no_run125/// # use std::time::Duration;126/// cdk_rsx_timers::set_timer_interval(Duration::from_secs(5), || async {127/// cdk_rsx::println!("This will run every five seconds forever!");128/// });129/// ```130///131/// [`time()`]: https://docs.rs/ic-cdk/0.20.3/ic_cdk/api/fn.time.html132pub fn set_timer_interval<Fut>(interval: Duration, func: impl FnMut() -> Fut + 'static) -> TimerId133where134 Fut: Future<Output = ()> + 'static,135{136 let mut func = func;137 let scheduled_time = get_scheduled_time(interval);138 let key = TASKS.with_borrow_mut(|tasks| {139 tasks.insert(Task::Repeated {140 func: Box::new(move || Box::pin(func())),141 interval,142 concurrent_calls: 0,143 })144 });145 TIMERS.with_borrow_mut(|timers| {146 timers.push(Timer::new(key, scheduled_time));147 });148 state::rearm_ic0_timer();149 key150}151152/// Sets `func` to be executed every `interval`. Panics if `interval` + [`time()`] is more than [`u64::MAX`] nanoseconds.153///154/// To cancel the interval timer, pass the returned `TimerId` to [`clear_timer`].155///156/// Unlike [`set_timer_interval`], this function takes an async closure (`async || {`). This is simpler to use157/// with captured variables, but also means that invocations cannot be run concurrently; if the interval is up158/// but the previous invocation is still running, the new invocation will be skipped.159///160/// <div class="warning">161///162/// Interval timers should be *idempotent* with respect to the canister's state, as during heavy network load,163/// timeouts may result in duplicate execution.164///165/// </div>166///167/// <div class="warning">168///169/// Timers are not persisted across canister upgrades.170///171/// </div>172///173/// # Examples174///175/// ```no_run176/// # use std::time::Duration;177/// cdk_rsx_timers::set_timer_interval_serial(Duration::from_secs(5), async || {178/// cdk_rsx::println!("This will run every five seconds forever!");179/// });180/// ```181///182/// [`time()`]: https://docs.rs/ic-cdk/0.20.3/ic_cdk/api/fn.time.html183pub fn set_timer_interval_serial(interval: Duration, func: impl AsyncFnMut() + 'static) -> TimerId {184 let scheduled_time = get_scheduled_time(interval);185 let key = TASKS.with_borrow_mut(|tasks| {186 tasks.insert(Task::RepeatedSerial {187 func: Box::new(func),188 interval,189 })190 });191 TIMERS.with_borrow_mut(|timers| {192 timers.push(Timer::new(key, scheduled_time));193 });194 state::rearm_ic0_timer();195 key196}197198/// Cancels an existing timer. Does nothing if the timer has already been canceled.199///200/// # Examples201///202/// ```no_run203/// # use std::time::Duration;204/// let timer_id = cdk_rsx_timers::set_timer(Duration::from_secs(60), async {205/// cdk_rsx::println!("This will never run, because we cancel it!");206/// });207/// cdk_rsx_timers::clear_timer(timer_id);208/// ```209pub fn clear_timer(id: TimerId) {210 let removed = TASKS.with_borrow_mut(|tasks| tasks.remove(id));211 // A future's captures may cancel other registrations. Never run them while212 // holding either the task table or the timer heap.213 drop(removed);214 state::update_ic0_timer();215}216217fn get_scheduled_time(delay: Duration) -> u64 {218 let delay_ns = u64::try_from(delay.as_nanos()).expect(219 "delay out of bounds (must be within `u64::MAX - cdk_rsx::api::time()` nanoseconds)",220 );221 cdk_rsx_sys::time().checked_add(delay_ns).expect(222 "delay out of bounds (must be within `u64::MAX - cdk_rsx::api::time()` nanoseconds)",223 )224}225226/// Release scheduled timer futures and all backing after physical calls drain.227/// The host must first establish that its durable work can safely be rebound.228#[doc(hidden)]229pub fn shutdown() -> Result<(), &'static str> {230 state::shutdown()231}232233/// Reconcile the IC wake without removing timer registrations when dispatch is held.234#[doc(hidden)]235pub fn dispatch_changed() {236 if cdk_rsx_executor::dispatch::is_paused() {237 state::disarm_ic0_timer();238 } else {239 state::rearm_ic0_timer();240 }241}242243/// Count already dispatched timer calls whose callbacks have yet to retire.244#[doc(hidden)]245pub fn pending_callbacks() -> u32 {246 // The global timer caps the count at 250.247 state::ALL_CALLS.get() as u32248}