Skip to main content

lifecycle/
tasks.rs

1//! Cooperative task stop with a monotonic deadline, using only the public task
2//! manager API (relationships, signals and sleep).
3//!
4//! Tasks receive [`Signal::Termination`] and must finish by themselves. Embassy
5//! cannot preempt or kill a task, so an unresponsive task is reported as
6//! [`Error::Timeout`] and keeps every resource it references: nothing is
7//! deallocated underneath it.
8
9use crate::Error;
10use alloc::vec::Vec;
11use core::time::Duration;
12use task::{Manager, Signal, TaskIdentifier};
13
14/// Interval between liveness checks while waiting for tasks to finish.
15pub const POLL_INTERVAL: Duration = Duration::from_millis(20);
16
17/// Ask every descendant of `root` to terminate, except the subtrees rooted at
18/// `keep` (runtime services stopped by the driver stage), and wait until they
19/// are gone or `budget` elapsed on the monotonic clock `now`.
20///
21/// Tasks are tracked once discovered, so children that outlive their parent
22/// (and therefore lose their place under `root`) are still waited for. Signals
23/// go to the most recently discovered (deepest) tasks first and are resent on
24/// every check; delivery is idempotent.
25pub async fn stop(
26    manager: &Manager,
27    root: TaskIdentifier,
28    keep: &[TaskIdentifier],
29    now: impl Fn() -> Duration,
30    budget: Duration,
31) -> Result<(), Error> {
32    let deadline = now().saturating_add(budget);
33    let mut tracked: Vec<TaskIdentifier> = Vec::new();
34    loop {
35        discover(manager, root, keep, &mut tracked).await;
36
37        let mut index = 0;
38        while index < tracked.len() {
39            if manager.get_parent(tracked[index]).await.is_ok() {
40                index += 1;
41            } else {
42                tracked.swap_remove(index);
43            }
44        }
45        if tracked.is_empty() {
46            return Ok(());
47        }
48
49        for &task in tracked.iter().rev() {
50            let _ = manager.send_signal(task, Signal::Termination).await;
51        }
52
53        if now() >= deadline {
54            return Err(Error::Timeout);
55        }
56        Manager::sleep(POLL_INTERVAL).await;
57    }
58}
59
60async fn discover(
61    manager: &Manager,
62    root: TaskIdentifier,
63    keep: &[TaskIdentifier],
64    tracked: &mut Vec<TaskIdentifier>,
65) {
66    let mut index = 0;
67    let mut parent = root;
68    loop {
69        if let Ok(children) = manager.get_children(parent).await {
70            for child in children {
71                if child != root && !keep.contains(&child) && !tracked.contains(&child) {
72                    tracked.push(child);
73                }
74            }
75        }
76        let Some(&next) = tracked.get(index) else {
77            return;
78        };
79        parent = next;
80        index += 1;
81    }
82}
83
84/// Whether the current task was asked to terminate or interrupt.
85///
86/// Signals are not consumed. Tasks without a signal wakeup must poll this at a
87/// bounded interval while blocked.
88pub async fn termination_requested(manager: &Manager, task: TaskIdentifier) -> bool {
89    matches!(
90        manager.peek_signal(task).await,
91        Ok(Some(Signal::Termination | Signal::Interrupt))
92    )
93}
94
95#[cfg(test)]
96#[allow(
97    clippy::disallowed_types,
98    reason = "host-only unit tests use std atomics"
99)]
100mod tests {
101    extern crate std;
102
103    use super::*;
104    use std::{
105        sync::atomic::{AtomicBool, Ordering},
106        time::Instant,
107    };
108
109    fn clock() -> impl Fn() -> Duration {
110        let start = Instant::now();
111        move || start.elapsed()
112    }
113
114    #[task::test]
115    async fn cooperative_tasks_stop_and_unresponsive_ones_time_out() {
116        static RELEASED: AtomicBool = AtomicBool::new(false);
117        static STOP_STUBBORN: AtomicBool = AtomicBool::new(false);
118        let manager = task::test_manager();
119        let root = manager.get_current_task_identifier().await;
120        let spawner = manager.get_spawner(root).await.unwrap();
121
122        let (service, service_identifier) = manager
123            .spawn(root, "Service", Some(spawner), async |_| {
124                while !STOP_STUBBORN.load(Ordering::Acquire) {
125                    Manager::sleep(Duration::from_millis(5)).await;
126                }
127            })
128            .await
129            .unwrap();
130
131        let (cooperative, _) = manager
132            .spawn(root, "Guest", Some(spawner), async move |task| {
133                let manager = task::test_manager();
134                // A nested child is stopped too.
135                let (child, _) = manager
136                    .spawn(task, "Guest child", Some(spawner), async |task| {
137                        let manager = task::test_manager();
138                        while !termination_requested(manager, task).await {
139                            Manager::sleep(Duration::from_millis(5)).await;
140                        }
141                    })
142                    .await
143                    .unwrap();
144                while !termination_requested(manager, task).await {
145                    Manager::sleep(Duration::from_millis(5)).await;
146                }
147                child.join().await;
148                // Cleanup hook: handles are released before the task ends.
149                RELEASED.store(true, Ordering::Release);
150            })
151            .await
152            .unwrap();
153
154        assert_eq!(
155            stop(
156                manager,
157                root,
158                &[service_identifier],
159                clock(),
160                Duration::from_secs(2)
161            )
162            .await,
163            Ok(())
164        );
165        cooperative.join().await;
166        assert!(RELEASED.load(Ordering::Acquire));
167        // The kept service never received a signal and still runs.
168        assert_eq!(manager.peek_signal(service_identifier).await, Ok(None));
169
170        let (stubborn, stubborn_identifier) = manager
171            .spawn(root, "Stubborn", Some(spawner), async |_| {
172                while !STOP_STUBBORN.load(Ordering::Acquire) {
173                    Manager::sleep(Duration::from_millis(5)).await;
174                }
175            })
176            .await
177            .unwrap();
178        let started = Instant::now();
179        assert_eq!(
180            stop(
181                manager,
182                root,
183                &[service_identifier],
184                clock(),
185                Duration::from_millis(100)
186            )
187            .await,
188            Err(Error::Timeout)
189        );
190        assert!(started.elapsed() >= Duration::from_millis(100));
191        // Timed-out tasks stay registered with their state intact.
192        assert!(manager.get_parent(stubborn_identifier).await.is_ok());
193        assert_eq!(
194            manager.peek_signal(stubborn_identifier).await,
195            Ok(Some(Signal::Termination))
196        );
197
198        STOP_STUBBORN.store(true, Ordering::Release);
199        stubborn.join().await;
200        service.join().await;
201    }
202}