Skip to main content

nros_node/
lifecycle.rs

1//! Lifecycle node API (REP-2002)
2//!
3//! Provides managed lifecycle state machines for nros nodes.
4//!
5//! - [`LifecyclePollingNode`] — standalone state machine with plain function pointers (`no_std`)
6//! - [`LifecyclePollingNodeCtx`] — standalone state machine with `unsafe fn(*mut c_void) -> TransitionResult`
7//!   callbacks, for bridging the C FFI (`no_std`)
8
9use core::ffi::c_void;
10use nros_core::lifecycle::{
11    LifecycleState, LifecycleTransition, TransitionResult, apply_transition, can_transition,
12};
13
14/// Error type for lifecycle transitions.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum LifecycleError {
17    /// The requested transition is not valid from the current state.
18    InvalidTransition {
19        /// The state the node was in when the transition was attempted.
20        from: LifecycleState,
21        /// The transition that was requested.
22        transition: LifecycleTransition,
23    },
24    /// The transition callback returned a non-success result.
25    CallbackFailed {
26        /// The transition that was attempted.
27        transition: LifecycleTransition,
28        /// The result returned by the callback.
29        result: TransitionResult,
30    },
31    /// The node is in the Finalized state and cannot transition.
32    NodeFinalized,
33}
34
35// ═══════════════════════════════════════════════════════════════════════════
36// LIFECYCLE POLLING NODE (no_std — function pointers, no NodeHandle)
37// ═══════════════════════════════════════════════════════════════════════════
38
39/// Lifecycle callback function pointer (`no_std` compatible).
40pub type LifecycleCallbackFn = fn() -> TransitionResult;
41
42/// Standalone lifecycle state machine for `no_std` environments.
43///
44/// Uses function pointers instead of boxed closures. Does not wrap a
45/// `NodeHandle` — the user manages the node separately.
46///
47/// # Example
48///
49/// ```ignore
50/// fn on_configure() -> TransitionResult {
51///     // Initialize hardware...
52///     TransitionResult::Success
53/// }
54///
55/// let mut lifecycle = LifecyclePollingNode::new();
56/// lifecycle.register_on_configure(on_configure);
57/// lifecycle.configure()?;
58/// ```
59pub struct LifecyclePollingNode {
60    state: LifecycleState,
61    on_configure: Option<LifecycleCallbackFn>,
62    on_activate: Option<LifecycleCallbackFn>,
63    on_deactivate: Option<LifecycleCallbackFn>,
64    on_cleanup: Option<LifecycleCallbackFn>,
65    on_shutdown: Option<LifecycleCallbackFn>,
66    on_error: Option<LifecycleCallbackFn>,
67}
68
69impl LifecyclePollingNode {
70    /// Create a new standalone lifecycle state machine.
71    ///
72    /// Starts in the `Unconfigured` state.
73    pub const fn new() -> Self {
74        Self {
75            state: LifecycleState::Unconfigured,
76            on_configure: None,
77            on_activate: None,
78            on_deactivate: None,
79            on_cleanup: None,
80            on_shutdown: None,
81            on_error: None,
82        }
83    }
84
85    /// Get the current lifecycle state.
86    pub const fn state(&self) -> LifecycleState {
87        self.state
88    }
89
90    /// Trigger a lifecycle transition.
91    pub fn trigger_transition(
92        &mut self,
93        transition: LifecycleTransition,
94    ) -> Result<LifecycleState, LifecycleError> {
95        if self.state.is_terminal() {
96            return Err(LifecycleError::NodeFinalized);
97        }
98
99        if !can_transition(self.state, transition) {
100            return Err(LifecycleError::InvalidTransition {
101                from: self.state,
102                transition,
103            });
104        }
105
106        let result = self.invoke_callback(transition);
107        self.state = apply_transition(self.state, transition, result);
108
109        if result == TransitionResult::Success {
110            Ok(self.state)
111        } else {
112            Err(LifecycleError::CallbackFailed { transition, result })
113        }
114    }
115
116    /// Convenience: configure (Unconfigured -> Inactive)
117    pub fn configure(&mut self) -> Result<LifecycleState, LifecycleError> {
118        self.trigger_transition(LifecycleTransition::Configure)
119    }
120
121    /// Convenience: activate (Inactive -> Active)
122    pub fn activate(&mut self) -> Result<LifecycleState, LifecycleError> {
123        self.trigger_transition(LifecycleTransition::Activate)
124    }
125
126    /// Convenience: deactivate (Active -> Inactive)
127    pub fn deactivate(&mut self) -> Result<LifecycleState, LifecycleError> {
128        self.trigger_transition(LifecycleTransition::Deactivate)
129    }
130
131    /// Convenience: cleanup (Inactive -> Unconfigured)
132    pub fn cleanup(&mut self) -> Result<LifecycleState, LifecycleError> {
133        self.trigger_transition(LifecycleTransition::Cleanup)
134    }
135
136    /// Convenience: shutdown from the current state.
137    pub fn shutdown(&mut self) -> Result<LifecycleState, LifecycleError> {
138        let transition = match self.state {
139            LifecycleState::Unconfigured => LifecycleTransition::ShutdownUnconfigured,
140            LifecycleState::Inactive => LifecycleTransition::ShutdownInactive,
141            LifecycleState::Active => LifecycleTransition::ShutdownActive,
142            LifecycleState::Finalized => return Err(LifecycleError::NodeFinalized),
143            LifecycleState::ErrorProcessing => {
144                return Err(LifecycleError::InvalidTransition {
145                    from: self.state,
146                    transition: LifecycleTransition::ShutdownUnconfigured,
147                });
148            }
149        };
150        self.trigger_transition(transition)
151    }
152
153    /// Convenience: configure then activate (stops on failure).
154    pub fn bring_up(&mut self) -> Result<LifecycleState, LifecycleError> {
155        self.configure()?;
156        self.activate()
157    }
158
159    /// Register a callback for the `configure` transition.
160    pub fn register_on_configure(&mut self, cb: LifecycleCallbackFn) {
161        self.on_configure = Some(cb);
162    }
163
164    /// Register a callback for the `activate` transition.
165    pub fn register_on_activate(&mut self, cb: LifecycleCallbackFn) {
166        self.on_activate = Some(cb);
167    }
168
169    /// Register a callback for the `deactivate` transition.
170    pub fn register_on_deactivate(&mut self, cb: LifecycleCallbackFn) {
171        self.on_deactivate = Some(cb);
172    }
173
174    /// Register a callback for the `cleanup` transition.
175    pub fn register_on_cleanup(&mut self, cb: LifecycleCallbackFn) {
176        self.on_cleanup = Some(cb);
177    }
178
179    /// Register a callback for the `shutdown` transition.
180    pub fn register_on_shutdown(&mut self, cb: LifecycleCallbackFn) {
181        self.on_shutdown = Some(cb);
182    }
183
184    /// Register a callback for the `error` transition (error recovery).
185    pub fn register_on_error(&mut self, cb: LifecycleCallbackFn) {
186        self.on_error = Some(cb);
187    }
188
189    fn invoke_callback(&mut self, transition: LifecycleTransition) -> TransitionResult {
190        let cb = match transition {
191            LifecycleTransition::Configure => self.on_configure,
192            LifecycleTransition::Activate => self.on_activate,
193            LifecycleTransition::Deactivate => self.on_deactivate,
194            LifecycleTransition::Cleanup => self.on_cleanup,
195            LifecycleTransition::ShutdownUnconfigured
196            | LifecycleTransition::ShutdownInactive
197            | LifecycleTransition::ShutdownActive => self.on_shutdown,
198            LifecycleTransition::ErrorRecovery => self.on_error,
199        };
200
201        match cb {
202            Some(f) => f(),
203            None => TransitionResult::Success,
204        }
205    }
206}
207
208impl Default for LifecyclePollingNode {
209    fn default() -> Self {
210        Self::new()
211    }
212}
213
214// ═══════════════════════════════════════════════════════════════════════════
215// LIFECYCLE POLLING NODE WITH CONTEXT (no_std — C FFI compatible)
216// ═══════════════════════════════════════════════════════════════════════════
217
218/// Lifecycle callback taking a user context pointer (`no_std`, C FFI shape).
219///
220/// Returns a `u8` matching the C `RCLC_LIFECYCLE_RET_*` constants
221/// (`0 = Success`, `1 = Failure`, `2 = Error`). Any unknown value is
222/// coerced to [`TransitionResult::Error`] inside
223/// [`LifecyclePollingNodeCtx::trigger_transition`].
224pub type LifecycleCallbackFnCtx = unsafe extern "C" fn(ctx: *mut c_void) -> u8;
225
226/// One transition this state machine has performed and not yet ANNOUNCED on
227/// `~/transition_event` (REP-2002's communication interface).
228///
229/// Crate-visible: this is the MECHANISM between the state machine and the
230/// executor that owns the publisher, not a surface a user drives. A node that
231/// wants to know the state asks [`LifecyclePollingNodeCtx::state`]; a node
232/// that wants to watch another node's transitions subscribes to the topic.
233///
234/// Recorded by [`LifecyclePollingNodeCtx::trigger_transition`] and drained by
235/// the executor, which owns the publisher. Recording where the transition
236/// HAPPENS rather than at each caller is the whole point: `ros2 lifecycle
237/// set`, `rclc_executor_lifecycle_change_state`,
238/// `nros_cpp_lifecycle_change_state`, `nros_cpp_lifecycle_register_node` and the
239/// safe `LifecycleCallbacks` road all funnel through that one function, so a
240/// new caller is announced without being told to announce.
241#[cfg(feature = "lifecycle-services")]
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub(crate) struct TransitionAnnouncement {
244    /// Steady-clock nanoseconds at the moment the transition completed.
245    ///
246    /// rcl stamps `TransitionEvent.timestamp` from `rcutils_steady_time_now`
247    /// in `rcl_lifecycle`'s `com_interface.c`, not from the wall clock, so
248    /// this reads [`nros_core::clock::Clock::steady`].
249    pub timestamp_ns: u64,
250    /// The transition that ran.
251    pub transition: LifecycleTransition,
252    /// The state the machine was in before it ran.
253    pub start_state: LifecycleState,
254    /// The state the machine reached, whether the callback succeeded or not.
255    pub goal_state: LifecycleState,
256}
257
258/// How many [`TransitionAnnouncement`]s a state machine holds between drains.
259///
260/// The drain is the executor's lifecycle step, so the bound is "the longest
261/// burst a transition source can produce before the executor next spins".
262/// Measured against the sources in this tree the longest is TWO —
263/// `nros_cpp_lifecycle_register_node(exec, ns, name, 2)` runs `configure` then
264/// `activate` from `__nros_entry_setup`, before the spin loop starts. Four is that with
265/// headroom for a caller driving its own sequence; beyond it a record is
266/// dropped and COUNTED, never silently lost
267/// ([`LifecyclePollingNodeCtx::take_dropped_announcements`]) — the posture the
268/// zpico session's `reply_slot_refusals` already takes for the other bounded
269/// table in this stack.
270#[cfg(feature = "lifecycle-services")]
271pub(crate) const TRANSITION_ANNOUNCEMENT_QUEUE: usize = 4;
272
273// RFC-0128 D3 / phase-554 W6.
274/// A managed node's publishers follow its state. One byte, read and written
275/// with plain atomic loads and stores so it needs no compare-and-swap
276/// (thumbv6m has none).
277///
278/// A node that is not managed stays `UNMANAGED` and its publishers always
279/// send. Once its lifecycle machine exists the gate is `INACTIVE` until the
280/// machine enters `active`.
281pub struct PublishGate(core::sync::atomic::AtomicU8);
282
283impl PublishGate {
284    // Only the node table creates unmanaged gates, and it needs a backend.
285    #[cfg_attr(not(any(has_rmw, test)), allow(dead_code))]
286    const UNMANAGED: u8 = 0;
287    const INACTIVE: u8 = 1;
288    const ACTIVE: u8 = 2;
289
290    // Only the node table creates unmanaged gates, and it needs a backend.
291    #[cfg_attr(not(any(has_rmw, test)), allow(dead_code))]
292    /// A gate for a node that is not managed: always open.
293    pub(crate) const fn unmanaged() -> Self {
294        Self(core::sync::atomic::AtomicU8::new(Self::UNMANAGED))
295    }
296
297    /// Open (`true`) or close the gate of a managed node.
298    pub(crate) fn set_active(&self, active: bool) {
299        let v = if active { Self::ACTIVE } else { Self::INACTIVE };
300        self.0.store(v, core::sync::atomic::Ordering::Release);
301    }
302
303    /// Whether a publisher of this node may send now.
304    pub fn is_open(&self) -> bool {
305        self.0.load(core::sync::atomic::Ordering::Acquire) != Self::INACTIVE
306    }
307}
308
309// RFC-0128 D3 / phase-554 W6.
310/// A publisher's view of its node's
311/// [`PublishGate`].
312///
313/// A managed node's publisher sends nothing while the node is not `active`:
314/// `publish` returns success and the first dropped message logs once, as
315/// rclcpp's `LifecyclePublisher` warns. A publisher created off a node (the
316/// executor's own, or an internal one) carries no gate and always sends.
317///
318/// Public so the C and C++ publishers hold the same thing and drop and report
319/// exactly as a Rust one does. Get one from `Executor::publisher_gate`.
320pub struct PublisherGate {
321    /// The node's gate, in the executor's node table, which is carved from
322    /// the executor's backing and never moves. Read only while the executor
323    /// is open, which is also the life of the RMW handle beside it.
324    node: Option<core::ptr::NonNull<PublishGate>>,
325    /// Set after the first dropped message has been reported. A plain load
326    /// and store: one publisher is used from one context at a time.
327    warned: core::sync::atomic::AtomicBool,
328}
329
330// SAFETY: the pointee is a `PublishGate`, which is an atomic byte; reading it
331// from another thread is what it is for.
332unsafe impl Send for PublisherGate {}
333// SAFETY: as above; `warned` is atomic too.
334unsafe impl Sync for PublisherGate {}
335
336impl PublisherGate {
337    /// A publisher that belongs to no node: always sends.
338    pub const fn none() -> Self {
339        Self {
340            node: None,
341            warned: core::sync::atomic::AtomicBool::new(false),
342        }
343    }
344
345    /// A publisher of the node whose gate this is.
346    #[cfg_attr(not(any(has_rmw, test)), allow(dead_code))]
347    pub(crate) fn of(gate: core::ptr::NonNull<PublishGate>) -> Self {
348        Self {
349            node: Some(gate),
350            warned: core::sync::atomic::AtomicBool::new(false),
351        }
352    }
353
354    /// `true` when this message must be dropped because the node is not
355    /// active. Reports the first drop on the log.
356    pub fn drops(&self, topic: &str) -> bool {
357        use core::sync::atomic::Ordering;
358        let Some(gate) = self.node else {
359            return false;
360        };
361        // SAFETY: see `node`.
362        if unsafe { gate.as_ref() }.is_open() {
363            return false;
364        }
365        if !self.warned.load(Ordering::Relaxed) {
366            self.warned.store(true, Ordering::Relaxed);
367            nros_log::log_warn!(
368                nros_log::get_logger("nros_lifecycle"),
369                "publishing on `{}` while its node is not active: the message is \
370                 dropped, and so is every message until the node is activated",
371                topic
372            );
373        }
374        true
375    }
376}
377
378/// Lifecycle state machine with `unsafe fn(*mut c_void) -> TransitionResult` callbacks.
379///
380/// Thin counterpart to [`LifecyclePollingNode`] for bridging the C FFI: each
381/// callback slot stores a pointer to `extern "C"` user code plus a single
382/// shared `*mut c_void` context that is passed on every invocation. The core
383/// state machine logic comes from [`nros_core::lifecycle`], same as
384/// `LifecyclePollingNode`.
385pub struct LifecyclePollingNodeCtx {
386    state: LifecycleState,
387    on_configure: Option<LifecycleCallbackFnCtx>,
388    on_activate: Option<LifecycleCallbackFnCtx>,
389    on_deactivate: Option<LifecycleCallbackFnCtx>,
390    on_cleanup: Option<LifecycleCallbackFnCtx>,
391    on_shutdown: Option<LifecycleCallbackFnCtx>,
392    on_error: Option<LifecycleCallbackFnCtx>,
393    context: *mut c_void,
394    /// Transitions performed and not yet announced on `~/transition_event`.
395    ///
396    /// Behind `lifecycle-services` with everything else in this mechanism: the
397    /// drain is the executor's publisher, so an image that registers no
398    /// lifecycle services has nowhere to announce TO, and recording into a
399    /// queue nobody reads is bytes and a clock read per transition bought for
400    /// nothing.
401    #[cfg(feature = "lifecycle-services")]
402    announcements: heapless::Deque<TransitionAnnouncement, TRANSITION_ANNOUNCEMENT_QUEUE>,
403    /// How many announcements the queue above had to drop. Saturating: the
404    /// number is a signal, and a wrap would turn it into a lie.
405    #[cfg(feature = "lifecycle-services")]
406    announcements_dropped: u32,
407    // RFC-0128 D3 / phase-554 W6.
408    /// The publish gate of the node this
409    /// machine is served on, in the executor's node table (carved, so it never
410    /// moves). `None` for a standalone machine with no node.
411    publish_gate: Option<core::ptr::NonNull<PublishGate>>,
412}
413
414// `*mut c_void` is `!Sync` + `!Send`; that's the correct posture for a
415// state machine owned by one task. No auto-impl needed.
416
417impl LifecyclePollingNodeCtx {
418    /// Create a new standalone lifecycle state machine. Starts in `Unconfigured`.
419    pub const fn new() -> Self {
420        Self {
421            state: LifecycleState::Unconfigured,
422            on_configure: None,
423            on_activate: None,
424            on_deactivate: None,
425            on_cleanup: None,
426            on_shutdown: None,
427            on_error: None,
428            context: core::ptr::null_mut(),
429            #[cfg(feature = "lifecycle-services")]
430            announcements: heapless::Deque::new(),
431            #[cfg(feature = "lifecycle-services")]
432            announcements_dropped: 0,
433            publish_gate: None,
434        }
435    }
436
437    /// Make `gate` follow this machine: open while the machine is `active`,
438    /// closed otherwise. Called once, when the executor creates the machine
439    /// for a node; from then on every transition writes it. Only the
440    /// executor's node machines call it, and those need `lifecycle-services`
441    /// and a backend (the `lifecycle_services` module's own condition).
442    #[cfg_attr(
443        not(all(feature = "lifecycle-services", any(has_rmw, test))),
444        allow(dead_code)
445    )]
446    pub(crate) fn bind_publish_gate(&mut self, gate: core::ptr::NonNull<PublishGate>) {
447        self.publish_gate = Some(gate);
448        self.sync_publish_gate();
449    }
450
451    fn set_publish_gate(&self, active: bool) {
452        if let Some(g) = self.publish_gate {
453            // SAFETY: see `publish_gate`; the executor that owns this machine
454            // owns the node table too.
455            unsafe { g.as_ref() }.set_active(active);
456        }
457    }
458
459    fn sync_publish_gate(&self) {
460        self.set_publish_gate(self.state == LifecycleState::Active);
461    }
462
463    /// Get the current lifecycle state.
464    pub const fn state(&self) -> LifecycleState {
465        self.state
466    }
467
468    /// Take the oldest unannounced transition, if any.
469    ///
470    /// The executor calls this until it returns `None` and publishes each one
471    /// on `~/transition_event`. A state machine nobody drains fills its queue
472    /// and counts the overflow; it never blocks a transition.
473    #[cfg(all(feature = "lifecycle-services", any(has_rmw, test)))]
474    pub(crate) fn take_announcement(&mut self) -> Option<TransitionAnnouncement> {
475        self.announcements.pop_front()
476    }
477
478    /// How many announcements have been dropped since this was last called —
479    /// and reset the counter.
480    ///
481    /// Read-and-clear rather than read, so a drainer reports a burst once
482    /// instead of once per spin for the rest of the image's life.
483    #[cfg(all(feature = "lifecycle-services", any(has_rmw, test)))]
484    pub(crate) fn take_dropped_announcements(&mut self) -> u32 {
485        core::mem::replace(&mut self.announcements_dropped, 0)
486    }
487
488    /// Record a completed transition for the executor to announce.
489    #[cfg(feature = "lifecycle-services")]
490    fn record_announcement(
491        &mut self,
492        transition: LifecycleTransition,
493        start_state: LifecycleState,
494        goal_state: LifecycleState,
495    ) {
496        let record = TransitionAnnouncement {
497            timestamp_ns: nros_core::clock::Clock::steady().now().to_nanos().max(0) as u64,
498            transition,
499            start_state,
500            goal_state,
501        };
502        if self.announcements.push_back(record).is_err() {
503            self.announcements_dropped = self.announcements_dropped.saturating_add(1);
504        }
505    }
506
507    /// Set the user context pointer passed to every callback.
508    pub fn set_context(&mut self, ctx: *mut c_void) {
509        self.context = ctx;
510    }
511
512    /// Get the user context pointer.
513    pub fn context(&self) -> *mut c_void {
514        self.context
515    }
516
517    /// Register / clear the callback for a given transition slot.
518    pub fn register(&mut self, slot: LifecycleCallbackSlot, cb: Option<LifecycleCallbackFnCtx>) {
519        match slot {
520            LifecycleCallbackSlot::Configure => self.on_configure = cb,
521            LifecycleCallbackSlot::Activate => self.on_activate = cb,
522            LifecycleCallbackSlot::Deactivate => self.on_deactivate = cb,
523            LifecycleCallbackSlot::Cleanup => self.on_cleanup = cb,
524            LifecycleCallbackSlot::Shutdown => self.on_shutdown = cb,
525            LifecycleCallbackSlot::Error => self.on_error = cb,
526        }
527    }
528
529    /// Clear every registered callback. Used on fini.
530    pub fn clear_callbacks(&mut self) {
531        self.on_configure = None;
532        self.on_activate = None;
533        self.on_deactivate = None;
534        self.on_cleanup = None;
535        self.on_shutdown = None;
536        self.on_error = None;
537        self.context = core::ptr::null_mut();
538    }
539
540    /// Force the state to `Finalized`. Used on fini.
541    pub fn finalize(&mut self) {
542        self.state = LifecycleState::Finalized;
543        self.sync_publish_gate();
544    }
545
546    /// Trigger a lifecycle transition.
547    ///
548    /// # Safety
549    /// The registered callback (if any) is called via a raw `unsafe fn` pointer
550    /// with the stored `*mut c_void` context. The caller must guarantee that
551    /// any registered callback / context pair remains valid.
552    pub unsafe fn trigger_transition(
553        &mut self,
554        transition: LifecycleTransition,
555    ) -> Result<LifecycleState, LifecycleError> {
556        if self.state.is_terminal() {
557            return Err(LifecycleError::NodeFinalized);
558        }
559
560        if !can_transition(self.state, transition) {
561            return Err(LifecycleError::InvalidTransition {
562                from: self.state,
563                transition,
564            });
565        }
566
567        let cb = match transition {
568            LifecycleTransition::Configure => self.on_configure,
569            LifecycleTransition::Activate => self.on_activate,
570            LifecycleTransition::Deactivate => self.on_deactivate,
571            LifecycleTransition::Cleanup => self.on_cleanup,
572            LifecycleTransition::ShutdownUnconfigured
573            | LifecycleTransition::ShutdownInactive
574            | LifecycleTransition::ShutdownActive => self.on_shutdown,
575            LifecycleTransition::ErrorRecovery => self.on_error,
576        };
577
578        // RFC-0128 D3: the publishers are active by the time `on_activate`
579        // runs, as rclcpp's base `on_activate` activates them first, so a
580        // publish inside the callback goes out. The line after the callback
581        // closes them again if activation did not land in `active`.
582        if transition == LifecycleTransition::Activate {
583            self.set_publish_gate(true);
584        }
585
586        let result = match cb {
587            Some(f) => {
588                let raw = unsafe { f(self.context) };
589                TransitionResult::from_u8(raw).unwrap_or(TransitionResult::Error)
590            }
591            None => TransitionResult::Success,
592        };
593
594        let start_state = self.state;
595        self.state = apply_transition(self.state, transition, result);
596        self.sync_publish_gate();
597
598        // REP-2002's communication interface is the five services PLUS a
599        // `~/transition_event` publisher, and this is the ONE place a
600        // transition happens (issue 1587). Recorded on the FAILURE path too:
601        // rcl publishes the failure transition as well, and a supervisor
602        // watching passively is exactly the reader who needs to see a
603        // `Configure` that landed in `ErrorProcessing` rather than `Inactive`.
604        // A REJECTED transition publishes nothing, because none ran — the two
605        // early returns above are before this point, as they are in rcl.
606        #[cfg(feature = "lifecycle-services")]
607        self.record_announcement(transition, start_state, self.state);
608        // No lifecycle services in this build means no publisher to announce
609        // on, so there is nothing to record and nothing to read `start_state`.
610        #[cfg(not(feature = "lifecycle-services"))]
611        let _ = start_state;
612
613        if result == TransitionResult::Success {
614            Ok(self.state)
615        } else {
616            Err(LifecycleError::CallbackFailed { transition, result })
617        }
618    }
619}
620
621impl Default for LifecyclePollingNodeCtx {
622    fn default() -> Self {
623        Self::new()
624    }
625}
626
627/// Which transition callback slot to register in [`LifecyclePollingNodeCtx::register`].
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629pub enum LifecycleCallbackSlot {
630    /// `Unconfigured -> Inactive`
631    Configure,
632    /// `Inactive -> Active`
633    Activate,
634    /// `Active -> Inactive`
635    Deactivate,
636    /// `Inactive -> Unconfigured`
637    Cleanup,
638    /// any state -> `Finalized`
639    Shutdown,
640    /// `ErrorProcessing -> Unconfigured`
641    Error,
642}
643
644// ═══════════════════════════════════════════════════════════════════════════
645// SAFE LIFECYCLE-CALLBACK TRAIT (issue 0335 / phase-317)
646// ═══════════════════════════════════════════════════════════════════════════
647
648/// Safe lifecycle-callback surface, symmetric with the C++ `nros::LifecycleNode`
649/// (rclcpp `LifecycleNodeInterface`). Implement the transitions you need; the
650/// rest default to `Success` (`on_error` to `Failure`), matching rclcpp's
651/// non-pure-virtual defaults. Register the node with
652/// `Executor::register_lifecycle_node`,
653/// which binds the five REP-2002 services and wires each transition here — no
654/// `unsafe` in user code.
655///
656/// # Example
657/// ```ignore
658/// struct MyNode { configured: bool }
659/// impl LifecycleCallbacks for MyNode {
660///     fn on_configure(&mut self) -> TransitionResult {
661///         self.configured = true;
662///         TransitionResult::Success
663///     }
664/// }
665/// executor.register_lifecycle_node(&mut my_node)?;
666/// ```
667///
668/// Unlike rclcpp's `on_*(const State& previous)`, the callbacks take no
669/// `previous` argument: the FFI callback boundary ([`LifecycleCallbackFnCtx`])
670/// carries only the user context, and the [`LifecyclePollingNode`] fn-pointer
671/// API is likewise state-less. Read the current state via
672/// `Executor::lifecycle_state_machine`
673/// `.state()` if a transition needs it.
674pub trait LifecycleCallbacks {
675    /// `Unconfigured -> Inactive`. Default: `Success`.
676    fn on_configure(&mut self) -> TransitionResult {
677        TransitionResult::Success
678    }
679    /// `Inactive -> Active`. Default: `Success`.
680    fn on_activate(&mut self) -> TransitionResult {
681        TransitionResult::Success
682    }
683    /// `Active -> Inactive`. Default: `Success`.
684    fn on_deactivate(&mut self) -> TransitionResult {
685        TransitionResult::Success
686    }
687    /// `Inactive -> Unconfigured`. Default: `Success`.
688    fn on_cleanup(&mut self) -> TransitionResult {
689        TransitionResult::Success
690    }
691    /// any state `-> Finalized`. Default: `Success`.
692    fn on_shutdown(&mut self) -> TransitionResult {
693        TransitionResult::Success
694    }
695    /// `ErrorProcessing -> Unconfigured`. Default: `Failure` (matching rclcpp).
696    fn on_error(&mut self) -> TransitionResult {
697        TransitionResult::Failure
698    }
699}
700
701/// Monomorphized `extern "C"` trampolines that recover `&mut T` from the FFI
702/// context pointer and dispatch to the [`LifecycleCallbacks`] method. rustc
703/// emits one per `T`, so there is no closure box — `no_std`-safe. Registered by
704/// `Executor::register_lifecycle_node`;
705/// not meant to be called directly.
706pub mod trampolines {
707    use super::{LifecycleCallbacks, TransitionResult};
708    use core::ffi::c_void;
709
710    macro_rules! trampoline {
711        ($name:ident, $method:ident) => {
712            /// # Safety
713            /// `ctx` must be a `*mut T` that outlives the registration and is not
714            /// aliased for the duration of the call (the executor spins
715            /// single-threaded, so no concurrent `&mut T` exists).
716            pub unsafe extern "C" fn $name<T: LifecycleCallbacks>(ctx: *mut c_void) -> u8 {
717                if ctx.is_null() {
718                    return TransitionResult::Error as u8;
719                }
720                // SAFETY: caller (`register_lifecycle_node`) set `ctx` to a live
721                // `&mut T`; the spin loop invokes this synchronously, so the
722                // reference is unique for the call.
723                let node = unsafe { &mut *(ctx as *mut T) };
724                node.$method() as u8
725            }
726        };
727    }
728
729    trampoline!(on_configure, on_configure);
730    trampoline!(on_activate, on_activate);
731    trampoline!(on_deactivate, on_deactivate);
732    trampoline!(on_cleanup, on_cleanup);
733    trampoline!(on_shutdown, on_shutdown);
734    trampoline!(on_error, on_error);
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    // ═══════════════════════════════════════════════════════════════════════
742    // Transition announcements (issue 1587)
743    // ═══════════════════════════════════════════════════════════════════════
744
745    #[cfg(feature = "lifecycle-services")]
746    #[test]
747    fn every_executed_transition_is_recorded_once() {
748        let mut sm = LifecyclePollingNodeCtx::new();
749        // SAFETY: no callbacks registered, so no FFI pointer is invoked.
750        unsafe { sm.trigger_transition(LifecycleTransition::Configure) }.expect("configure");
751
752        let ev = sm.take_announcement().expect("configure was recorded");
753        assert_eq!(ev.transition, LifecycleTransition::Configure);
754        assert_eq!(ev.start_state, LifecycleState::Unconfigured);
755        assert_eq!(ev.goal_state, LifecycleState::Inactive);
756        assert!(
757            sm.take_announcement().is_none(),
758            "one transition, one record"
759        );
760        assert_eq!(sm.take_dropped_announcements(), 0);
761    }
762
763    #[cfg(feature = "lifecycle-services")]
764    #[test]
765    fn a_rejected_transition_records_nothing() {
766        let mut sm = LifecyclePollingNodeCtx::new();
767        // Activate is illegal from Unconfigured: no callback runs and no
768        // state changes, so there is nothing to announce.
769        // SAFETY: no callbacks registered.
770        assert!(unsafe { sm.trigger_transition(LifecycleTransition::Activate) }.is_err());
771        assert!(sm.take_announcement().is_none());
772        assert_eq!(sm.take_dropped_announcements(), 0);
773    }
774
775    #[cfg(feature = "lifecycle-services")]
776    #[test]
777    fn an_undrained_queue_counts_its_losses_instead_of_hiding_them() {
778        let mut sm = LifecyclePollingNodeCtx::new();
779        // Configure/Cleanup cycles indefinitely between Unconfigured and
780        // Inactive, so this drives more transitions than the queue holds
781        // without ever draining it.
782        let runs = TRANSITION_ANNOUNCEMENT_QUEUE + 3;
783        for i in 0..runs {
784            let t = if i % 2 == 0 {
785                LifecycleTransition::Configure
786            } else {
787                LifecycleTransition::Cleanup
788            };
789            // SAFETY: no callbacks registered.
790            unsafe { sm.trigger_transition(t) }.expect("legal transition");
791        }
792        let mut drained = 0;
793        while sm.take_announcement().is_some() {
794            drained += 1;
795        }
796        assert_eq!(drained, TRANSITION_ANNOUNCEMENT_QUEUE);
797        assert_eq!(
798            sm.take_dropped_announcements() as usize,
799            runs - TRANSITION_ANNOUNCEMENT_QUEUE,
800            "the overflow is COUNTED — a bounded table that discards silently is \
801             the defect the zpico reply slots already answered"
802        );
803        assert_eq!(
804            sm.take_dropped_announcements(),
805            0,
806            "read-and-clear: a burst is reported once, not every spin thereafter"
807        );
808    }
809
810    // ═══════════════════════════════════════════════════════════════════════
811    // Safe LifecycleCallbacks trait (issue 0335 / phase-317)
812    // ═══════════════════════════════════════════════════════════════════════
813
814    struct DemoNode {
815        configured: bool,
816    }
817    impl LifecycleCallbacks for DemoNode {
818        fn on_configure(&mut self) -> TransitionResult {
819            self.configured = true;
820            TransitionResult::Success
821        }
822        fn on_error(&mut self) -> TransitionResult {
823            TransitionResult::Error
824        }
825        // on_activate / on_deactivate / on_cleanup / on_shutdown use the defaults.
826    }
827
828    #[test]
829    fn trampoline_dispatches_to_trait_impl_and_defaults() {
830        let mut n = DemoNode { configured: false };
831        let ctx = &mut n as *mut DemoNode as *mut c_void;
832
833        // Overridden method runs and mutates through the recovered &mut.
834        let rc = unsafe { trampolines::on_configure::<DemoNode>(ctx) };
835        assert_eq!(rc, TransitionResult::Success as u8);
836        assert!(n.configured);
837
838        // Defaulted method returns Success without an override.
839        let rc = unsafe { trampolines::on_activate::<DemoNode>(&mut n as *mut _ as *mut c_void) };
840        assert_eq!(rc, TransitionResult::Success as u8);
841
842        // Overridden on_error returns Error.
843        let rc = unsafe { trampolines::on_error::<DemoNode>(&mut n as *mut _ as *mut c_void) };
844        assert_eq!(rc, TransitionResult::Error as u8);
845
846        // Null ctx is Error, never a deref.
847        let rc = unsafe { trampolines::on_configure::<DemoNode>(core::ptr::null_mut()) };
848        assert_eq!(rc, TransitionResult::Error as u8);
849    }
850
851    #[test]
852    fn ctx_state_machine_drives_trait_through_a_transition() {
853        // The seam `register_lifecycle_node` builds on: set_context + register a
854        // monomorphized trampoline, then a transition dispatches to the trait.
855        let mut n = DemoNode { configured: false };
856        let mut sm = LifecyclePollingNodeCtx::new();
857        sm.set_context(&mut n as *mut DemoNode as *mut c_void);
858        sm.register(
859            LifecycleCallbackSlot::Configure,
860            Some(trampolines::on_configure::<DemoNode>),
861        );
862
863        // SAFETY: `n` outlives `sm`; the transition runs synchronously here.
864        let new_state =
865            unsafe { sm.trigger_transition(LifecycleTransition::Configure) }.expect("configure");
866
867        assert!(n.configured, "the trait's on_configure ran");
868        assert_eq!(new_state, LifecycleState::Inactive);
869    }
870
871    #[test]
872    fn raw_extern_c_callbacks_drive_the_ctx_state_machine() {
873        // Issue 0335 — the raw-FFI shape the `linux/rust/lifecycle-node` example
874        // used to demonstrate (a user hand-writing `extern "C"` callbacks against
875        // the C-parity seam). Relocated here as automated coverage so the example
876        // can show the safe `LifecycleCallbacks` trait instead of an FFI test.
877        unsafe extern "C" fn cb_success(_ctx: *mut c_void) -> u8 {
878            TransitionResult::Success as u8
879        }
880        let mut sm = LifecyclePollingNodeCtx::new();
881        sm.register(LifecycleCallbackSlot::Configure, Some(cb_success));
882        sm.register(LifecycleCallbackSlot::Activate, Some(cb_success));
883
884        // SAFETY: the callbacks ignore the (null) context.
885        let s =
886            unsafe { sm.trigger_transition(LifecycleTransition::Configure) }.expect("configure");
887        assert_eq!(s, LifecycleState::Inactive);
888        let s = unsafe { sm.trigger_transition(LifecycleTransition::Activate) }.expect("activate");
889        assert_eq!(s, LifecycleState::Active);
890    }
891
892    // ═══════════════════════════════════════════════════════════════════════
893    // LifecyclePollingNode tests (no_std, always available)
894    // ═══════════════════════════════════════════════════════════════════════
895
896    #[test]
897    fn test_polling_node_initial_state() {
898        let node = LifecyclePollingNode::new();
899        assert_eq!(node.state(), LifecycleState::Unconfigured);
900    }
901
902    #[test]
903    fn test_polling_node_default() {
904        let node = LifecyclePollingNode::default();
905        assert_eq!(node.state(), LifecycleState::Unconfigured);
906    }
907
908    #[test]
909    fn test_polling_node_happy_path() {
910        let mut node = LifecyclePollingNode::new();
911
912        assert_eq!(node.configure().unwrap(), LifecycleState::Inactive);
913        assert_eq!(node.activate().unwrap(), LifecycleState::Active);
914        assert_eq!(node.deactivate().unwrap(), LifecycleState::Inactive);
915        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
916    }
917
918    #[test]
919    fn test_polling_node_cleanup_cycle() {
920        let mut node = LifecyclePollingNode::new();
921
922        node.configure().unwrap();
923        assert_eq!(node.cleanup().unwrap(), LifecycleState::Unconfigured);
924
925        // Can configure again
926        assert_eq!(node.configure().unwrap(), LifecycleState::Inactive);
927    }
928
929    #[test]
930    fn test_polling_node_invalid_transition() {
931        let mut node = LifecyclePollingNode::new();
932
933        let err = node.activate().unwrap_err();
934        assert_eq!(
935            err,
936            LifecycleError::InvalidTransition {
937                from: LifecycleState::Unconfigured,
938                transition: LifecycleTransition::Activate,
939            }
940        );
941    }
942
943    #[test]
944    fn test_polling_node_finalized_rejection() {
945        let mut node = LifecyclePollingNode::new();
946        node.shutdown().unwrap();
947
948        assert_eq!(node.configure().unwrap_err(), LifecycleError::NodeFinalized);
949        assert_eq!(node.shutdown().unwrap_err(), LifecycleError::NodeFinalized);
950    }
951
952    fn on_configure_success() -> TransitionResult {
953        TransitionResult::Success
954    }
955
956    fn on_configure_failure() -> TransitionResult {
957        TransitionResult::Failure
958    }
959
960    fn on_configure_error() -> TransitionResult {
961        TransitionResult::Error
962    }
963
964    #[test]
965    fn test_polling_node_callback_success() {
966        let mut node = LifecyclePollingNode::new();
967        node.register_on_configure(on_configure_success);
968
969        assert_eq!(node.configure().unwrap(), LifecycleState::Inactive);
970    }
971
972    #[test]
973    fn test_polling_node_callback_failure_rollback() {
974        let mut node = LifecyclePollingNode::new();
975        node.register_on_configure(on_configure_failure);
976
977        let err = node.configure().unwrap_err();
978        assert_eq!(
979            err,
980            LifecycleError::CallbackFailed {
981                transition: LifecycleTransition::Configure,
982                result: TransitionResult::Failure,
983            }
984        );
985        // State rolled back to Unconfigured
986        assert_eq!(node.state(), LifecycleState::Unconfigured);
987    }
988
989    #[test]
990    fn test_polling_node_callback_error() {
991        let mut node = LifecyclePollingNode::new();
992        node.register_on_configure(on_configure_error);
993
994        let err = node.configure().unwrap_err();
995        assert_eq!(
996            err,
997            LifecycleError::CallbackFailed {
998                transition: LifecycleTransition::Configure,
999                result: TransitionResult::Error,
1000            }
1001        );
1002        // State moved to ErrorProcessing
1003        assert_eq!(node.state(), LifecycleState::ErrorProcessing);
1004    }
1005
1006    #[test]
1007    fn test_polling_node_error_recovery() {
1008        let mut node = LifecyclePollingNode::new();
1009        node.register_on_configure(on_configure_error);
1010
1011        let _ = node.configure();
1012        assert_eq!(node.state(), LifecycleState::ErrorProcessing);
1013
1014        // Cannot shutdown from error processing
1015        assert!(node.shutdown().is_err());
1016
1017        // Can recover
1018        node.register_on_error(on_configure_success);
1019        let result = node.trigger_transition(LifecycleTransition::ErrorRecovery);
1020        assert_eq!(result.unwrap(), LifecycleState::Unconfigured);
1021    }
1022
1023    #[test]
1024    fn test_polling_node_bring_up() {
1025        let mut node = LifecyclePollingNode::new();
1026        assert_eq!(node.bring_up().unwrap(), LifecycleState::Active);
1027    }
1028
1029    #[test]
1030    fn test_polling_node_bring_up_stops_on_configure_failure() {
1031        let mut node = LifecyclePollingNode::new();
1032        node.register_on_configure(on_configure_failure);
1033
1034        let err = node.bring_up().unwrap_err();
1035        assert_eq!(
1036            err,
1037            LifecycleError::CallbackFailed {
1038                transition: LifecycleTransition::Configure,
1039                result: TransitionResult::Failure,
1040            }
1041        );
1042        // State is still Unconfigured, activate was never attempted
1043        assert_eq!(node.state(), LifecycleState::Unconfigured);
1044    }
1045
1046    #[test]
1047    fn test_polling_node_shutdown_from_each_state() {
1048        // From Unconfigured
1049        let mut node = LifecyclePollingNode::new();
1050        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
1051
1052        // From Inactive
1053        let mut node = LifecyclePollingNode::new();
1054        node.configure().unwrap();
1055        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
1056
1057        // From Active
1058        let mut node = LifecyclePollingNode::new();
1059        node.bring_up().unwrap();
1060        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
1061    }
1062
1063    #[test]
1064    fn test_polling_node_no_callback_defaults_success() {
1065        // Without any callbacks registered, transitions should succeed
1066        let mut node = LifecyclePollingNode::new();
1067        assert_eq!(node.configure().unwrap(), LifecycleState::Inactive);
1068        assert_eq!(node.activate().unwrap(), LifecycleState::Active);
1069        assert_eq!(node.deactivate().unwrap(), LifecycleState::Inactive);
1070        assert_eq!(node.cleanup().unwrap(), LifecycleState::Unconfigured);
1071        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
1072    }
1073
1074    fn on_shutdown_success() -> TransitionResult {
1075        TransitionResult::Success
1076    }
1077
1078    #[test]
1079    fn test_polling_node_shutdown_callback_invoked() {
1080        let mut node = LifecyclePollingNode::new();
1081        node.register_on_shutdown(on_shutdown_success);
1082
1083        // Shutdown from Unconfigured should invoke the shutdown callback
1084        assert_eq!(node.shutdown().unwrap(), LifecycleState::Finalized);
1085    }
1086
1087    // ═══════════════════════════════════════════════════════════════════════
1088    // LifecyclePollingNodeCtx tests (C FFI shape)
1089    // ═══════════════════════════════════════════════════════════════════════
1090
1091    unsafe extern "C" fn ctx_cb_success(_: *mut c_void) -> u8 {
1092        TransitionResult::Success as u8
1093    }
1094    unsafe extern "C" fn ctx_cb_failure(_: *mut c_void) -> u8 {
1095        TransitionResult::Failure as u8
1096    }
1097    unsafe extern "C" fn ctx_cb_error(_: *mut c_void) -> u8 {
1098        TransitionResult::Error as u8
1099    }
1100
1101    #[test]
1102    fn test_ctx_node_happy_path() {
1103        unsafe {
1104            let mut node = LifecyclePollingNodeCtx::new();
1105            node.register(LifecycleCallbackSlot::Configure, Some(ctx_cb_success));
1106            node.register(LifecycleCallbackSlot::Activate, Some(ctx_cb_success));
1107            node.register(LifecycleCallbackSlot::Deactivate, Some(ctx_cb_success));
1108            node.register(LifecycleCallbackSlot::Shutdown, Some(ctx_cb_success));
1109
1110            assert_eq!(
1111                node.trigger_transition(LifecycleTransition::Configure)
1112                    .unwrap(),
1113                LifecycleState::Inactive
1114            );
1115            assert_eq!(
1116                node.trigger_transition(LifecycleTransition::Activate)
1117                    .unwrap(),
1118                LifecycleState::Active
1119            );
1120            assert_eq!(
1121                node.trigger_transition(LifecycleTransition::Deactivate)
1122                    .unwrap(),
1123                LifecycleState::Inactive
1124            );
1125            assert_eq!(
1126                node.trigger_transition(LifecycleTransition::ShutdownInactive)
1127                    .unwrap(),
1128                LifecycleState::Finalized
1129            );
1130        }
1131    }
1132
1133    #[test]
1134    fn test_ctx_node_invalid_transition() {
1135        unsafe {
1136            let mut node = LifecyclePollingNodeCtx::new();
1137            let err = node
1138                .trigger_transition(LifecycleTransition::Activate)
1139                .unwrap_err();
1140            assert_eq!(
1141                err,
1142                LifecycleError::InvalidTransition {
1143                    from: LifecycleState::Unconfigured,
1144                    transition: LifecycleTransition::Activate,
1145                }
1146            );
1147            assert_eq!(node.state(), LifecycleState::Unconfigured);
1148        }
1149    }
1150
1151    #[test]
1152    fn test_ctx_node_callback_failure_rolls_back() {
1153        unsafe {
1154            let mut node = LifecyclePollingNodeCtx::new();
1155            node.register(LifecycleCallbackSlot::Configure, Some(ctx_cb_failure));
1156            assert!(
1157                node.trigger_transition(LifecycleTransition::Configure)
1158                    .is_err()
1159            );
1160            assert_eq!(node.state(), LifecycleState::Unconfigured);
1161        }
1162    }
1163
1164    #[test]
1165    fn test_ctx_node_callback_error_enters_error_processing() {
1166        unsafe {
1167            let mut node = LifecyclePollingNodeCtx::new();
1168            node.register(LifecycleCallbackSlot::Configure, Some(ctx_cb_error));
1169            assert!(
1170                node.trigger_transition(LifecycleTransition::Configure)
1171                    .is_err()
1172            );
1173            assert_eq!(node.state(), LifecycleState::ErrorProcessing);
1174        }
1175    }
1176
1177    #[test]
1178    fn test_ctx_node_finalized_rejects() {
1179        unsafe {
1180            let mut node = LifecyclePollingNodeCtx::new();
1181            node.finalize();
1182            let err = node
1183                .trigger_transition(LifecycleTransition::Configure)
1184                .unwrap_err();
1185            assert_eq!(err, LifecycleError::NodeFinalized);
1186        }
1187    }
1188
1189    #[test]
1190    fn test_ctx_node_context_passed() {
1191        use core::sync::atomic::{AtomicU32, Ordering};
1192        static SEEN: AtomicU32 = AtomicU32::new(0);
1193        unsafe extern "C" fn cb_record(ctx: *mut c_void) -> u8 {
1194            SEEN.store(ctx as usize as u32, Ordering::Relaxed);
1195            TransitionResult::Success as u8
1196        }
1197
1198        unsafe {
1199            let mut node = LifecyclePollingNodeCtx::new();
1200            node.set_context(0xBEEFu32 as usize as *mut c_void);
1201            node.register(LifecycleCallbackSlot::Configure, Some(cb_record));
1202            let _ = node.trigger_transition(LifecycleTransition::Configure);
1203            assert_eq!(SEEN.load(Ordering::Relaxed), 0xBEEF);
1204        }
1205    }
1206
1207    #[test]
1208    fn test_ctx_node_clear_callbacks_resets() {
1209        unsafe {
1210            let mut node = LifecyclePollingNodeCtx::new();
1211            node.set_context(core::ptr::dangling_mut::<c_void>());
1212            node.register(LifecycleCallbackSlot::Configure, Some(ctx_cb_success));
1213            node.clear_callbacks();
1214            assert!(node.context().is_null());
1215            // With no callback, transition still succeeds (default = Success).
1216            assert_eq!(
1217                node.trigger_transition(LifecycleTransition::Configure)
1218                    .unwrap(),
1219                LifecycleState::Inactive
1220            );
1221        }
1222    }
1223}