embassy_supervisor/lib.rs
1// `no_std` for the shipped crate and the embedded build; under `cargo test` the
2// crate is built for the host, where the test harness and the unit tests need `std`.
3#![cfg_attr(not(test), no_std)]
4#![forbid(unsafe_code)]
5#![deny(missing_docs)]
6//! # embassy-supervisor — a task-lifecycle supervisor for [embassy](https://embassy.dev)
7//!
8//! Application- and HAL-agnostic primitives for orchestrating a set of embassy
9//! tasks: bringing them up in dependency order, tearing them down in reverse,
10//! scaling an elastic worker pool with load, placing nodes on interrupt-priority
11//! tiers or a second core, and starting/stopping/pausing/resuming individual
12//! tasks at runtime while keeping the dependency graph consistent. The supervisor
13//! orchestrates task *lifecycle* and leaves the rest — allocation, HAL, power,
14//! what the tasks do — to the application.
15//!
16//! ## The model
17//!
18//! * The graph is declared once with the [`supervisor_graph!`] macro: each
19//! managed task becomes a [`TaskNode`] `static`, and the macro bundles the node
20//! slots, dependency table, and a topological order computed **at compile time**
21//! into a single [`Graph`] (`GRAPH`). The whole graph is validated at compile
22//! time — a dependency cycle, an unknown or duplicate dependency, a duplicate
23//! name, or bad pool bounds are compile errors.
24//! * [`Supervisor::new`] takes `&GRAPH` (no work, no failure) and uses the order
25//! to bring tasks up in dependency order ([`Supervisor::start`]) and tear them
26//! down in reverse ([`Supervisor::teardown`]).
27//! * `executor NAME;` items declare runtime-filled [`SpawnerSlot`]s, and
28//! `executor: NAME` on a node (or a whole pool) routes its spawn through one —
29//! an interrupt-priority tier or the second core. Bring-up *awaits* the slot
30//! (bounded), so an executor that comes up late — or on another core — is a
31//! rendezvous, not a race.
32//! * Each managed task names its worker with either `task:` (preferred) — a
33//! **plain `async fn`** that the macro wraps in a generated
34//! `#[embassy_executor::task]` shell (one concrete shell per declaration, so a
35//! *generic* worker is fine) — or `spawn:`, naming a hand-written
36//! `#[embassy_executor::task]` directly. A `task:` pool emits one shell sized to
37//! its members; `pool_size: N` sizes a single node's shell.
38//! * `resources: [NAME: Type, ..]` on a `task:` node threads **owned resources
39//! from `main`** into the worker through macro-emitted [`ResourceSlot`]s —
40//! compile-time exclusive ownership (the `Peripherals` field is consumed, no
41//! `steal()` inside the task), fail-closed provisioning (an unprovided slot
42//! fails `start` with `SpawnError::Busy`), and restore-on-exit so a respawn
43//! re-takes the *same instance*. Per-entry kind markers refine that
44//! default: `consume` hands the worker the value **by value** with no
45//! restore (drop-at-teardown drivers; rebuilt-per-cycle resources — a
46//! respawn fail-closes until the app re-`provide()`s); `shared` is a
47//! fan-out slot for a `Copy` handle (the glue copies via
48//! [`ResourceSlot::get`], the slot stays filled — any number of nodes and
49//! whole pools may declare the same name); and `local` swaps in a
50//! graph-site slot without the `T: Send` bound (`!Send` driver handles,
51//! single-core contract). See the macro docs for the markers' fine print.
52//! * The pre-spawn waits are per-node tunable (`slot_timeout:` /
53//! [`TaskNode::with_slot_timeout`]), which makes **provider nodes** work: a
54//! first-in-topo node whose worker *builds* resources at runtime and
55//! `provide()`s them into other nodes' slots (the graph-native `hw_init`);
56//! consumers size their timeout to the build and the gate wait becomes a
57//! rendezvous.
58//! * Two flags span every lifecycle operation: **disabled** (stopped until an
59//! explicit `Activate` — declared `disabled` in the graph or control-stopped;
60//! see [`TaskNode::set_disabled`]) and **detached** (self-managed: after
61//! [`TaskNode::set_detached`] no supervisor operation touches the node).
62//! * Each node carries a `TaskHandle` of per-node atomic flags and
63//! single-consumer `Signal`s. Every node is single-instance — no counts, no
64//! fan-out. See [`TaskHandle`].
65//!
66//! ## Three lifecycles, distinguished by [`Mode`]
67//!
68//! * [`Mode::Terminate`] — the task exits its loop on shutdown and is respawned
69//! on the next bring-up. Stateless services (a network listener, a logger).
70//! * [`Mode::Pause`] — the task acks the shutdown then parks on
71//! `wait_resume()`; it is resumed in place, never respawned. Tasks that
72//! retain a resource across the pause (an open peripheral handle, a socket).
73//! * [`Mode::OnDemand`] — like `Terminate`, but not started at boot and not
74//! auto-respawned; the supervisor brings it up and down at runtime to scale
75//! an elastic worker pool ([`ElasticPool`]) with load.
76//!
77//! ## Writing a supervised task
78//!
79//! A supervised worker's first parameter is its node. With `task:` you write a
80//! plain `async fn` and the macro stamps the `#[embassy_executor::task]` shell
81//! (and, with `resources:`, hands it `&mut` resource handles after the node, in
82//! declared order); with `spawn:` you write the `#[embassy_executor::task]`
83//! yourself. Either way the macro's glue passes the node, and extra arguments come
84//! from the partial-call spawn form. Four rules cover the task side of the protocol:
85//!
86//! 1. select long-lived work against [`TaskNode::wait_shutdown`] — that's how a
87//! stop reaches you;
88//! 2. ack exactly once per stop with [`TaskNode::ack_dropped`]: on exit
89//! (`Terminate`/`OnDemand`), or on each pause (`Pause`) *before* parking on
90//! [`TaskNode::wait_resume`];
91//! 3. an autonomous exit acks too, so the supervisor sees the node as down;
92//! 4. resources follow the mode: a `Terminate` task re-acquires everything on
93//! respawn (drop-on-exit is the cleanup), a `Pause` task keeps what it holds
94//! across the park.
95//!
96//! Pool workers additionally report load with [`TaskNode::mark_busy`] /
97//! [`TaskNode::mark_idle`] (a real transition fires the scale signal itself), and
98//! a self-managed daemon or run-once job opts out of supervision with
99//! [`TaskNode::set_detached`]. The README's *Writing supervised tasks* section has
100//! per-mode skeletons.
101//!
102//! ## What the supervisor does *not* do
103//!
104//! * It does not model any power-state transition (sleep/wake): it reacts to
105//! "teardown" and "bring-up" requests; the application drives them.
106//! * It does not allocate, and does no work at construction: the topological
107//! sort runs at compile time (see the `supervisor_graph!` macro).
108//! * It does not observe task internals. Tasks self-report their drop state via
109//! `ack_dropped()`; a task that fails to ack within a timeout panics the
110//! supervisor with the offending node's name.
111//!
112//! ## Cargo features
113//!
114//! * `control` *(default)* — the runtime control plane: [`ControlOp`],
115//! [`request_control`], [`Supervisor::apply_control`].
116//! * `pool` *(default)* — elastic worker pools: [`ElasticPool`],
117//! [`Supervisor::run_pools`], and the `pools` field of [`Graph`].
118//! * `defmt` — route the supervisor's logs through `defmt`; without it the log
119//! macros are no-ops.
120//! * `trace` family (all opt-in) — `trace`: the [`trace`] recorders consuming
121//! embassy-executor's `_embassy_trace_*` hooks; `trace-hooks`:
122//! `supervisor_graph!` also *defines* the hook symbols; `metadata-names`: node
123//! names stamped into task Metadata for external consumers (rtos-trace/
124//! SystemView) — independent of `trace`, so it needs no hook symbols and pairs
125//! with embassy's own `rtos-trace`; `trace-names`: shorthand for `trace` +
126//! `metadata-names`; `trace-nested`: preemption-exact accounting (a nested
127//! higher-tier poll credits its time back to the window it interrupted).
128//!
129//! Build with `default-features = false` for a minimal core that only does
130//! dependency-ordered bring-up/teardown (drops the control plane and pools,
131//! trimming flash and a couple of statics).
132//!
133//! ## Example
134//!
135//! [`supervisor_graph!`] declares the whole graph once — it generates the node
136//! `static`s and a single [`Graph`] value `GRAPH` bundling the node slots, dep
137//! table, and compile-time topological order (a dependency cycle is a compile
138//! error), which [`Supervisor::new`] consumes.
139//!
140//! ```ignore
141//! use embassy_executor::Spawner;
142//! use embassy_supervisor::{supervisor_graph, Supervisor, wait_control};
143//!
144//! // `app` depends on `net`; `task:` names a plain async worker fn the macro wraps
145//! // in its `#[embassy_executor::task]` shell (`spawn:` takes one you wrote yourself).
146//! supervisor_graph! {
147//! node NET = Terminate, deps: [], task: net_task;
148//! node APP = Terminate, deps: [NET], task: app_task;
149//! }
150//!
151//! #[embassy_executor::task]
152//! async fn supervisor_task(spawner: Spawner) {
153//! let sup = Supervisor::new(&GRAPH);
154//! sup.start(spawner).await.expect("initial spawn"); // brings up `net`, then `app`
155//! loop {
156//! // Apply runtime start/stop/pause/resume requests in dependency order.
157//! let cmd = wait_control().await;
158//! sup.apply_control(cmd, spawner).await;
159//! }
160//! // With the `pool` feature you'd instead drive scaling and control together:
161//! // `select(sup.run_pools(spawner), wait_control())` (see the `firmware` crate).
162//! }
163//! ```
164//!
165//! The `firmware` crate in the [repository](https://github.com/cedrivard/embassy-supervisor)
166//! is a complete working example (USB-net, an HTTP control plane, an elastic pool,
167//! and OTA).
168
169#[macro_use]
170mod fmt;
171
172use core::cell::Cell;
173use core::sync::atomic::Ordering;
174
175use embassy_executor::{SendSpawner, SpawnError, Spawner};
176use embassy_futures::select::{Either, select};
177use embassy_sync::blocking_mutex::Mutex as BlockingMutex;
178use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
179#[cfg(feature = "control")]
180use embassy_sync::channel::Channel;
181use embassy_sync::signal::Signal;
182use embassy_time::{Timer, with_timeout};
183use portable_atomic::AtomicBool;
184#[cfg(feature = "trace")]
185use portable_atomic::AtomicU32;
186
187// ─── Scale-request signal (task → supervisor) ──────────────────────────────
188//
189// Elastic pool workers fire this when their busy/idle status changes; the
190// supervisor's `run_pools` loop awaits it and re-runs the pool policies
191// (`ElasticPool`). Single-consumer `Signal`: many tasks may `signal()`, only the
192// supervisor `wait()`s. This is the *only* path by which task status reaches the
193// supervisor — it never polls.
194#[cfg(feature = "pool")]
195static SCALE_REQ: Signal<CriticalSectionRawMutex, ()> = Signal::new();
196
197/// Fire the scale-request signal. Called by a task on a busy/idle transition.
198/// A no-op when the `pool` feature is disabled (no pools to re-evaluate).
199pub fn request_scale() {
200 #[cfg(feature = "pool")]
201 SCALE_REQ.signal(());
202}
203
204/// Await the next scale request. The supervisor's driver loop selects this
205/// against its other wake sources and runs the scaling policy on each wake.
206#[cfg(feature = "pool")]
207pub async fn wait_scale() {
208 SCALE_REQ.wait().await;
209}
210
211// ─── Runtime control commands (app → supervisor) ───────────────────────────
212//
213// An application's control surface (e.g. a network endpoint) usually can't drive
214// the supervisor directly: the `Supervisor` and the `Spawner` live on the
215// supervisor task's stack, not in a `static`. So control is decoupled via this
216// channel — the caller `request_control()`s a (node, op) pair and returns
217// immediately; the supervisor's driver loop `wait_control()`s it and runs the
218// dependency-honoring `apply_control`. A `Channel` (not a `Signal`) so
219// back-to-back requests aren't coalesced; capacity 4 is ample for hand-driven
220// control and a full channel simply drops the surplus (`try_send`).
221
222/// Which way to drive a node. Higher-level verbs fold onto these two:
223/// `start`/`resume` → `Activate`, `stop`/`pause` → `Deactivate`. The concrete
224/// mechanism (respawn vs resume vs leave-to-pool) is then chosen per node `Mode`
225/// by the supervisor when it applies the command ([`Supervisor::apply_control`]).
226#[cfg(feature = "control")]
227#[derive(Clone, Copy, PartialEq, Eq, Debug)]
228pub enum ControlOp {
229 /// Bring the node up (start a stopped `Terminate` node, resume a `Pause` node).
230 Activate,
231 /// Take the node down (and its dependents, per the graph).
232 Deactivate,
233}
234
235/// A runtime control request: drive `node` (and, per the dependency graph and
236/// pool membership, the nodes it implies) in the `op` direction.
237#[cfg(feature = "control")]
238#[derive(Clone, Copy, Debug)]
239pub struct ControlCommand {
240 /// The node to drive.
241 pub node: &'static TaskNode,
242 /// The direction to drive it.
243 pub op: ControlOp,
244}
245
246/// App → supervisor control mailbox. `&'static TaskNode` is `Copy + Sync`, so
247/// the target rides the channel directly — no name lookup needed supervisor-side.
248#[cfg(feature = "control")]
249static CONTROL_REQ: Channel<CriticalSectionRawMutex, ControlCommand, 4> = Channel::new();
250
251/// Enqueue a control request. Non-blocking; drops if the mailbox is full (4
252/// outstanding), which is harmless for low-frequency manual control. Called by
253/// the application's control surface.
254#[cfg(feature = "control")]
255pub fn request_control(node: &'static TaskNode, op: ControlOp) {
256 let _ = CONTROL_REQ.try_send(ControlCommand { node, op });
257}
258
259/// Await the next control request. Selected by the supervisor's driver loop
260/// against pool scaling and any other application wake sources.
261#[cfg(feature = "control")]
262pub async fn wait_control() -> ControlCommand {
263 CONTROL_REQ.receive().await
264}
265
266/// Per-node timeout for `wait_dropped`. A task that doesn't ack within this
267/// window is a bug (e.g. a missing `ack_dropped()` call) and panics the
268/// supervisor with the offending node's name. 2 s comfortably exceeds a typical
269/// task's poll period and peripheral settle time.
270const SHUTDOWN_ACK_TIMEOUT_MS: u64 = 2_000;
271
272/// How long the supervisor's bring-up waits for a node's `executor:`
273/// [`SpawnerSlot`] to be filled before failing the spawn with
274/// [`SpawnError::Busy`]. A genuine cross-core rendezvous resolves in microseconds;
275/// a slot empty this long is a misconfiguration (the app never registered that
276/// executor's spawner). Bounded, so a misconfigured graph fails loudly instead of
277/// hanging bring-up forever.
278const SLOT_READY_TIMEOUT: embassy_time::Duration = embassy_time::Duration::from_millis(100);
279
280// ─── Mode ────────────────────────────────────────────────────────────────
281
282/// Lifecycle policy for a managed task: what the task does on shutdown and what
283/// the supervisor does to bring it back.
284#[derive(Clone, Copy, PartialEq, Eq, Debug)]
285pub enum Mode {
286 /// Task exits its loop on shutdown. The supervisor respawns it via the
287 /// node's `spawn` fn from `respawn_terminate`.
288 Terminate,
289 /// Task acks shutdown and parks on `wait_resume()`. The supervisor resumes
290 /// it from `resume_pausable`; the task is never respawned, so it keeps any
291 /// resource it holds (a peripheral handle, a socket) across the pause.
292 Pause,
293 /// Like `Terminate` (exits on shutdown), but **not** started at boot and
294 /// **not** auto-respawned. The supervisor brings it up and down at runtime
295 /// via `start_node` / `stop_node` in response to load — see [`ElasticPool`].
296 /// `start()` skips it; `respawn_terminate()` leaves it down (it
297 /// re-grows under demand); `teardown()` only acts on it while it is running.
298 OnDemand,
299}
300
301impl Mode {
302 /// Stable lower-case wire name, used both for serialization (e.g. a JSON
303 /// task-state view) and for `defmt` logging — the single source of these
304 /// strings.
305 pub fn as_str(&self) -> &'static str {
306 match self {
307 Mode::Terminate => "terminate",
308 Mode::Pause => "pause",
309 Mode::OnDemand => "ondemand",
310 }
311 }
312}
313
314#[cfg(feature = "defmt")]
315impl defmt::Format for Mode {
316 fn format(&self, f: defmt::Formatter) {
317 defmt::write!(f, "{}", self.as_str());
318 }
319}
320
321// ─── TaskHandle ──────────────────────────────────────────────────────────
322
323/// Coordination state for one task. Embedded inside [`TaskNode`].
324///
325/// Every node is single-instance, so each field is a per-node atomic flag or a
326/// single-consumer signal — no counts, no fan-out. Written by one side (task or
327/// supervisor) and read by the other:
328/// * `shutdown` / `shutdown_wake` — supervisor requests exit; the task parks
329/// on the signal and reads the flag.
330/// * `dropped` / `dropped_wake` — the task acks its exit; the supervisor
331/// parks on the signal (with a timeout) and reads the flag.
332/// * `resume_wake` — supervisor resumes a parked Pause-mode task.
333/// * `running` — supervisor's record that the node is spawned; `busy` — the
334/// task's active/idle status. Both read by the elastic scaling policy.
335/// * `disabled` — the node has been manually deactivated; see below.
336pub struct TaskHandle {
337 /// Set true by the supervisor when shutdown is requested.
338 /// Cleared by `reset()` before the next spawn.
339 shutdown: AtomicBool,
340 /// Wake source for `wait_shutdown()`. Fired by `signal_shutdown()`.
341 shutdown_wake: Signal<CriticalSectionRawMutex, ()>,
342 /// Set true by the instance when it acks the shutdown (a bool, not a count,
343 /// since every node is single-instance). Cleared by `reset()`.
344 dropped: AtomicBool,
345 /// Wake source for `wait_dropped()`. Fired by `ack_dropped()`.
346 dropped_wake: Signal<CriticalSectionRawMutex, ()>,
347 /// True while the supervisor has the node spawned and it hasn't exited.
348 /// Always-on nodes are set true by `start()`; `OnDemand` nodes are set
349 /// true/false by `start_node()` / `stop_node()`. `teardown()` only acts on
350 /// `running` nodes, so a down `OnDemand` node doesn't stall it.
351 running: AtomicBool,
352 /// True while the task is actively serving (its active/idle status). Set by
353 /// `mark_busy()` / `mark_idle()`; read by the scaling policy.
354 busy: AtomicBool,
355 /// Wake source for `wait_resume()` on Pause-mode tasks. Fired by
356 /// `signal_resume()`.
357 resume_wake: Signal<CriticalSectionRawMutex, ()>,
358 /// True while the node has been manually deactivated (stopped/paused) via the
359 /// runtime control interface (`Supervisor::deactivate`). Unlike the other
360 /// flags this one is **lifecycle-spanning**: it is *not* cleared by
361 /// `reset()`, so a manual stop "sticks" — the automatic bring-up paths
362 /// (`start`, `respawn_terminate`, `resume_pausable`, and the elastic pool's
363 /// grow) skip a node while it is set. Cleared only by `Supervisor::activate`.
364 /// Because it lives in a `static`, it also survives a power-state transition
365 /// that retains RAM (e.g. a warm-resume from deep sleep).
366 disabled: AtomicBool,
367 /// Self-managed: while set, the supervisor never drives this node — teardown,
368 /// deactivate/activate, `stop_node`, respawn, and pause-resume all skip it. Not
369 /// cleared by `reset()`. Full rationale on [`TaskNode::set_detached`].
370 detached: AtomicBool,
371 /// The executor task id currently running this node (`TaskRef::id()`, captured
372 /// from the `SpawnToken` by the macro's spawn glue). `0` = unknown (not yet
373 /// spawned, or a parked/closure-spawned node that never registered). Overwritten
374 /// on every (re)spawn, so — unlike an external tracker — it stays correct across
375 /// respawns without any unlinking.
376 #[cfg(feature = "trace")]
377 task_id: AtomicU32,
378 /// Accumulated executor-poll time for this node, in embassy-time ticks,
379 /// wrapping. Consumers sample twice and `wrapping_sub` to get a rate; the
380 /// crate does no windowing.
381 #[cfg(feature = "trace")]
382 exec_ticks: AtomicU32,
383 /// Number of executor polls of this node, wrapping.
384 #[cfg(feature = "trace")]
385 polls: AtomicU32,
386 /// Longest single poll ever observed, in ticks — the "never yields" watermark.
387 /// A large value names the node that hogged the executor even after the fact,
388 /// which a live check cannot do from the blocked executor itself.
389 #[cfg(feature = "trace")]
390 max_poll_ticks: AtomicU32,
391}
392
393impl TaskHandle {
394 const fn new(disabled_at_boot: bool) -> Self {
395 Self {
396 shutdown: AtomicBool::new(false),
397 shutdown_wake: Signal::new(),
398 dropped: AtomicBool::new(false),
399 dropped_wake: Signal::new(),
400 running: AtomicBool::new(false),
401 busy: AtomicBool::new(false),
402 resume_wake: Signal::new(),
403 disabled: AtomicBool::new(disabled_at_boot),
404 detached: AtomicBool::new(false),
405 #[cfg(feature = "trace")]
406 task_id: AtomicU32::new(0),
407 #[cfg(feature = "trace")]
408 exec_ticks: AtomicU32::new(0),
409 #[cfg(feature = "trace")]
410 polls: AtomicU32::new(0),
411 #[cfg(feature = "trace")]
412 max_poll_ticks: AtomicU32::new(0),
413 }
414 }
415}
416
417// ─── Executor spawner slots ──────────────────────────────────────────────
418
419/// A runtime-filled slot holding the [`SendSpawner`] of an executor other than
420/// the one the supervisor runs on — an `InterruptExecutor` tier, the second
421/// core's executor, any foreign thread executor (via `Spawner::make_send()`).
422///
423/// Declared by the `executor NAME;` item of [`supervisor_graph!`]; nodes carrying
424/// `executor: NAME` are spawned through the slot instead of the supervisor's own
425/// `Spawner`. The application fills it once at startup — before, or concurrently
426/// with, [`Supervisor::start`] (e.g. from the second core's bring-up):
427///
428/// ```ignore
429/// static EXECUTOR_HIGH: InterruptExecutor = InterruptExecutor::new();
430/// HIGH.set(EXECUTOR_HIGH.start(interrupt::SWI_IRQ_0));
431/// sup.start(spawner).await?; // nodes declared `executor: HIGH` spawn on that tier
432/// ```
433///
434/// The supervisor's bring-up (`start` / `start_node` / `respawn_terminate`) awaits
435/// [`ready`](Self::ready) for a node's slot before spawning it, so a tier filled
436/// late — or from another core — is handled without a race; a slot still empty after
437/// the supervisor's bounded wait fails the spawn with [`SpawnError::Busy`] rather
438/// than silently dropping the task. Spawned futures must be `Send` (a non-`Send`
439/// `executor:` task is a compile error at the glue).
440pub struct SpawnerSlot {
441 slot: BlockingMutex<CriticalSectionRawMutex, Cell<Option<SendSpawner>>>,
442 /// Wakes a `ready()` waiter when `set` fills the slot (cross-core safe:
443 /// `Signal` is critical-section based and latches).
444 filled: Signal<CriticalSectionRawMutex, ()>,
445}
446
447impl SpawnerSlot {
448 /// An empty slot (`const` — it lives in a `static` the macro emits).
449 pub const fn new() -> Self {
450 Self {
451 slot: BlockingMutex::new(Cell::new(None)),
452 filled: Signal::new(),
453 }
454 }
455
456 /// Fill the slot (last set wins) and wake a [`ready`](Self::ready) waiter.
457 /// Call before [`Supervisor::start`] — or from the other core's bring-up,
458 /// with the supervisor awaiting `ready()`.
459 pub fn set(&self, spawner: SendSpawner) {
460 self.slot.lock(|c| c.set(Some(spawner)));
461 self.filled.signal(());
462 }
463
464 /// The registered spawner, or `None` while unfilled.
465 pub fn get(&self) -> Option<SendSpawner> {
466 self.slot.lock(Cell::get)
467 }
468
469 /// Await the slot and return the spawner. The rendezvous primitive: the
470 /// supervisor's bring-up awaits this for a node's `executor:` slot before
471 /// spawning it (bounded, see [`Supervisor::start`]), so a tier filled late — or
472 /// from another core — is handled without a race. Returns immediately once the
473 /// slot is filled, so any number of *late* callers are fine (an application can
474 /// gate work on the executor being up). While the slot is still empty, at most
475 /// one task should be parked here: the underlying `Signal` holds a single waker,
476 /// so a second pre-fill waiter would displace the first.
477 pub async fn ready(&self) -> SendSpawner {
478 loop {
479 if let Some(sp) = self.get() {
480 return sp;
481 }
482 // `Signal` latches: a `set()` racing between the check above and
483 // this wait still wakes us.
484 self.filled.wait().await;
485 }
486 }
487}
488
489impl Default for SpawnerSlot {
490 fn default() -> Self {
491 Self::new()
492 }
493}
494
495// ─── ResourceSlot ────────────────────────────────────────────────────────
496
497/// Type-erased readiness view of a [`ResourceSlot`], for the supervisor's
498/// bring-up wait.
499///
500/// A `TaskNode` can gate on any number of slots of *different* `T`s, so the node
501/// stores `&'static [&'static dyn ResourceGate]` (object-safe: no `T` in the
502/// signatures). Same shape as embassy's `dyn` driver registries — see
503/// <https://doc.rust-lang.org/reference/items/traits.html#object-safety>.
504/// The supervisor only needs "is it filled?" plus the signal to park on; taking
505/// the value stays in the generated spawn glue, where the concrete `T` is known.
506pub trait ResourceGate: Sync {
507 /// Non-consuming "is the slot currently filled" check.
508 fn is_filled(&self) -> bool;
509 /// The latching [`Signal`] fired by `provide`/`restore`, for the supervisor's
510 /// bounded pre-spawn wait (see [`Supervisor::start`]).
511 fn filled_signal(&self) -> &Signal<CriticalSectionRawMutex, ()>;
512}
513
514/// A one-value handoff cell threading an owned resource from `main` into a
515/// supervised task — the safe replacement for `Peripherals::steal()` inside
516/// the task body.
517///
518/// Declared (as a `pub static`) by [`supervisor_graph!`] for each entry in a
519/// node's `resources:` clause. The protocol:
520///
521/// 1. `main` splits `Peripherals` and **moves** the resource in with
522/// [`provide`](Self::provide). This is where the compile-time guarantee
523/// lives: the singleton field is *consumed*, so no second owner — and no
524/// `unsafe` steal — can exist.
525/// 2. The generated spawn glue [`take`](Self::take)s it just before spawning
526/// the node. An empty slot fails the spawn with `SpawnError::Busy` — a
527/// fail-closed error out of [`Supervisor::start`], not a panic inside the
528/// task (compare `static_cell::StaticCell`, which panics on misuse).
529/// 3. The generated task shell hands the worker `&mut T` and
530/// [`restore`](Self::restore)s the value after the worker returns, so a
531/// `Terminate` respawn re-takes the *same instance* instead of stealing a
532/// fresh one. (A `Pause` worker never returns — it parks — so it simply
533/// retains the resource, exactly like a hand-written parked task.)
534///
535/// Same primitives as [`SpawnerSlot`]: a critical-section
536/// [`BlockingMutex`]`<`[`Cell`]`<Option<T>>>` for the value (`Sync` for
537/// `T: Send`, provided by embassy-sync — no `unsafe` here) plus a latching
538/// [`Signal`] so the supervisor can await late provisioning (bounded; see
539/// [`Supervisor::start`]).
540pub struct ResourceSlot<T> {
541 slot: BlockingMutex<CriticalSectionRawMutex, Cell<Option<T>>>,
542 /// Wakes the supervisor's pre-spawn wait when `provide`/`restore` fills the
543 /// slot (latching, so a fill racing the check-then-wait still wakes it).
544 filled: Signal<CriticalSectionRawMutex, ()>,
545}
546
547impl<T> ResourceSlot<T> {
548 /// An empty slot (`const` — it lives in a `static` the macro emits).
549 pub const fn new() -> Self {
550 Self {
551 slot: BlockingMutex::new(Cell::new(None)),
552 filled: Signal::new(),
553 }
554 }
555
556 /// Move the resource in (from `main`'s `Peripherals` split) and wake the
557 /// supervisor's pre-spawn wait. Call before [`Supervisor::start`]; a slot
558 /// still empty after the supervisor's bounded wait fails that node's spawn
559 /// with `SpawnError::Busy`. Filling an occupied slot replaces (drops) the
560 /// old value — don't: one resource, one slot, moved exactly once.
561 pub fn provide(&self, value: T) {
562 self.slot.lock(|c| c.set(Some(value)));
563 self.filled.signal(());
564 }
565
566 /// Take the resource out, leaving the slot empty. Called by the generated
567 /// spawn glue just before the spawn; `None` means "not provided yet" or
568 /// "currently held by a live task instance".
569 pub fn take(&self) -> Option<T> {
570 self.slot.lock(Cell::take)
571 }
572
573 /// Copy the resource out **without emptying the slot** — the `shared`
574 /// resource kind's read: any number of consumers (several nodes, a whole
575 /// pool) get the same `Copy` handle, and the slot stays filled for the
576 /// next one. Only for `T: Copy` (a `Stack`-like handle, a `&'static`
577 /// registry ref); an owned singleton uses [`take`](Self::take).
578 pub fn get(&self) -> Option<T>
579 where
580 T: Copy,
581 {
582 // Same peek shape as `is_filled`: `Cell` has no `&T` access, so
583 // take-copy-put-back under one critical section.
584 self.slot.lock(|c| {
585 let v = c.take();
586 c.set(v);
587 v
588 })
589 }
590
591 /// Put the resource back for the next spawn. Called by the generated task
592 /// shell after the worker returns (i.e. after its clean shutdown ack), so a
593 /// respawn re-takes the same instance.
594 pub fn restore(&self, value: T) {
595 self.provide(value);
596 }
597}
598
599// `T: Send` (not just any `T`): the gate is reachable from the supervisor task,
600// which may run on a different core than the provider — the same bound the
601// inner `BlockingMutex` requires for `Sync`, restated here so the `dyn` upcast
602// can't outrun it.
603impl<T: Send> ResourceGate for ResourceSlot<T> {
604 fn is_filled(&self) -> bool {
605 // Peek without consuming: `Cell` has no `&T` access (no `T: Copy`
606 // here), so take-and-put-back under the same critical section.
607 self.slot.lock(|c| {
608 let v = c.take();
609 let filled = v.is_some();
610 c.set(v);
611 filled
612 })
613 }
614
615 fn filled_signal(&self) -> &Signal<CriticalSectionRawMutex, ()> {
616 &self.filled
617 }
618}
619
620impl<T> Default for ResourceSlot<T> {
621 fn default() -> Self {
622 Self::new()
623 }
624}
625
626// ─── TaskNode ────────────────────────────────────────────────────────────
627
628/// A node in the supervisor's task graph.
629///
630/// Designed to live in `static` memory: every field is `Sync`, all constructors
631/// are `const`. Declared by [`supervisor_graph!`], which emits one per managed
632/// task along with the [`Graph`] (`GRAPH`) that [`Supervisor::new`] consumes.
633pub struct TaskNode {
634 /// Human-readable name. Used in defmt logs and panic messages.
635 pub name: &'static str,
636 /// Lifecycle policy. See [`Mode`].
637 pub mode: Mode,
638 /// App-provided spawn function (typically an inline closure at the node's
639 /// declaration). Called once at boot from `Supervisor::start`, again from
640 /// `respawn_terminate` for Terminate nodes, and at runtime from `start_node`
641 /// for `OnDemand` nodes. `None` for a **parked** node the application spawns
642 /// itself (e.g. a `Pause` sensor holding a peripheral handle): the supervisor
643 /// tracks its lifecycle but never spawns it.
644 pub spawn: Option<fn(Spawner) -> Result<(), SpawnError>>,
645 /// The executor [`SpawnerSlot`] this node spawns through (`executor: NAME` in
646 /// the graph), or `None` to spawn on the supervisor's own `Spawner`. When
647 /// `Some`, the supervisor awaits the slot's [`ready`](SpawnerSlot::ready)
648 /// (bounded by [`SLOT_READY_TIMEOUT`]) *before* invoking `spawn`, so the
649 /// generated glue's own non-blocking `SpawnerSlot::get` is already filled. Set
650 /// by the macro via [`with_executor`](Self::with_executor); `const`, zero-cost.
651 spawn_slot: Option<&'static SpawnerSlot>,
652 /// The [`ResourceSlot`]s this node's spawn takes from (`resources:` in the
653 /// graph), type-erased to their [`ResourceGate`] readiness view. The
654 /// supervisor awaits every gate being filled (bounded by
655 /// [`SLOT_READY_TIMEOUT`]) *before* invoking `spawn`, so (a) a `main` that
656 /// provides late is tolerated and (b) a respawn cannot race the previous
657 /// instance's shell restoring the value (the restore happens after the
658 /// worker's shutdown ack). Empty for nodes without `resources:`. Set by the
659 /// macro via [`with_resources`](Self::with_resources); `const`, zero-cost.
660 resource_gates: &'static [&'static dyn ResourceGate],
661 /// Bound on the pre-spawn waits for this node's `executor:` slot and
662 /// `resources:` gates. Defaults to [`SLOT_READY_TIMEOUT`] (100 ms — sized
663 /// for "main provided before start"); raise it (`slot_timeout:` in the
664 /// graph) for a node whose slots are filled by a **provider node** at
665 /// runtime — e.g. an async radio bring-up worth hundreds of milliseconds.
666 /// Set by the macro via [`with_slot_timeout`](Self::with_slot_timeout).
667 slot_timeout: embassy_time::Duration,
668 handle: TaskHandle,
669}
670
671impl TaskNode {
672 /// A single-instance node started at boot (`Terminate`/`Pause`) or on demand
673 /// (`Mode::OnDemand`). Every node is single-instance; an elastic service is
674 /// modelled as several `OnDemand` nodes of the same pooled task fn.
675 ///
676 /// A `TaskNode` carries only its own identity and behaviour; the graph's
677 /// dependency edges live in the compile-time index table that
678 /// [`supervisor_graph!`] emits and [`Supervisor::new`] consumes.
679 /// `disabled_at_boot` seeds the node's disabled flag so a control-started node
680 /// (e.g. an OTA task) can be declared down and started later via a control op.
681 /// `spawn` is `None` for a parked node the application spawns itself.
682 pub const fn new(
683 name: &'static str,
684 mode: Mode,
685 spawn: Option<fn(Spawner) -> Result<(), SpawnError>>,
686 disabled_at_boot: bool,
687 ) -> Self {
688 Self {
689 name,
690 mode,
691 spawn,
692 spawn_slot: None,
693 resource_gates: &[],
694 slot_timeout: SLOT_READY_TIMEOUT,
695 handle: TaskHandle::new(disabled_at_boot),
696 }
697 }
698
699 /// Route this node's spawn through the given executor [`SpawnerSlot`] (the
700 /// `executor: NAME` graph annotation). The supervisor awaits the slot before
701 /// spawning the node, so a tier filled late — or from another core — is handled
702 /// without a race, and the generated glue's non-blocking `get` is already filled.
703 /// `const` and chainable in a `static` initializer; emitted by [`supervisor_graph!`].
704 pub const fn with_executor(mut self, slot: &'static SpawnerSlot) -> Self {
705 self.spawn_slot = Some(slot);
706 self
707 }
708
709 /// Declare the [`ResourceSlot`]s this node's spawn takes from (the
710 /// `resources:` graph clause). The supervisor awaits every gate being
711 /// filled before spawning the node, so the generated glue's non-blocking
712 /// `take()` finds the value. `const` and chainable in a `static`
713 /// initializer; emitted by [`supervisor_graph!`].
714 pub const fn with_resources(mut self, gates: &'static [&'static dyn ResourceGate]) -> Self {
715 self.resource_gates = gates;
716 self
717 }
718
719 /// Override the pre-spawn slot/gate wait bound for this node (the
720 /// `slot_timeout: <millis>` graph clause). The default
721 /// (`SLOT_READY_TIMEOUT`, 100 ms) assumes slots are provided *before*
722 /// `start()`; a node consuming a **provider node's** outputs must cover the
723 /// provider's async build time (the failure mode stays a loud
724 /// `SpawnError::Busy`, just later). `const` and chainable in a `static`
725 /// initializer; emitted by [`supervisor_graph!`].
726 pub const fn with_slot_timeout(mut self, timeout: embassy_time::Duration) -> Self {
727 self.slot_timeout = timeout;
728 self
729 }
730
731 // ── Task-side API ────────────────────────────────────────────────────
732 //
733 // Called from inside the `#[embassy_executor::task] async fn` body. The
734 // whole task-side protocol is four rules (the README's "Writing supervised
735 // tasks" section has per-mode skeletons):
736 // 1. select long-lived work against `wait_shutdown()`;
737 // 2. `ack_dropped()` exactly once per stop — on exit (Terminate/OnDemand)
738 // or on each pause (Pause), before parking on `wait_resume()`;
739 // 3. an autonomous exit acks too;
740 // 4. resources follow the mode: Terminate re-acquires on respawn, Pause
741 // retains across park.
742
743 /// True iff the supervisor has requested shutdown. Checked at the loop top
744 /// alongside `wait_shutdown()` in a `select`.
745 pub fn shutdown_requested(&self) -> bool {
746 self.handle.shutdown.load(Ordering::Acquire)
747 }
748
749 /// Park until shutdown is requested. Returns immediately if shutdown has
750 /// already been requested. Use this for single-instance tasks in a `select`
751 /// against the task's main work future.
752 pub async fn wait_shutdown(&self) {
753 // Fast path — already requested. (Important because the signal is
754 // edge-triggered: if `signal()` fired before we got here, the bare
755 // `wait()` below would block forever.)
756 if self.handle.shutdown.load(Ordering::Acquire) {
757 return;
758 }
759 self.handle.shutdown_wake.wait().await;
760 }
761
762 /// Mark this instance as having shut down: clears the running flag and acks
763 /// the teardown handshake (so the supervisor's `wait_dropped` completes).
764 /// Every instance must call this exactly once on exit (Terminate/OnDemand
765 /// mode) or on each pause (Pause mode). It also covers an **autonomous** exit
766 /// the supervisor didn't request — e.g. a pool worker backing off — so the
767 /// pool sees the instance as down and can re-grow it under later demand.
768 pub fn ack_dropped(&self) {
769 self.handle.running.store(false, Ordering::Release);
770 self.handle.dropped.store(true, Ordering::Release);
771 self.handle.dropped_wake.signal(());
772 }
773
774 /// Pause-mode only: park until the supervisor signals resume. Call *after*
775 /// [`ack_dropped`](Self::ack_dropped) — ack the pause, then park; held
776 /// resources stay owned across the park.
777 pub async fn wait_resume(&self) {
778 self.handle.resume_wake.wait().await;
779 }
780
781 /// Report that this task started serving a request (active). Fires the
782 /// scale-request signal on a real idle→busy transition so the scaling policy
783 /// can react (e.g. grow the pool); a redundant call doesn't re-signal.
784 pub fn mark_busy(&self) {
785 if !self.handle.busy.swap(true, Ordering::Release) {
786 request_scale();
787 }
788 }
789
790 /// Report that this task finished serving and is idle again. Fires the
791 /// scale-request signal on a real busy→idle transition so the scaling policy
792 /// can react (e.g. shrink the pool); a redundant call doesn't re-signal.
793 pub fn mark_idle(&self) {
794 if self.handle.busy.swap(false, Ordering::Release) {
795 request_scale();
796 }
797 }
798
799 /// True while this task is actively serving. Read by the scaling policy.
800 pub fn is_busy(&self) -> bool {
801 self.handle.busy.load(Ordering::Acquire)
802 }
803
804 /// True while the supervisor has this node spawned (and it hasn't exited).
805 /// Read by the scaling policy to count live instances, and by a task-state
806 /// view.
807 pub fn is_running(&self) -> bool {
808 self.handle.running.load(Ordering::Acquire)
809 }
810
811 /// True while the node is disabled: declared `disabled` in the graph
812 /// (stopped-at-boot, up on an explicit `Activate`), or manually deactivated
813 /// via the control interface and not yet re-activated. Read by a task-state
814 /// view and by the automatic bring-up paths (which skip a disabled node).
815 pub fn is_disabled(&self) -> bool {
816 self.handle.disabled.load(Ordering::Acquire)
817 }
818
819 /// Mark/clear this node as **detached**: a self-managing node the supervisor
820 /// brings up once (via [`start`](Supervisor::start)) and then stops managing
821 /// **entirely**. Every runtime lifecycle operation skips a detached node: full
822 /// [`teardown`](Supervisor::teardown), the control deactivate/activate cascades,
823 /// [`stop_node`](Supervisor::stop_node), [`respawn_terminate`](Supervisor::respawn_terminate),
824 /// and pause-resume. It keeps running (or, for a one-shot, stays exited) across a
825 /// teardown/wake cycle instead of being stopped, re-enabled, or re-spawned. Use it
826 /// for a task that must outlive the teardown it participates in — e.g. a sleep/power
827 /// coordinator that tears the graph down, sleeps, then wakes it — or a self-managed
828 /// one-shot whose `deps:` exist only for start-ordering. The node owns its own
829 /// shutdown; the supervisor will not drive it.
830 pub fn set_detached(&self, detached: bool) {
831 self.handle.detached.store(detached, Ordering::Release);
832 }
833
834 /// True while this node is [detached](Self::set_detached): self-managed, skipped by
835 /// every runtime lifecycle operation (teardown, deactivate/activate, `stop_node`,
836 /// respawn, pause-resume). Only the initial `start` brings it up.
837 pub fn is_detached(&self) -> bool {
838 self.handle.detached.load(Ordering::Acquire)
839 }
840
841 // ── Trace/observability API (features `trace`/`trace-names`) ───────────
842
843 /// Record the executor task id (`SpawnToken::id()` / `TaskRef::id()`) currently
844 /// backing this node, so the [`trace`] recorders can attribute executor polls to
845 /// it. Called automatically by the spawn glue `supervisor_graph!` generates;
846 /// call it manually only for a **parked** node (no `spawn:`) or a verbatim-closure
847 /// `spawn:`, where the macro cannot see the token. Overwrites on every (re)spawn.
848 #[cfg(feature = "trace")]
849 pub fn set_task_id(&self, id: u32) {
850 self.handle.task_id.store(id, Ordering::Release);
851 }
852
853 /// Register an externally-spawned token as this node's live task: records
854 /// the task id for the [`trace`] recorders and (feature `metadata-names`)
855 /// stamps the node name into the task Metadata. One call replaces the
856 /// manual [`set_task_id`](Self::set_task_id) dance wherever the macro can't
857 /// see the token — parked nodes and verbatim-closure `spawn:` forms:
858 ///
859 /// ```ignore
860 /// let t = environment_task(i2c_dev)?;
861 /// BME280.adopt(&t);
862 /// high_spawner.spawn(t);
863 /// ```
864 #[cfg(feature = "trace")]
865 pub fn adopt<S>(&self, token: &embassy_executor::SpawnToken<S>) {
866 self.set_task_id(token.id());
867 #[cfg(feature = "metadata-names")]
868 self.stamp_name(token);
869 }
870
871 /// Stamp this node's name into the task's embassy `Metadata` (feature
872 /// `metadata-names`), so external consumers — rtos-trace/SystemView, debuggers —
873 /// show the graph node name instead of an opaque task id. Unlike
874 /// [`adopt`](Self::adopt) this does **not** capture the task id or touch the
875 /// supervisor's [`trace`] recorders, so it needs neither the `trace` feature nor
876 /// the `_embassy_trace_*` hook symbols: it is the name-only spawn path emitted
877 /// when `metadata-names` is on but `trace` is off (pair it with embassy's
878 /// `rtos-trace`). Called automatically by the spawn glue; call it manually only
879 /// for a parked or verbatim-closure node the macro can't see.
880 ///
881 /// Requires `embassy-executor`'s `metadata-name` feature, which `metadata-names`
882 /// pulls in; without a registered name the task keeps embassy's default.
883 #[cfg(feature = "metadata-names")]
884 pub fn stamp_name<S>(&self, token: &embassy_executor::SpawnToken<S>) {
885 token.metadata().set_name(self.name);
886 }
887
888 /// The executor task id last recorded by [`set_task_id`](Self::set_task_id)
889 /// (`0` = never spawned / not registered).
890 #[cfg(feature = "trace")]
891 pub fn task_id(&self) -> u32 {
892 self.handle.task_id.load(Ordering::Acquire)
893 }
894
895 /// Accumulated executor-poll time of this node, in embassy-time ticks. Wrapping:
896 /// sample twice and `wrapping_sub` the readings to get a rate over a window.
897 #[cfg(feature = "trace")]
898 pub fn exec_ticks(&self) -> u32 {
899 self.handle.exec_ticks.load(Ordering::Relaxed)
900 }
901
902 /// Number of executor polls of this node (wrapping counter).
903 #[cfg(feature = "trace")]
904 pub fn poll_count(&self) -> u32 {
905 self.handle.polls.load(Ordering::Relaxed)
906 }
907
908 /// Longest single executor poll of this node ever observed, in ticks — the
909 /// "never yields" watermark. A poll is expected to be microseconds; a large
910 /// value names the node that hogged its executor, even after the fact.
911 #[cfg(feature = "trace")]
912 pub fn max_poll_ticks(&self) -> u32 {
913 self.handle.max_poll_ticks.load(Ordering::Relaxed)
914 }
915
916 // ── Supervisor-side API ──────────────────────────────────────────────
917 //
918 // Driven by the `Supervisor` struct. Kept `pub(crate)` so app code doesn't
919 // accidentally bypass the supervisor's orchestration.
920
921 pub(crate) fn signal_shutdown(&self) {
922 self.handle.shutdown.store(true, Ordering::Release);
923 self.handle.shutdown_wake.signal(());
924 }
925
926 pub(crate) fn signal_resume(&self) {
927 self.handle.resume_wake.signal(());
928 }
929
930 pub(crate) fn set_running(&self, running: bool) {
931 self.handle.running.store(running, Ordering::Release);
932 }
933
934 /// Set/clear the manual-deactivation flag. Set by `Supervisor::deactivate`,
935 /// cleared by `Supervisor::activate`. Deliberately *not* touched by
936 /// `reset()`, so a manual stop survives respawn cycles and RAM-retaining
937 /// power-state transitions.
938 ///
939 /// Public so an application can pre-disable a `Terminate` node *before*
940 /// `Supervisor::start`, making it a stopped-at-boot task that only comes up on
941 /// an explicit `Activate` control (a node started by control rather than at boot).
942 pub fn set_disabled(&self, disabled: bool) {
943 self.handle.disabled.store(disabled, Ordering::Release);
944 }
945
946 /// Wait until the instance has called `ack_dropped()`. Single-instance, so
947 /// one ack ends the wait. The fast-path flag check handles the ack landing
948 /// before this await (the `dropped_wake` signal is edge-triggered).
949 pub(crate) async fn wait_dropped(&self) {
950 if self.handle.dropped.load(Ordering::Acquire) {
951 return;
952 }
953 self.handle.dropped_wake.wait().await;
954 }
955
956 /// Clear the shutdown flag, dropped flag, busy flag, and the shutdown /
957 /// dropped wake-signals so the next cycle starts clean. Doesn't touch
958 /// `running` (managed around spawn/stop), `resume_wake` (`resume_pausable`
959 /// fires that for Pause nodes), or `disabled` (lifecycle-spanning).
960 pub(crate) fn reset(&self) {
961 self.handle.shutdown.store(false, Ordering::Release);
962 self.handle.dropped.store(false, Ordering::Release);
963 self.handle.busy.store(false, Ordering::Release);
964 self.handle.shutdown_wake.reset();
965 self.handle.dropped_wake.reset();
966 }
967}
968
969/// Manual impl: the private `TaskHandle` (Signals + atomics) has no `Debug`, and a
970/// snapshot of the *live* flags is more useful than raw handle internals anyway.
971/// `finish_non_exhaustive` marks the elided fields (`spawn`, the handle).
972impl core::fmt::Debug for TaskNode {
973 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
974 f.debug_struct("TaskNode")
975 .field("name", &self.name)
976 .field("mode", &self.mode)
977 .field("running", &self.is_running())
978 .field("busy", &self.is_busy())
979 .field("disabled", &self.is_disabled())
980 .field("detached", &self.is_detached())
981 .finish_non_exhaustive()
982 }
983}
984
985// ─── Graph ───────────────────────────────────────────────────────────────
986
987/// The compile-time task graph produced by [`supervisor_graph!`]: the node slots,
988/// the dependency-index table, the topological order, and the elastic pools — the
989/// single value [`Supervisor::new`] consumes. The macro emits one `pub static GRAPH`
990/// of this type. The fields are public so the application can read them directly
991/// (e.g. a status endpoint iterating `GRAPH.nodes` / `GRAPH.deps`).
992///
993/// `N` is capped at 256 (graph indices are `u8`); the macro enforces this at
994/// expansion time.
995pub struct Graph<const N: usize> {
996 /// Node slots, one per declared node. `None` marks a `#[cfg]`-ed-out node.
997 pub nodes: &'static [Option<&'static TaskNode>; N],
998 /// Per-node dependency indices into `nodes` (`deps[i]` lists node `i`'s deps).
999 pub deps: &'static [&'static [u8]; N],
1000 /// Topologically sorted indices into `nodes` (dependencies before dependents;
1001 /// reverse iteration is the teardown order). A dependency cycle is a compile error.
1002 pub order: [u8; N],
1003 /// Elastic worker pools to register with the supervisor (empty when unused).
1004 #[cfg(feature = "pool")]
1005 pub pools: &'static [&'static dyn Pool],
1006}
1007
1008// ─── Supervisor ──────────────────────────────────────────────────────────
1009
1010/// Orchestrates a set of managed tasks across spawn / teardown / bring-up.
1011///
1012/// Owned by a single supervisor task. Concurrent access from other tasks goes
1013/// through each [`TaskNode`]'s own atomic state, not the `Supervisor` struct.
1014pub struct Supervisor<const N: usize> {
1015 /// Node slots, one per declared node. `None` marks a slot whose node was
1016 /// `#[cfg]`-ed out of the build (feature-gated); every method skips those.
1017 nodes: &'static [Option<&'static TaskNode>],
1018 /// Per-node dependency indices into `nodes` (`deps[i]` lists the indices of
1019 /// the nodes that node `i` depends on). The single runtime source of graph
1020 /// topology, generated alongside `order` by the `supervisor_graph!` macro.
1021 deps: &'static [&'static [u8]],
1022 /// Topologically sorted indices into `nodes`: dependencies before their
1023 /// dependents; reverse iteration is the teardown order. Precomputed at
1024 /// compile time (a cycle is a compile error), so construction does no work.
1025 order: [u8; N],
1026 /// Elastic pools, so the control interface can co-control a whole pool from
1027 /// any one member (`apply_control` expands the target through
1028 /// [`Pool::members`]) — the same registry `run_pools` drives. Taken from
1029 /// `GRAPH.pools` at construction (empty when no pool is declared).
1030 #[cfg(feature = "pool")]
1031 pools: &'static [&'static dyn Pool],
1032}
1033
1034/// Await a node's `executor:` [`SpawnerSlot`] (if it has one), bounded by the
1035/// node's [`slot_timeout`](TaskNode::with_slot_timeout) (default
1036/// [`SLOT_READY_TIMEOUT`]). A slot still empty after the wait yields
1037/// [`SpawnError::Busy`] — a loud misconfiguration, not a silent hang. A node with no
1038/// slot returns immediately, so a same-executor bring-up never touches the timer.
1039async fn await_spawn_slot(node: &'static TaskNode) -> Result<(), SpawnError> {
1040 if let Some(slot) = node.spawn_slot {
1041 with_timeout(node.slot_timeout, slot.ready())
1042 .await
1043 .map_err(|_| SpawnError::Busy)?;
1044 }
1045 Ok(())
1046}
1047
1048/// Await every [`ResourceSlot`] a node's `resources:` clause takes from being
1049/// filled, bounded by the node's
1050/// [`slot_timeout`](TaskNode::with_slot_timeout) (default
1051/// [`SLOT_READY_TIMEOUT`]) per gate. Covers three windows: `main` providing
1052/// after `start` was entered; — on respawn — the previous instance's shell
1053/// still between the shutdown ack and its `restore()` call (on another core
1054/// the two can genuinely overlap); and a **provider node** still building the
1055/// values this node consumes (size `slot_timeout:` to the build time). A gate
1056/// still empty at the deadline yields [`SpawnError::Busy`] — an unprovided
1057/// slot is a loud misconfiguration, not a silent hang. Nodes without
1058/// `resources:` have an empty gate list and never touch the timer. Same
1059/// check-then-park loop as [`SpawnerSlot::ready`]; the `filled` signal
1060/// latches, so a fill racing the check still wakes the wait (and the same
1061/// single-pre-fill-waiter caveat applies — the supervisor task is the only
1062/// intended waiter).
1063async fn await_resources(node: &'static TaskNode) -> Result<(), SpawnError> {
1064 for gate in node.resource_gates {
1065 let wait = async {
1066 loop {
1067 if gate.is_filled() {
1068 break;
1069 }
1070 gate.filled_signal().wait().await;
1071 }
1072 };
1073 with_timeout(node.slot_timeout, wait)
1074 .await
1075 .map_err(|_| SpawnError::Busy)?;
1076 }
1077 Ok(())
1078}
1079
1080impl<const N: usize> Supervisor<N> {
1081 /// Build a supervisor from a precomputed [`Graph`] — the `GRAPH` that
1082 /// `supervisor_graph!` emits (node slots, dependency-index table, compile-time
1083 /// topological `order`, and the elastic pools). A dependency cycle is a
1084 /// *compile* error, so construction is infallible and does no work —
1085 /// `start` / `teardown` / `respawn_terminate` just iterate.
1086 pub const fn new(graph: &'static Graph<N>) -> Self {
1087 Self {
1088 nodes: graph.nodes,
1089 deps: graph.deps,
1090 order: graph.order,
1091 #[cfg(feature = "pool")]
1092 pools: graph.pools,
1093 }
1094 }
1095
1096 /// Spawn every boot node in dependency order. Called once at boot.
1097 /// `Mode::OnDemand` nodes are skipped — they're brought up at runtime by
1098 /// `start_node`. A **parked** node (no `spawn` fn) is spawned externally by
1099 /// `main()` (with hardware handles main owns); it's still marked `running`
1100 /// here. Disabled nodes, and `#[cfg]`-ed-out slots, are skipped.
1101 ///
1102 /// Async because an `executor: NAME` node first awaits its [`SpawnerSlot::ready`]
1103 /// (bounded by `SLOT_READY_TIMEOUT` — the rendezvous with a tier or second core
1104 /// that comes up asynchronously); a slot still empty at the deadline fails the
1105 /// bring-up with [`SpawnError::Busy`]. A node with no `executor:` slot never
1106 /// touches the timer.
1107 pub async fn start(&self, spawner: Spawner) -> Result<(), SpawnError> {
1108 // Register the node slots with the trace recorders.
1109 #[cfg(feature = "trace")]
1110 trace::register_graph(self.nodes);
1111
1112 for i in self.order.iter() {
1113 let Some(node) = self.nodes[*i as usize] else {
1114 continue;
1115 };
1116 if matches!(node.mode, Mode::OnDemand) || node.is_disabled() {
1117 continue;
1118 }
1119 info!("supervisor: spawning {} ({})", node.name, node.mode);
1120 if let Some(spawn) = node.spawn {
1121 // For an `executor:` node, wait (bounded) for its slot to be filled
1122 // before spawning; a same-executor node has no slot, so this is an
1123 // immediate no-op and the bring-up loop stays tight. Then wait for
1124 // the node's `resources:` slots (if any) so the glue's take() finds
1125 // the value even if main provides late.
1126 await_spawn_slot(node).await?;
1127 await_resources(node).await?;
1128 spawn(spawner)?;
1129 }
1130 node.set_running(true);
1131 }
1132 Ok(())
1133 }
1134
1135 /// Start a single node at runtime — e.g. growing an elastic pool. Resets the
1136 /// handle, spawns one instance via the node's `spawn` fn (which must launch
1137 /// exactly one), and marks it `running`. Returns `SpawnError::Busy` if the
1138 /// underlying embassy task pool is exhausted (the ceiling), which the caller
1139 /// treats as "can't grow".
1140 pub async fn start_node(
1141 &self,
1142 node: &'static TaskNode,
1143 spawner: Spawner,
1144 ) -> Result<(), SpawnError> {
1145 node.reset();
1146 if let Some(spawn) = node.spawn {
1147 await_spawn_slot(node).await?;
1148 await_resources(node).await?;
1149 spawn(spawner)?;
1150 }
1151 node.set_running(true);
1152 info!("supervisor: started {}", node.name);
1153 Ok(())
1154 }
1155
1156 /// Signal `node` to shut down, wait for its ack (panicking on timeout — a
1157 /// missing `ack_dropped()` somewhere), then clear `running`. Shared by
1158 /// `stop_node` and `teardown`; the caller must have checked `is_running`.
1159 async fn shutdown_and_wait(&self, node: &'static TaskNode) {
1160 node.signal_shutdown();
1161 if let Either::Second(()) = select(
1162 node.wait_dropped(),
1163 Timer::after_millis(SHUTDOWN_ACK_TIMEOUT_MS),
1164 )
1165 .await
1166 {
1167 panic!(
1168 "supervisor: task {} did not ack shutdown within {}ms",
1169 node.name, SHUTDOWN_ACK_TIMEOUT_MS,
1170 );
1171 }
1172 node.set_running(false);
1173 }
1174
1175 /// Stop a single running node at runtime — e.g. shrinking an elastic pool.
1176 /// Signals shutdown, waits for the ack, clears `running`. No-op if the node
1177 /// isn't running, or is [detached](TaskNode::set_detached) (self-managed — the
1178 /// supervisor never stops it). Panics if it doesn't ack within the timeout.
1179 pub async fn stop_node(&self, node: &'static TaskNode) {
1180 if !node.is_running() || node.is_detached() {
1181 return;
1182 }
1183 self.shutdown_and_wait(node).await;
1184 info!("supervisor: stopped {}", node.name);
1185 }
1186
1187 /// Signal every **running** node to shut down in **reverse** topological
1188 /// order, awaiting each node's ack before moving to its dependency. Down
1189 /// `OnDemand` nodes are skipped (no instance to ack). Pause-mode nodes ack
1190 /// and park on `wait_resume()`; Terminate/OnDemand nodes exit. Panics if a
1191 /// running node fails to ack within `SHUTDOWN_ACK_TIMEOUT_MS`.
1192 pub async fn teardown(&self) {
1193 for i in self.order.iter().rev() {
1194 let Some(node) = self.nodes[*i as usize] else {
1195 continue;
1196 };
1197 if !node.is_running() {
1198 continue;
1199 }
1200 // A detached node is self-managed; never tear it down. See
1201 // [`TaskNode::set_detached`].
1202 if node.is_detached() {
1203 continue;
1204 }
1205 info!("supervisor: tearing down {}", node.name);
1206 self.shutdown_and_wait(node).await;
1207 }
1208 }
1209
1210 /// Signal every Pause-mode node to resume. Cheap and synchronous — the tasks
1211 /// were parked on `wait_resume()` and pick up immediately. Called separately
1212 /// from `respawn_terminate` so the application can fire resume independently
1213 /// of the respawn step. Disabled (manually-paused) nodes are skipped so a
1214 /// manual pause sticks, and detached (self-managed) Pause nodes are left
1215 /// parked; there is intentionally no dependency gate here.
1216 pub fn resume_pausable(&self) {
1217 for i in self.order.iter() {
1218 let Some(node) = self.nodes[*i as usize] else {
1219 continue;
1220 };
1221 if matches!(node.mode, Mode::Pause) && !node.is_disabled() && !node.is_detached() {
1222 node.reset();
1223 info!("supervisor: resuming {}", node.name);
1224 node.signal_resume();
1225 node.set_running(true);
1226 }
1227 }
1228 }
1229
1230 /// Reset and re-spawn every Terminate-mode node in dependency order.
1231 /// Pause-mode nodes are untouched (use `resume_pausable`); `OnDemand` nodes
1232 /// are left down — they re-grow under load via `start_node`. Disabled nodes
1233 /// are skipped so a manual stop sticks across the bring-up. Detached nodes are
1234 /// skipped too: `teardown` never brought them down, so they are still running
1235 /// and re-spawning would double-spawn them (see [`TaskNode::set_detached`]). The
1236 /// reset happens before the spawn so newly-running tasks see a clean handle.
1237 pub async fn respawn_terminate(&self, spawner: Spawner) -> Result<(), SpawnError> {
1238 for i in self.order.iter() {
1239 let Some(node) = self.nodes[*i as usize] else {
1240 continue;
1241 };
1242 if matches!(node.mode, Mode::Terminate) && !node.is_disabled() && !node.is_detached() {
1243 node.reset();
1244 info!("supervisor: respawning {}", node.name);
1245 if let Some(spawn) = node.spawn {
1246 await_spawn_slot(node).await?;
1247 // A `resources:` node's previous instance restores its slot
1248 // value only after the shutdown ack, so wait (bounded) for
1249 // the restore before the glue's take().
1250 await_resources(node).await?;
1251 spawn(spawner)?;
1252 }
1253 node.set_running(true);
1254 }
1255 }
1256 Ok(())
1257 }
1258}
1259
1260// ─── Runtime control (dependency- and pool-honoring start/stop) ────────────
1261//
1262// The `apply_control` entry point drives one `ControlCommand` from the
1263// application's control surface. Unlike the pool's bare `start_node`/`stop_node`,
1264// these honor the graph: a stop cascades through dependents (so nothing is left
1265// running without a dependency), a start cascades through deps (so nothing comes
1266// up before what it needs), and either expands across a whole `ElasticPool` so
1267// the pool is controlled as a unit. A manual stop/pause also sets the
1268// lifecycle-spanning `disabled` flag, so it sticks against the elastic policy and
1269// the wake respawn.
1270
1271// Graph-index helpers used by BOTH the control plane and the pool driver, so they
1272// are gated on either feature — `pool` alone (no `control`) must still compile.
1273#[cfg(any(feature = "control", feature = "pool"))]
1274impl<const N: usize> Supervisor<N> {
1275 /// Position of `node` in `self.nodes` (pointer identity — every node is a
1276 /// `&'static`). `None` only if the node isn't in this graph (impossible for
1277 /// targets sourced from `GRAPH.nodes`; treated as a no-op by callers).
1278 fn index_of(&self, node: &'static TaskNode) -> Option<usize> {
1279 self.nodes
1280 .iter()
1281 .position(|n| n.is_some_and(|x| core::ptr::eq(x, node)))
1282 }
1283
1284 /// Whether every dependency of `node` is currently running, resolved through
1285 /// the graph's index table. The pool driver checks this before growing a
1286 /// worker, so a pool member is never spawned while one of its dependencies is
1287 /// down.
1288 #[cfg(feature = "pool")]
1289 pub(crate) fn deps_running(&self, node: &'static TaskNode) -> bool {
1290 match self.index_of(node) {
1291 Some(i) => self.deps[i]
1292 .iter()
1293 .all(|&di| self.nodes[di as usize].is_some_and(|n| n.is_running())),
1294 None => false,
1295 }
1296 }
1297}
1298
1299#[cfg(feature = "control")]
1300impl<const N: usize> Supervisor<N> {
1301 /// Seed a membership set with `target` plus — if `target` belongs to an
1302 /// elastic pool — every member of that pool, so control is applied to the
1303 /// whole pool atomically. Pool membership is read from `GRAPH.pools`; with no
1304 /// pools (the `pool` feature off, or none declared) this is just `{target}`.
1305 fn seed(&self, target: &'static TaskNode, set: &mut [bool; N]) {
1306 if let Some(i) = self.index_of(target) {
1307 set[i] = true;
1308 }
1309 #[cfg(feature = "pool")]
1310 for pool in self.pools {
1311 let members = pool.members();
1312 if members.iter().any(|m| core::ptr::eq(*m, target)) {
1313 for m in members {
1314 if let Some(i) = self.index_of(m) {
1315 set[i] = true;
1316 }
1317 }
1318 }
1319 }
1320 }
1321
1322 /// Apply one control command, honoring pool membership and the dependency
1323 /// graph. Run from the supervisor's driver loop (never concurrently with
1324 /// itself), so the cascade is atomic from the application's perspective.
1325 pub async fn apply_control(&self, cmd: ControlCommand, spawner: Spawner) {
1326 match cmd.op {
1327 ControlOp::Deactivate => self.deactivate(cmd.node).await,
1328 ControlOp::Activate => self.activate(cmd.node, spawner).await,
1329 }
1330 }
1331
1332 /// Bring `target` (and its pool, and every transitive dependent) down, in
1333 /// reverse-topological order so each dependent stops before the dependency it
1334 /// relies on. Marks the whole set `disabled` so the stop sticks against the
1335 /// elastic policy and the wake respawn until a matching `activate`.
1336 async fn deactivate(&self, target: &'static TaskNode) {
1337 let mut set = [false; N];
1338 self.seed(target, &mut set);
1339
1340 // Grow the set to include transitive dependents. `order` is
1341 // dependency-first, so when we reach a node its deps are already decided;
1342 // a node joins if any dep it declares is already in the set.
1343 for i in self.order.iter() {
1344 let j = *i as usize;
1345 if set[j] {
1346 continue;
1347 }
1348 let Some(node) = self.nodes[j] else {
1349 continue;
1350 };
1351 // A detached node declares its dep only for start ordering and intends
1352 // to outlive it, so it's never pulled into the cascade.
1353 if node.is_detached() {
1354 continue;
1355 }
1356 if self.deps[j].iter().any(|&di| set[di as usize]) {
1357 set[j] = true;
1358 }
1359 }
1360
1361 // Tear down in reverse topo order (dependents before their deps).
1362 for i in self.order.iter().rev() {
1363 let j = *i as usize;
1364 if !set[j] {
1365 continue;
1366 }
1367 let Some(node) = self.nodes[j] else {
1368 continue;
1369 };
1370 // A detached node is self-managed — never control-stop it. The growth loop
1371 // keeps detached *dependents* out of the set; this also covers a detached
1372 // node that was seeded directly (or a detached pool member). Without it a
1373 // detached one-shot that already exited (stale `is_running`, no ack path)
1374 // would be signalled a shutdown it can never acknowledge, panicking here.
1375 if node.is_detached() {
1376 continue;
1377 }
1378 node.set_disabled(true);
1379 if node.is_running() {
1380 info!("supervisor: control-stop {}", node.name);
1381 self.shutdown_and_wait(node).await;
1382 }
1383 }
1384 }
1385
1386 /// Bring `target` (and its pool, and every transitive dependency) up, in
1387 /// topological order so each dependency starts before its dependent. Clears
1388 /// `disabled` across the set. `OnDemand` (pool) members are only re-enabled,
1389 /// not force-spawned — the elastic policy re-grows them under load, which is
1390 /// the whole point of the pool.
1391 async fn activate(&self, target: &'static TaskNode, spawner: Spawner) {
1392 let mut set = [false; N];
1393 self.seed(target, &mut set);
1394
1395 // Grow the set to include transitive deps. Walk dependents-first
1396 // (reverse topo); when a set member is seen, pull in its direct deps.
1397 // A detached member's `deps:` are start-ordering only (the node is
1398 // self-managed), so don't expand from it — mirrors deactivate's guard;
1399 // otherwise activating a detached target would un-disable deps that
1400 // were independently disabled.
1401 for i in self.order.iter().rev() {
1402 let j = *i as usize;
1403 if set[j] && !self.nodes[j].is_some_and(|n| n.is_detached()) {
1404 for &di in self.deps[j] {
1405 set[di as usize] = true;
1406 }
1407 }
1408 }
1409
1410 // Bring up in topo order (deps before dependents).
1411 for i in self.order.iter() {
1412 let j = *i as usize;
1413 if !set[j] {
1414 continue;
1415 }
1416 let Some(node) = self.nodes[j] else {
1417 continue;
1418 };
1419 // A detached node is self-managed — the supervisor never re-enables or
1420 // re-starts it, even when it is a dependency of an activated target.
1421 if node.is_detached() {
1422 continue;
1423 }
1424 node.set_disabled(false);
1425 if node.is_running() {
1426 continue;
1427 }
1428 match node.mode {
1429 Mode::Terminate => {
1430 info!("supervisor: control-start {}", node.name);
1431 // SpawnError::Busy (pool exhausted) → can't start, skip.
1432 let _ = self.start_node(node, spawner).await;
1433 }
1434 Mode::Pause => {
1435 info!("supervisor: control-resume {}", node.name);
1436 node.reset();
1437 node.signal_resume();
1438 node.set_running(true);
1439 }
1440 // Pool worker — leave it down; the elastic policy regrows it on
1441 // demand now that `disabled` is cleared.
1442 Mode::OnDemand => {}
1443 }
1444 }
1445 }
1446}
1447
1448// ─── Topological sort (Kahn's algorithm, const) ───────────────────────────
1449//
1450// Computes the topological order at *compile time* over a per-node
1451// dependency-index table; a dependency cycle is a compile error.
1452
1453/// Topologically sort a graph given as a per-node dependency-index table.
1454///
1455/// `deps[i]` lists the indices of the nodes that node `i` depends on; the result
1456/// lists node indices in dependency-first order (a dependency appears before its
1457/// dependents). The supervisor iterates it forward for `start` /
1458/// `respawn_terminate` and in reverse for `teardown`.
1459///
1460/// Evaluated at compile time by the code `supervisor_graph!` generates — a
1461/// dependency **cycle is a compile error** (the `panic!` fires during const
1462/// evaluation). `#[doc(hidden)]`: an engine for the macro, not a user-facing API.
1463///
1464/// Supports at most 256 nodes: indices are `u8`, so a larger `N` would truncate.
1465/// The macro rejects bigger graphs at expansion; the assert below is defense in
1466/// depth for a manual caller (a const-eval panic, i.e. a compile error).
1467#[doc(hidden)]
1468#[must_use]
1469pub const fn topo_sort_const<const N: usize>(deps: &[&'static [u8]; N]) -> [u8; N] {
1470 assert!(
1471 N <= 256,
1472 "supervisor graph exceeds 256 node slots (indices are u8)"
1473 );
1474 // in_degree[i] = number of deps of node i not yet resolved.
1475 let mut in_degree = [0u8; N];
1476 let mut i = 0;
1477 while i < N {
1478 in_degree[i] = deps[i].len() as u8;
1479 i += 1;
1480 }
1481
1482 // Queue (fixed array, head/tail indices) seeded with the dependency-free nodes.
1483 let mut queue = [0u8; N];
1484 let mut tail = 0;
1485 i = 0;
1486 while i < N {
1487 if in_degree[i] == 0 {
1488 queue[tail] = i as u8;
1489 tail += 1;
1490 }
1491 i += 1;
1492 }
1493
1494 let mut order = [0u8; N];
1495 let mut produced = 0;
1496 let mut head = 0;
1497 while head < tail {
1498 let node = queue[head] as usize;
1499 head += 1;
1500 order[produced] = node as u8;
1501 produced += 1;
1502
1503 // Decrement the in-degree of every node that depends on `node`.
1504 let mut j = 0;
1505 while j < N {
1506 if in_degree[j] != 0 {
1507 let mut depends = false;
1508 let mut k = 0;
1509 while k < deps[j].len() {
1510 if deps[j][k] as usize == node {
1511 depends = true;
1512 }
1513 k += 1;
1514 }
1515 if depends {
1516 in_degree[j] -= 1;
1517 if in_degree[j] == 0 {
1518 queue[tail] = j as u8;
1519 tail += 1;
1520 }
1521 }
1522 }
1523 j += 1;
1524 }
1525 }
1526
1527 // A cycle leaves some nodes unproduced. During const eval this panic is a
1528 // compile error, so cyclic graphs are rejected at build time. `core::panic!`
1529 // (not the crate's defmt-shimmed `panic!`) keeps this const-evaluable.
1530 if produced != N {
1531 core::panic!("supervisor_graph!: dependency cycle");
1532 }
1533 order
1534}
1535
1536#[cfg(feature = "pool")]
1537mod pool;
1538#[cfg(feature = "pool")]
1539pub use pool::*;
1540
1541#[cfg(feature = "trace")]
1542pub mod trace;
1543
1544/// Declare a supervised task graph and compute its topological order at compile
1545/// time (single source of nodes, deps, pool, and order). See the
1546/// `embassy-supervisor-macros` crate for the surface syntax.
1547#[cfg(feature = "macros")]
1548pub use embassy_supervisor_macros::supervisor_graph;
1549
1550/// Building blocks for `supervisor_graph!`-generated code — NOT public API.
1551///
1552/// The macro's `local`-marked `resources:` entries emit a slot *type* at the
1553/// graph declaration site (it needs an `unsafe impl Sync`, — same reason the
1554/// `trace-hooks` symbols are emitted there). That generated type must name
1555/// the exact `Signal`/mutex types in [`ResourceGate`]'s signature; re-exporting
1556/// them here keeps the macro's contract that a consumer only needs
1557/// `embassy-supervisor` itself as a real-named dependency (not `embassy-sync`).
1558#[doc(hidden)]
1559pub mod _export {
1560 pub use embassy_sync::blocking_mutex::Mutex as BlockingMutex;
1561 pub use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
1562 pub use embassy_sync::signal::Signal;
1563 // For the `slot_timeout:` clause's emitted `with_slot_timeout(..)` call.
1564 pub use embassy_time::Duration;
1565}
1566
1567// ─── Tests (host-only) ─────────────────────────────────────────────────────
1568//
1569// Run on the host: `cargo test -p embassy-supervisor --target x86_64-unknown-linux-gnu`
1570// (the workspace `.cargo/config.toml` pins the embedded target, so `--target` is
1571// required to override it). These exercise the compile-time `topo_sort_const`
1572// over index adjacency tables — exactly what `supervisor_graph!` generates.
1573#[cfg(test)]
1574mod tests {
1575 use super::topo_sort_const;
1576
1577 /// Position of index `x` within `order`.
1578 fn pos<const N: usize>(order: &[u8; N], x: u8) -> usize {
1579 order.iter().position(|&y| y == x).expect("index present")
1580 }
1581
1582 #[test]
1583 fn linear_chain_orders_deps_before_dependents() {
1584 // A=0, B=1 dep A, C=2 dep B.
1585 const DEPS: [&[u8]; 3] = [&[], &[0], &[1]];
1586 const ORDER: [u8; 3] = topo_sort_const(&DEPS);
1587 assert_eq!(ORDER, [0, 1, 2]);
1588 }
1589
1590 #[test]
1591 fn diamond_puts_root_first_and_join_last() {
1592 // A=0; B=1 dep A; C=2 dep A; D=3 dep B,C.
1593 const DEPS: [&[u8]; 4] = [&[], &[0], &[0], &[1, 2]];
1594 const ORDER: [u8; 4] = topo_sort_const(&DEPS);
1595 assert_eq!(ORDER[0], 0, "root first");
1596 assert_eq!(ORDER[3], 3, "join last");
1597 assert!(pos(&ORDER, 1) < pos(&ORDER, 3), "B before D");
1598 assert!(pos(&ORDER, 2) < pos(&ORDER, 3), "C before D");
1599 }
1600
1601 #[test]
1602 fn independent_nodes_all_present() {
1603 const DEPS: [&[u8]; 2] = [&[], &[]];
1604 const ORDER: [u8; 2] = topo_sort_const(&DEPS);
1605 assert!(ORDER.contains(&0) && ORDER.contains(&1));
1606 }
1607
1608 #[test]
1609 fn unsorted_input_is_sorted() {
1610 // Declared out of dependency order: node 0 depends on 1 and 2, node 2 on 1.
1611 const DEPS: [&[u8]; 3] = [&[1, 2], &[], &[1]];
1612 const ORDER: [u8; 3] = topo_sort_const(&DEPS);
1613 assert!(pos(&ORDER, 1) < pos(&ORDER, 2), "1 before 2");
1614 assert!(pos(&ORDER, 2) < pos(&ORDER, 0), "2 before 0");
1615 }
1616
1617 #[test]
1618 fn evaluates_at_compile_time() {
1619 // The sort runs in a `const` context, proving it is const-evaluable.
1620 // (A cyclic table here would be a *compile* error, not a test failure.)
1621 const DEPS: [&[u8]; 3] = [&[], &[0], &[1]];
1622 const _: () = {
1623 let order = topo_sort_const(&DEPS);
1624 assert!(order[0] == 0 && order[1] == 1 && order[2] == 2);
1625 };
1626 }
1627
1628 // Uncommenting this must fail to compile ("dependency cycle"):
1629 // const CYCLE: [&[u8]; 2] = [&[1], &[0]];
1630 // const _BAD: [u8; 2] = topo_sort_const(&CYCLE);
1631}