Skip to main content

nros_node/executor/
action.rs

1//! Action server and client registration on the executor and handle types.
2
3use core::marker::PhantomData;
4
5use nros_core::RosAction;
6use nros_rmw::{ActionEndpointHashes, ActionInfo, QoSProfile, ServiceInfo, Session, TopicInfo};
7
8#[allow(unused_imports)]
9use crate::rmw_type_registry::{MessageForRmw, register_type};
10
11use super::{
12    action_core::{ActionClientCore, ActionServerCore, RawActiveGoal},
13    arena::{
14        ActionClientCallbackEntry, ActionClientRawArenaEntry, ActionServerArenaEntry,
15        ActionServerRawArenaEntry, BufferStrategy, CallbackMeta, EntryKind, TraceName,
16        action_client_callback_try_process, action_client_raw_try_process,
17        action_server_raw_try_process, action_server_try_process, always_ready,
18        as_active_goal_count, as_complete_goal, as_expire_goals, as_for_each_active_goal,
19        as_goal_exists, as_publish_feedback, as_raw_active_goal_count, as_raw_complete_goal,
20        as_raw_expire_goals, as_raw_for_each_active_goal, as_raw_goal_exists,
21        as_raw_publish_feedback, as_raw_set_goal_status, as_set_goal_status, buffered_region_size,
22        drop_entry, no_pre_sample,
23    },
24    handles::{ActionServer, ActiveGoal},
25    spin::Executor,
26    spsc_ring::SpscRing,
27    triple_buffer::TripleBuffer,
28    types::{
29        HandleId, InvocationMode, NodeError, RawAcceptedCallback, RawCancelCallback,
30        RawCancelResponseCallback, RawFeedbackCallback, RawGoalCallback, RawGoalResponseCallback,
31        RawResultCallback,
32    },
33};
34
35/// How many zenoh queryables ONE action server costs.
36///
37/// An action is three services on the wire (`send_goal`, `cancel_goal`,
38/// `get_result`; the feedback and status channels are topics, not queryables),
39/// so a launch file declaring one action server is declaring THREE entries in
40/// the backend's queryable table. A consumer sizing that table from a model
41/// must multiply, and this is the multiplier.
42///
43/// Defined here rather than in the consumer for the reason measured before:
44/// a count restated where it cannot be derived drifts from the code that
45/// decides it. `check-infra-queryable-counts` ties this to the distinct
46/// `create_service` calls below, so adding a fourth action channel fails the
47/// gate instead of silently under-sizing every image that declares an action.
48pub const ACTION_SERVER_QUERYABLES: usize = 3;
49
50/// Publishers an action SERVER creates, per action, beyond anything the author
51/// declares: the feedback topic and the status topic (`create_publisher` calls
52/// below). A consumer sizing the backend's publisher table from a declaration
53/// must add these, because an `ENTITIES action_server:...` spec declares ONE
54/// entity and costs two publisher slots.
55///
56/// Same rule as [`ACTION_SERVER_QUERYABLES`], and defined for the same reason:
57/// the number lives next to the calls that decide it, so it cannot drift from
58/// them without failing the gate that ties the two together.
59pub const ACTION_SERVER_PUBLISHERS: usize = 2;
60
61/// Subscriptions an action CLIENT creates, per action: the feedback topic.
62/// Status is polled through the result client rather than subscribed, so this
63/// is one and not two -- check the `create_subscription` calls below before
64/// changing it, not this comment.
65///
66/// The same under-sizing hazard as the two above: `ENTITIES action_client:...`
67/// is one declared entity and one subscriber slot that nothing else accounts
68/// for.
69pub const ACTION_CLIENT_SUBSCRIPTIONS: usize = 1;
70
71/// Service CLIENTS an action CLIENT creates, per action: `send_goal`,
72/// `cancel_goal` and `get_result` (the `create_client` calls below).
73///
74/// The liveliness pool needs it. Every service client the session
75/// opens declares one liveliness token (`create_client` in the zenoh shim), so
76/// an `action_client` spec is one declared entity and THREE tokens; a pool
77/// sized from the raw count is short for every image with an action client.
78/// Held to the distinct `create_client(&<name>_info` channels by
79/// `check-infra-queryable-counts`, same rule as the three above.
80pub const ACTION_CLIENT_SERVICE_CLIENTS: usize = 3;
81
82// ============================================================================
83// Raw action registration specs
84// ============================================================================
85
86/// Inputs for raw (untyped) action-server registration.
87///
88/// Collapses the runtime arguments shared by the
89/// `register_action_server_raw*` family. Buffer sizes / max-goals stay
90/// as const-generic turbofish parameters on the registration methods.
91pub struct RawActionServerSpec<'a> {
92    /// `None` registers on the executor's own node; `Some(id)` routes
93    /// the server's 5 underlying handles (send_goal / cancel_goal /
94    /// get_result servers + feedback / status publishers) through the
95    /// named Node's session.
96    pub node_id: Option<super::node_record::NodeId>,
97    pub action_name: &'a str,
98    pub type_name: &'a str,
99    /// The ACTION's own hash; feeds `ActionInfo` only. The endpoints are keyed
100    /// on [`hashes`](Self::hashes).
101    pub type_hash: &'a str,
102    /// The hash each of the five endpoints is keyed on.
103    pub hashes: ActionEndpointHashes<'a>,
104    /// QoS for the action's three underlying service servers (send_goal
105    /// / cancel_goal / get_result). The feedback + status
106    /// publishers keep their own profiles. Use
107    /// [`QoSProfile::services_default`] for the rclc-compatible default.
108    pub qos: QoSProfile,
109    pub goal_callback: RawGoalCallback,
110    pub cancel_callback: RawCancelCallback,
111    pub accepted_callback: Option<RawAcceptedCallback>,
112    pub context: *mut core::ffi::c_void,
113}
114
115/// Inputs for raw (untyped) action-client registration.
116///
117/// Collapses the runtime arguments shared by the
118/// `register_action_client_raw*` family. Buffer sizes stay as
119/// const-generic turbofish parameters on the registration methods.
120pub struct RawActionClientSpec<'a> {
121    /// `None` registers on the executor's own node; `Some(id)` routes
122    /// the client's 4 underlying handles (send_goal / cancel_goal /
123    /// get_result service clients + feedback subscriber) through the
124    /// named Node's session.
125    pub node_id: Option<super::node_record::NodeId>,
126    pub action_name: &'a str,
127    pub type_name: &'a str,
128    /// The ACTION's own hash; feeds `ActionInfo` only. The endpoints are keyed
129    /// on [`hashes`](Self::hashes).
130    pub type_hash: &'a str,
131    /// The hash each endpoint a client uses is keyed on.
132    pub hashes: ActionEndpointHashes<'a>,
133    pub goal_response_callback: Option<RawGoalResponseCallback>,
134    pub feedback_callback: Option<RawFeedbackCallback>,
135    pub result_callback: Option<RawResultCallback>,
136    /// `Some` makes the executor take this client's cancel
137    /// replies and deliver them here. `None` leaves them for the caller's own
138    /// reader. See [`RawCancelResponseCallback`].
139    pub cancel_response_callback: Option<RawCancelResponseCallback>,
140    pub context: *mut core::ffi::c_void,
141}
142
143// ============================================================================
144// Action server registration
145// ============================================================================
146
147impl<'s> Executor<'s> {
148    /// Register an action server with goal/cancel callbacks.
149    ///
150    /// The executor automatically dispatches:
151    /// - Goal acceptance via `goal_callback`
152    /// - Cancel requests via `cancel_callback`
153    /// - Result serving for completed goals
154    ///
155    /// Use the returned [`ActionServerHandle`] to publish feedback and complete goals.
156    ///
157    /// Uses default buffer sizes and max 4 concurrent goals.
158    pub fn register_action_server<A, GoalF, CancelF>(
159        &mut self,
160        action_name: &str,
161        goal_callback: GoalF,
162        cancel_callback: CancelF,
163    ) -> Result<ActionServerHandle<A>, NodeError>
164    where
165        A: RosAction + 'static,
166        A::Goal: Clone + MessageForRmw,
167        A::Result: Clone + Default + MessageForRmw,
168        A::Feedback: MessageForRmw,
169        A::SendGoalRequest: MessageForRmw,
170        A::SendGoalResponse: MessageForRmw,
171        A::GetResultRequest: MessageForRmw,
172        A::GetResultResponse: MessageForRmw,
173        A::FeedbackMessage: MessageForRmw,
174        GoalF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse + 'static,
175        CancelF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse
176            + 'static,
177    {
178        self.register_action_server_sized::<A, GoalF, CancelF, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, 4>(
179            action_name,
180            goal_callback,
181            cancel_callback,
182        )
183    }
184
185    /// Register an action server with custom buffer sizes.
186    pub fn register_action_server_sized<
187        A,
188        GoalF,
189        CancelF,
190        const GOAL_BUF: usize,
191        const RESULT_BUF: usize,
192        const FEEDBACK_BUF: usize,
193        const MAX_GOALS: usize,
194    >(
195        &mut self,
196        action_name: &str,
197        goal_callback: GoalF,
198        cancel_callback: CancelF,
199    ) -> Result<ActionServerHandle<A>, NodeError>
200    where
201        A: RosAction + 'static,
202        A::Goal: Clone + MessageForRmw,
203        A::Result: Clone + Default + MessageForRmw,
204        A::Feedback: MessageForRmw,
205        A::SendGoalRequest: MessageForRmw,
206        A::SendGoalResponse: MessageForRmw,
207        A::GetResultRequest: MessageForRmw,
208        A::GetResultResponse: MessageForRmw,
209        A::FeedbackMessage: MessageForRmw,
210        GoalF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse + 'static,
211        CancelF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse
212            + 'static,
213    {
214        // Phase 212.K.7.6.b + K.7.7.c — under `rmw-cyclonedds`, register
215        // the user-facing message types AND the five action-protocol
216        // envelope types with the cyclonedds runtime registry before
217        // creating the underlying service / topic entities. No-op for
218        // other RMWs. See `Node::create_action_server_sized` for the
219        // detailed rationale.
220        register_type::<A::Goal>()?;
221        register_type::<A::Result>()?;
222        register_type::<A::Feedback>()?;
223        register_type::<A::SendGoalRequest>()?;
224        register_type::<A::SendGoalResponse>()?;
225        register_type::<A::GetResultRequest>()?;
226        register_type::<A::GetResultResponse>()?;
227        register_type::<A::FeedbackMessage>()?;
228        // Phase 244 E3 (RFC-0044) — register the fixed `action_msgs` protocol
229        // types (CancelGoal_{Request,Response}, GoalStatusArray) the cancel /
230        // status plumbing serializes. The generated `impl RosAction` overrides
231        // this (default = no-op); previously every example hand-registered these
232        // three under `#[cfg(feature = "rmw-cyclonedds")]`.
233        A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
234        type Entry<
235            A,
236            GoalF,
237            CancelF,
238            const GB: usize,
239            const RB: usize,
240            const FB: usize,
241            const MG: usize,
242        > = ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>;
243
244        let slot = self.next_entry_slot()?;
245
246        // Create the action server entities (same logic as Node::create_action_server_sized)
247        let action_info = ActionInfo::new(action_name, A::ACTION_NAME, A::ACTION_HASH);
248
249        // ROS 2 matches the action's send_goal / get_result services by their
250        // per-channel service types (`<Action>_SendGoal` / `<Action>_GetResult`)
251        // and the feedback topic by `<Action>_FeedbackMessage` — not the bare
252        // action type. Pass those so a real `rcl_action` peer discovers us.
253        let send_goal_type = super::action_core::action_service_base_type(
254            <A::SendGoalRequest as nros_core::RosMessage>::TYPE_NAME,
255            A::ACTION_NAME,
256        );
257        let get_result_type = super::action_core::action_service_base_type(
258            <A::GetResultRequest as nros_core::RosMessage>::TYPE_NAME,
259            A::ACTION_NAME,
260        );
261        let feedback_type = <A::FeedbackMessage as nros_core::RosMessage>::TYPE_NAME;
262
263        let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
264        let send_goal_info = ServiceInfo::new(
265            &send_goal_keyexpr,
266            send_goal_type,
267            A::SEND_GOAL_SERVICE_HASH,
268        )
269        .with_domain(self.domain_id);
270        let send_goal_server = self
271            .session
272            .create_service(&send_goal_info, QoSProfile::services_default())
273            .map_err(NodeError::Transport)?;
274
275        let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
276        let cancel_goal_info = ServiceInfo::new(
277            &cancel_goal_keyexpr,
278            "action_msgs::srv::dds_::CancelGoal_",
279            A::CANCEL_GOAL_SERVICE_HASH,
280        )
281        .with_domain(self.domain_id);
282        let cancel_goal_server = self
283            .session
284            .create_service(&cancel_goal_info, QoSProfile::services_default())
285            .map_err(NodeError::Transport)?;
286
287        let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
288        let get_result_info = ServiceInfo::new(
289            &get_result_keyexpr,
290            get_result_type,
291            A::GET_RESULT_SERVICE_HASH,
292        )
293        .with_domain(self.domain_id);
294        let get_result_server = self
295            .session
296            .create_service(&get_result_info, QoSProfile::services_default())
297            .map_err(NodeError::Transport)?;
298
299        let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
300        let feedback_topic = TopicInfo::new(
301            &feedback_keyexpr,
302            feedback_type,
303            <A::FeedbackMessage as nros_core::RosMessage>::TYPE_HASH,
304        )
305        .with_domain(self.domain_id);
306        let feedback_publisher = self
307            .session
308            .create_publisher(&feedback_topic, QoSProfile::QOS_PROFILE_DEFAULT)
309            .map_err(NodeError::Transport)?;
310
311        let status_keyexpr: heapless::String<256> = action_info.status_key();
312        let status_topic = TopicInfo::new(
313            &status_keyexpr,
314            "action_msgs::msg::dds_::GoalStatusArray_",
315            A::STATUS_MESSAGE_HASH,
316        )
317        .with_domain(self.domain_id);
318        let status_publisher = self
319            .session
320            .create_publisher(&status_topic, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
321            .map_err(NodeError::Transport)?;
322
323        let server = ActionServer {
324            core: super::action_core::ActionServerCore {
325                send_goal_server,
326                cancel_goal_server,
327                get_result_server,
328                feedback_publisher,
329                status_publisher,
330                active_goals: heapless::Vec::new(),
331                completed_results: heapless::Vec::new(),
332                pending_get_results: heapless::Vec::new(),
333                result_slab: [0u8; RESULT_BUF],
334                result_slab_used: 0,
335                goal_buffer: [0u8; GOAL_BUF],
336                feedback_buffer: [0u8; FEEDBACK_BUF],
337                cancel_buffer: [0u8; 256],
338            },
339            typed_goals: heapless::Vec::new(),
340            completed_goals: heapless::Vec::new(),
341        };
342
343        let offset = self
344            .arena_alloc::<Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>(
345            )?;
346
347        unsafe {
348            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
349            let entry_ptr = arena_ptr.add(offset)
350                as *mut Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>;
351            core::ptr::write(
352                entry_ptr,
353                Entry {
354                    server,
355                    goal_callback,
356                    cancel_callback,
357                },
358            );
359        }
360
361        let meta = CallbackMeta {
362            offset,
363            kind: EntryKind::ActionServer,
364            arena_len: super::arena::ArenaLen::UNRECORDED,
365            has_data: always_ready,
366            pre_sample: no_pre_sample,
367            invocation: InvocationMode::Always,
368            try_process: action_server_try_process::<
369                A,
370                GoalF,
371                CancelF,
372                GOAL_BUF,
373                RESULT_BUF,
374                FEEDBACK_BUF,
375                MAX_GOALS,
376            >,
377            drop_fn: drop_entry::<
378                Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
379            >,
380        };
381        self.emplace_entry(slot, meta, TraceName::Text(action_name));
382
383        Ok(ActionServerHandle {
384            entry_index: slot,
385            publish_feedback_fn: as_publish_feedback::<
386                A,
387                GoalF,
388                CancelF,
389                GOAL_BUF,
390                RESULT_BUF,
391                FEEDBACK_BUF,
392                MAX_GOALS,
393            >,
394            complete_goal_fn: as_complete_goal::<
395                A,
396                GoalF,
397                CancelF,
398                GOAL_BUF,
399                RESULT_BUF,
400                FEEDBACK_BUF,
401                MAX_GOALS,
402            >,
403            set_goal_status_fn: as_set_goal_status::<
404                A,
405                GoalF,
406                CancelF,
407                GOAL_BUF,
408                RESULT_BUF,
409                FEEDBACK_BUF,
410                MAX_GOALS,
411            >,
412            active_goal_count_fn: as_active_goal_count::<
413                A,
414                GoalF,
415                CancelF,
416                GOAL_BUF,
417                RESULT_BUF,
418                FEEDBACK_BUF,
419                MAX_GOALS,
420            >,
421            goal_exists_fn: as_goal_exists::<
422                A,
423                GoalF,
424                CancelF,
425                GOAL_BUF,
426                RESULT_BUF,
427                FEEDBACK_BUF,
428                MAX_GOALS,
429            >,
430            expire_goals_fn: as_expire_goals::<
431                A,
432                GoalF,
433                CancelF,
434                GOAL_BUF,
435                RESULT_BUF,
436                FEEDBACK_BUF,
437                MAX_GOALS,
438            >,
439            for_each_active_goal_fn: as_for_each_active_goal::<
440                A,
441                GoalF,
442                CancelF,
443                GOAL_BUF,
444                RESULT_BUF,
445                FEEDBACK_BUF,
446                MAX_GOALS,
447            >,
448            _phantom: PhantomData,
449        })
450    }
451}
452
453// ============================================================================
454// Handle types for arena-registered action server
455// ============================================================================
456
457/// Handle to an action server registered in the executor's arena.
458///
459/// Returned by [`Executor::register_action_server()`]. Provides methods
460/// to interact with the server (publish feedback, complete goals) while the
461/// executor automatically handles goal acceptance, cancel requests, and
462/// result serving during [`spin_once()`](Executor::spin_once).
463#[allow(clippy::type_complexity)]
464pub struct ActionServerHandle<A: RosAction> {
465    pub(crate) entry_index: usize,
466    publish_feedback_fn:
467        unsafe fn(*mut u8, &nros_core::GoalUuid, &A::Feedback) -> Result<(), NodeError>,
468    complete_goal_fn: unsafe fn(
469        *mut u8,
470        &nros_core::GoalUuid,
471        nros_core::GoalStatusCode,
472        A::Result,
473    ) -> Result<(), NodeError>,
474    set_goal_status_fn: unsafe fn(*mut u8, &nros_core::GoalUuid, nros_core::GoalStatusCode),
475    active_goal_count_fn: unsafe fn(*const u8) -> usize,
476    goal_exists_fn: unsafe fn(*const u8, &nros_core::GoalUuid) -> bool,
477    expire_goals_fn: unsafe fn(*mut u8) -> usize,
478    for_each_active_goal_fn: unsafe fn(*const u8, &mut dyn FnMut(&ActiveGoal<A>)),
479    _phantom: PhantomData<A>,
480}
481
482impl<A: RosAction> Clone for ActionServerHandle<A> {
483    fn clone(&self) -> Self {
484        *self
485    }
486}
487
488impl<A: RosAction> Copy for ActionServerHandle<A> {}
489
490impl<A: RosAction> ActionServerHandle<A> {
491    /// Get the [`HandleId`] for this action server.
492    ///
493    /// Used with `Trigger::One` or `HandleSet` for trigger configuration.
494    pub fn handle_id(&self) -> HandleId {
495        HandleId::for_owned_slot(self.entry_index)
496    }
497
498    /// Publish feedback for an active goal.
499    ///
500    /// Serialises the feedback message and sends it to all clients
501    /// monitoring this goal. Returns an error if the handle slot has
502    /// been removed from the executor.
503    pub fn publish_feedback(
504        &self,
505        executor: &mut Executor,
506        goal_id: &nros_core::GoalUuid,
507        feedback: &A::Feedback,
508    ) -> Result<(), NodeError> {
509        let meta = executor.entries[self.entry_index]
510            .as_ref()
511            .ok_or(NodeError::BufferTooSmall)?;
512        let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
513        unsafe {
514            let data_ptr = arena_ptr.add(meta.offset);
515            (self.publish_feedback_fn)(data_ptr, goal_id, feedback)
516        }
517    }
518
519    /// Complete a goal with a terminal status and result payload.
520    ///
521    /// The goal is moved from the active set to the completed-results
522    /// slab. Clients waiting on a result will receive the response.
523    /// `status` should be one of `Succeeded`, `Aborted`, or `Canceled`.
524    ///
525    /// # Errors
526    ///
527    /// `NodeError::BufferTooSmall` when the handle slot has been removed from
528    /// the executor, or when the serialized result exceeds the server's
529    /// `RESULT_BUF` and so cannot be retained for a later `get_result` (issue
530    /// 0796 — this used to return `()` and swallow both).
531    /// Terminate `goal_id` as SUCCEEDED.
532    ///
533    /// The three terminal verbs (`succeed` / `abort` / `canceled`) name the
534    /// ACTION SPEC's terminal states, which is also what rclcpp_action's
535    /// `ServerGoalHandle` spells them: `succeed(result)`, `abort(result)`,
536    /// `canceled(result)` — and, since the rename, what C
537    /// (`rclc_action_canceled`) and C++ (`ActionServer<A>::canceled`) spell
538    /// them too. They take the goal ID rather than hanging off a
539    /// handle because a goal here lives in a fixed-capacity arena and is named
540    /// by its UUID — see the `divergence` row for why neither client library's
541    /// ownership model is available without an allocator.
542    ///
543    /// `complete_goal` remains the general form for a status computed at
544    /// runtime.
545    pub fn succeed(
546        &self,
547        executor: &mut Executor,
548        goal_id: &nros_core::GoalUuid,
549        result: A::Result,
550    ) -> Result<(), NodeError> {
551        self.complete_goal(
552            executor,
553            goal_id,
554            nros_core::GoalStatusCode::Succeeded,
555            result,
556        )
557    }
558
559    /// Terminate `goal_id` as ABORTED. See [`Self::succeed`].
560    pub fn abort(
561        &self,
562        executor: &mut Executor,
563        goal_id: &nros_core::GoalUuid,
564        result: A::Result,
565    ) -> Result<(), NodeError> {
566        self.complete_goal(
567            executor,
568            goal_id,
569            nros_core::GoalStatusCode::Aborted,
570            result,
571        )
572    }
573
574    /// Terminate `goal_id` as CANCELED. See [`Self::succeed`].
575    ///
576    /// This was `cancel`, and the argument for that spelling
577    /// lived on the `cancel` alias that has since been retired. It loses to the
578    /// drop-in claim: C spells it
579    /// `rclc_action_canceled`, rclcpp_action spells it
580    /// `ServerGoalHandle::canceled`, and Rust was the only one of the three
581    /// disagreeing — over a naming preference with no platform reason behind
582    /// it (the adoption rule: a rename is cheap, a surface our own languages disagree
583    /// about is not).
584    pub fn canceled(
585        &self,
586        executor: &mut Executor,
587        goal_id: &nros_core::GoalUuid,
588        result: A::Result,
589    ) -> Result<(), NodeError> {
590        self.complete_goal(
591            executor,
592            goal_id,
593            nros_core::GoalStatusCode::Canceled,
594            result,
595        )
596    }
597
598    pub fn complete_goal(
599        &self,
600        executor: &mut Executor,
601        goal_id: &nros_core::GoalUuid,
602        status: nros_core::GoalStatusCode,
603        result: A::Result,
604    ) -> Result<(), NodeError> {
605        let meta = executor.entries[self.entry_index]
606            .as_ref()
607            .ok_or(NodeError::BufferTooSmall)?;
608        let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
609        unsafe {
610            let data_ptr = arena_ptr.add(meta.offset);
611            (self.complete_goal_fn)(data_ptr, goal_id, status, result)
612        }
613    }
614
615    /// Update a goal's status without completing it.
616    ///
617    /// Use this to transition a goal to `Executing` or `Canceling`
618    /// while it is still active. To finish a goal, use [`complete_goal`](Self::complete_goal).
619    pub fn set_goal_status(
620        &self,
621        executor: &mut Executor,
622        goal_id: &nros_core::GoalUuid,
623        status: nros_core::GoalStatusCode,
624    ) {
625        if let Some(meta) = executor.entries[self.entry_index].as_ref() {
626            let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
627            unsafe {
628                let data_ptr = arena_ptr.add(meta.offset);
629                (self.set_goal_status_fn)(data_ptr, goal_id, status);
630            }
631        }
632    }
633
634    /// Get the number of currently active goals.
635    ///
636    /// Returns 0 if the action server handle has been removed from the executor.
637    pub fn active_goal_count(&self, executor: &Executor) -> usize {
638        match executor.entries[self.entry_index].as_ref() {
639            Some(meta) => {
640                let arena_ptr = executor.arena.as_ptr() as *const u8;
641                unsafe {
642                    let data_ptr = arena_ptr.add(meta.offset);
643                    (self.active_goal_count_fn)(data_ptr)
644                }
645            }
646            None => 0,
647        }
648    }
649
650    /// Is `goal_id` a goal this server still knows about?
651    ///
652    /// rcl's `rcl_action_server_goal_exists`, and the Rust half of the ledger
653    /// row `c:action_server_goal_exists`. TRUE while the goal is active AND
654    /// while its completed result is still retained, which is a strictly wider
655    /// window than `goal_status` reports — see
656    /// [`ActionServerCore::goal_exists`](crate::executor::ffi::ActionServerCoreFfi::goal_exists).
657    ///
658    /// Returns `false` if the handle slot has been removed from the executor,
659    /// which is the same answer a caller wants there: nothing on this server
660    /// knows the goal any more.
661    pub fn goal_exists(&self, executor: &Executor, goal_id: &nros_core::GoalUuid) -> bool {
662        match executor.entries[self.entry_index].as_ref() {
663            Some(meta) => {
664                let arena_ptr = executor.arena.as_ptr() as *const u8;
665                unsafe {
666                    let data_ptr = arena_ptr.add(meta.offset);
667                    (self.goal_exists_fn)(data_ptr, goal_id)
668                }
669            }
670            None => false,
671        }
672    }
673
674    /// Eagerly reclaim every completed result whose `get_result` reply has
675    /// already been sent — ledger row `c:action_expire_goals`.
676    ///
677    /// Returns the number of entries reclaimed. rcl's `rcl_action_expire_goals`
678    /// is the same capability under a CLOCK: it reclaims goals whose
679    /// `result_timeout` has elapsed and reports which. Ours has no clock — the
680    /// `no_std` core takes no time source — so the trigger is the
681    /// caller, and reclamation is otherwise on demand inside `complete_goal`.
682    /// Calling this is OPTIONAL; a server that never does still runs forever.
683    pub fn expire_goals(&self, executor: &mut Executor) -> usize {
684        match executor.entries[self.entry_index].as_ref() {
685            Some(meta) => {
686                let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
687                unsafe {
688                    let data_ptr = arena_ptr.add(meta.offset);
689                    (self.expire_goals_fn)(data_ptr)
690                }
691            }
692            None => 0,
693        }
694    }
695
696    /// Iterate over all currently active goals.
697    ///
698    /// Calls `f` for each goal that has been accepted but not yet
699    /// completed. Useful for monitoring progress or canceling stale goals.
700    pub fn for_each_active_goal(&self, executor: &Executor, mut f: impl FnMut(&ActiveGoal<A>)) {
701        if let Some(meta) = executor.entries[self.entry_index].as_ref() {
702            let arena_ptr = executor.arena.as_ptr() as *const u8;
703            unsafe {
704                let data_ptr = arena_ptr.add(meta.offset);
705                (self.for_each_active_goal_fn)(data_ptr, &mut f);
706            }
707        }
708    }
709}
710
711// ============================================================================
712// Raw (untyped) action server registration
713// ============================================================================
714
715impl<'s> Executor<'s> {
716    /// Register a raw action server with raw-bytes callbacks.
717    ///
718    /// Unlike [`register_action_server()`](Executor::register_action_server), this does
719    /// not require `RosAction` — the goal/cancel callbacks receive raw CDR
720    /// bytes. This is used by the C API thin wrapper.
721    ///
722    /// `type_name` and `type_hash` identify the action type for key expression
723    /// construction and liveliness tokens.
724    #[doc(hidden)]
725    #[allow(clippy::too_many_arguments)]
726    pub(crate) fn register_action_server_raw(
727        &mut self,
728        spec: RawActionServerSpec<'_>,
729    ) -> Result<ActionServerRawHandle, NodeError> {
730        self.register_action_server_raw_sized::<{ crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }, 4>(
731            spec,
732        )
733    }
734
735    /// Register a raw action server with custom buffer sizes.
736    ///
737    /// `spec.node_id` selects the target: `None` registers on the
738    /// executor's own node, `Some(id)` routes the server's 5 underlying
739    /// handles through the named Node's session.
740    /// `spec.qos` applies to the action's three underlying service
741    /// servers (send_goal / cancel_goal / get_result); the
742    /// feedback + status publishers keep their own profiles.
743    #[doc(hidden)]
744    pub fn register_action_server_raw_sized<
745        const GOAL_BUF: usize,
746        const RESULT_BUF: usize,
747        const FEEDBACK_BUF: usize,
748        const MAX_GOALS: usize,
749    >(
750        &mut self,
751        spec: RawActionServerSpec<'_>,
752    ) -> Result<ActionServerRawHandle, NodeError> {
753        let RawActionServerSpec {
754            node_id,
755            action_name,
756            type_name,
757            type_hash,
758            hashes,
759            qos,
760            goal_callback,
761            cancel_callback,
762            accepted_callback,
763            context,
764        } = spec;
765
766        type Entry<const GB: usize, const RB: usize, const FB: usize, const MG: usize> =
767            ActionServerRawArenaEntry<GB, RB, FB, MG>;
768
769        let slot = self.next_entry_slot()?;
770
771        let action_info = ActionInfo::new(action_name, type_name, type_hash);
772        // Issue 0656 — capture the domain BEFORE the session borrow below, for
773        // the same reason `node_name`/`ns` are cloned here: the `&mut session`
774        // in the create scope would otherwise conflict with `&self`.
775        let domain_id = self.domain_id;
776        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
777
778        // Thread node identity through each underlying ServiceInfo /
779        // TopicInfo so the Zenoh shim declares a liveliness token for
780        // each entity. Without `with_node_name`,
781        // `declare_entity_liveliness` short-circuits and
782        // `wait_for_action_server` has nothing to find — same fix as
783        // `Node::create_action_server_sized` (commit ea5e80b4).
784        // All 5 session-create calls grouped into one scope so the
785        // mutable session borrow drops before arena alloc below.
786        let (
787            send_goal_server,
788            cancel_goal_server,
789            get_result_server,
790            feedback_publisher,
791            status_publisher,
792        ) = {
793            // phase-338 W3 — ROS 2 matches these by their PER-CHANNEL types, not
794            // the bare action type. The typed path derives them from
795            // `A::SendGoalRequest::TYPE_NAME`; the raw path has only the bare
796            // type, and advertising it here left send_goal / get_result /
797            // feedback undiscoverable, so every goal timed out.
798            // Issue 2360 — one scope per endpoint: each name and info dies
799            // once its endpoint exists, so the eight `heapless::String<256>`
800            // and five infos are never all live in this frame at once (they
801            // were, beside the five handles, on a 32 KiB Zephyr main stack).
802            let send_goal_server = {
803                let send_goal_type: heapless::String<256> =
804                    super::action_core::action_channel_type(type_name, "SendGoal");
805                let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
806                let mut info =
807                    ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
808                        .with_namespace(&ns)
809                        .with_domain(domain_id);
810                if !node_name.is_empty() {
811                    info = info.with_node_name(&node_name);
812                }
813                self.session_at_mut(session_idx)
814                    .ok_or(NodeError::BackendMismatch)?
815                    .create_service(&info, qos)
816                    .map_err(NodeError::Transport)?
817            };
818            let cancel_goal_server = {
819                let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
820                let mut info = ServiceInfo::new(
821                    &cancel_goal_keyexpr,
822                    "action_msgs::srv::dds_::CancelGoal_",
823                    hashes.cancel_goal,
824                )
825                .with_namespace(&ns)
826                .with_domain(domain_id);
827                if !node_name.is_empty() {
828                    info = info.with_node_name(&node_name);
829                }
830                self.session_at_mut(session_idx)
831                    .ok_or(NodeError::BackendMismatch)?
832                    .create_service(&info, qos)
833                    .map_err(NodeError::Transport)?
834            };
835            let get_result_server = {
836                let get_result_type: heapless::String<256> =
837                    super::action_core::action_channel_type(type_name, "GetResult");
838                let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
839                let mut info =
840                    ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
841                        .with_namespace(&ns)
842                        .with_domain(domain_id);
843                if !node_name.is_empty() {
844                    info = info.with_node_name(&node_name);
845                }
846                self.session_at_mut(session_idx)
847                    .ok_or(NodeError::BackendMismatch)?
848                    .create_service(&info, qos)
849                    .map_err(NodeError::Transport)?
850            };
851            let feedback_publisher = {
852                let feedback_type: heapless::String<256> =
853                    super::action_core::action_channel_type(type_name, "FeedbackMessage");
854                let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
855                let mut info = TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
856                    .with_namespace(&ns)
857                    .with_domain(domain_id);
858                if !node_name.is_empty() {
859                    info = info.with_node_name(&node_name);
860                }
861                self.session_at_mut(session_idx)
862                    .ok_or(NodeError::BackendMismatch)?
863                    .create_publisher(&info, QoSProfile::QOS_PROFILE_DEFAULT)
864                    .map_err(NodeError::Transport)?
865            };
866            let status_publisher = {
867                let status_keyexpr: heapless::String<256> = action_info.status_key();
868                let mut info = TopicInfo::new(
869                    &status_keyexpr,
870                    "action_msgs::msg::dds_::GoalStatusArray_",
871                    hashes.status,
872                )
873                .with_namespace(&ns)
874                .with_domain(domain_id);
875                if !node_name.is_empty() {
876                    info = info.with_node_name(&node_name);
877                }
878                self.session_at_mut(session_idx)
879                    .ok_or(NodeError::BackendMismatch)?
880                    .create_publisher(&info, QoSProfile::QOS_PROFILE_ACTION_STATUS_DEFAULT)
881                    .map_err(NodeError::Transport)?
882            };
883            (
884                send_goal_server,
885                cancel_goal_server,
886                get_result_server,
887                feedback_publisher,
888                status_publisher,
889            )
890        };
891
892        let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>()?;
893
894        // Issue 2360 — written in place: building the entry (and its core's
895        // buffers) as a value and moving it in kept them on this frame.
896        unsafe {
897            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
898            let entry_ptr =
899                arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>;
900            ActionServerCore::init_in_place(
901                core::ptr::addr_of_mut!((*entry_ptr).core),
902                send_goal_server,
903                cancel_goal_server,
904                get_result_server,
905                feedback_publisher,
906                status_publisher,
907            );
908            core::ptr::addr_of_mut!((*entry_ptr).goal_callback).write(goal_callback);
909            core::ptr::addr_of_mut!((*entry_ptr).cancel_callback).write(cancel_callback);
910            core::ptr::addr_of_mut!((*entry_ptr).accepted_callback).write(accepted_callback);
911            core::ptr::addr_of_mut!((*entry_ptr).context).write(context);
912            // The entry's own fields, named with no `..`: a field added to it
913            // fails here until it is written above.
914            let Entry {
915                core: _,
916                goal_callback: _,
917                cancel_callback: _,
918                accepted_callback: _,
919                context: _,
920            } = &*entry_ptr;
921        }
922
923        let meta = CallbackMeta {
924            offset,
925            kind: EntryKind::ActionServer,
926            arena_len: super::arena::ArenaLen::UNRECORDED,
927            has_data: always_ready,
928            pre_sample: no_pre_sample,
929            invocation: InvocationMode::Always,
930            try_process: action_server_raw_try_process::<
931                GOAL_BUF,
932                RESULT_BUF,
933                FEEDBACK_BUF,
934                MAX_GOALS,
935            >,
936            drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>>,
937        };
938        self.emplace_entry(slot, meta, TraceName::Text(spec.action_name));
939        self.apply_node_default_sched(slot, node_id, None);
940
941        Ok(ActionServerRawHandle {
942            entry_index: slot,
943            publish_feedback_fn: as_raw_publish_feedback::<
944                GOAL_BUF,
945                RESULT_BUF,
946                FEEDBACK_BUF,
947                MAX_GOALS,
948            >,
949            complete_goal_fn: as_raw_complete_goal::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
950            set_goal_status_fn: as_raw_set_goal_status::<
951                GOAL_BUF,
952                RESULT_BUF,
953                FEEDBACK_BUF,
954                MAX_GOALS,
955            >,
956            active_goal_count_fn: as_raw_active_goal_count::<
957                GOAL_BUF,
958                RESULT_BUF,
959                FEEDBACK_BUF,
960                MAX_GOALS,
961            >,
962            goal_exists_fn: as_raw_goal_exists::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
963            expire_goals_fn: as_raw_expire_goals::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
964            for_each_active_goal_fn: as_raw_for_each_active_goal::<
965                GOAL_BUF,
966                RESULT_BUF,
967                FEEDBACK_BUF,
968                MAX_GOALS,
969            >,
970        })
971    }
972}
973
974// ============================================================================
975// Detaching a raw action entry from the storage that owns it — issue 1496
976// ============================================================================
977
978/// The `goal_callback` a DETACHED raw action server entry carries.
979///
980/// Issue 1496 — a DETACHED entry is not a released one: detaching leaves the
981/// action server's five RMW entities advertised after the object that
982/// registered them is gone, so a `send_goal` query still reaches its entry.
983/// (`release_action_server_raw`, resolution 2, is what removes them.)
984/// What must not survive is the DISPATCH: the registered `context` is the
985/// address of the owner's storage (for the C++ sched task, the `storage_` member of
986/// a destroyed `rclcpp_action::Server<A>`), so calling the real trampoline
987/// after destruction reads freed memory.
988///
989/// This stub ignores `context` entirely and rejects. A late goal therefore
990/// gets a well-formed REJECT reply instead of a dispatch into whatever now
991/// occupies the owner's storage.
992unsafe extern "C" fn detached_goal_callback(
993    _goal_id: *const nros_core::GoalUuid,
994    _goal_data: *const u8,
995    _goal_len: usize,
996    _context: *mut core::ffi::c_void,
997) -> nros_core::GoalResponse {
998    nros_core::GoalResponse::Reject
999}
1000
1001/// The `cancel_callback` a DETACHED raw action server entry carries.
1002///
1003/// ACCEPTS, where [`detached_goal_callback`] rejects, and the asymmetry is
1004/// deliberate: accepting a cancel runs entirely inside the arena's own
1005/// `ActionServerCore` (it moves the goal to `Canceled` and replies), touching
1006/// no user state, so a client holding a goal accepted before the server was
1007/// destroyed learns that the goal ended instead of waiting for a result nobody
1008/// will ever complete. Rejecting would leave it hanging on a server that
1009/// cannot answer. This is also what the C++ sched task already does for a server
1010/// with no cancel callback installed (`cancel_callback_trampoline`).
1011unsafe extern "C" fn detached_cancel_callback(
1012    _goal_id: *const nros_core::GoalUuid,
1013    _status: nros_core::GoalStatusCode,
1014    _context: *mut core::ffi::c_void,
1015) -> nros_core::CancelResponse {
1016    nros_core::CancelResponse::Accept
1017}
1018
1019impl<'s> Executor<'s> {
1020    /// Detach a raw action SERVER's arena entry from its owner's storage —
1021    /// issue 1496.
1022    ///
1023    /// This is not a release and does not pretend to be one. The entry keeps
1024    /// its slot, its arena bytes and its five RMW entities for the executor's
1025    /// lifetime: detaching is not releasing. Resolution 2 of issue 1496 —
1026    /// [`release_action_server_raw`](Self::release_action_server_raw), over the
1027    /// arena's free list — is what gives those back; this keeps them. What it
1028    /// does is cut the one edge that outlives the owner: the registered
1029    /// `context`, and the two callbacks that dereference it.
1030    ///
1031    /// After this call the entry answers a late `send_goal` with a REJECT and a
1032    /// late `cancel_goal` with an ACCEPT (`detached_goal_callback` /
1033    /// `detached_cancel_callback`), and the post-accept hook is cleared.
1034    /// Nothing reads `context` again, so the owner's storage may die.
1035    ///
1036    /// Returns `false` when `entry_index` holds no live entry or the entry is
1037    /// not an action server; the caller should treat that as "nothing to
1038    /// detach", which is the normal state for a server that was created and
1039    /// never registered.
1040    ///
1041    /// # Safety
1042    /// `entry_index` must be the index of an entry registered by
1043    /// [`register_action_server_raw_sized`](Executor::register_action_server_raw_sized)
1044    /// with **these same const parameters**. The callbacks and the context sit
1045    /// behind `ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>`
1046    /// in the entry, so their offsets are a function of those four numbers and
1047    /// a mismatch writes into the core's buffers instead. The `EntryKind`
1048    /// check below catches a wrong KIND, never wrong sizes — the same contract
1049    /// [`action_client_core_mut`](Executor::action_client_core_mut) and
1050    /// [`service_client_entry_mut`](Executor::service_client_entry_mut) carry.
1051    pub(crate) unsafe fn detach_action_server_raw_sized<
1052        const GOAL_BUF: usize,
1053        const RESULT_BUF: usize,
1054        const FEEDBACK_BUF: usize,
1055        const MAX_GOALS: usize,
1056    >(
1057        &mut self,
1058        entry_index: usize,
1059    ) -> bool {
1060        let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1061            return false;
1062        };
1063        if !matches!(meta.kind, EntryKind::ActionServer) {
1064            return false;
1065        }
1066        let offset = meta.offset;
1067        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1068        unsafe {
1069            let entry = &mut *(arena_ptr.add(offset)
1070                as *mut ActionServerRawArenaEntry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>);
1071            entry.goal_callback = detached_goal_callback;
1072            entry.cancel_callback = detached_cancel_callback;
1073            entry.accepted_callback = None;
1074            entry.context = core::ptr::null_mut();
1075        }
1076        true
1077    }
1078
1079    /// [`detach_action_server_raw_sized`](Executor::detach_action_server_raw_sized)
1080    /// for an entry registered through the default-sized
1081    /// [`register_action_server_raw`](Executor::register_action_server_raw).
1082    ///
1083    /// Takes the handle rather than a bare index so the caller cannot name a
1084    /// subscription slot by accident: an [`ActionServerRawHandle`] is only ever
1085    /// produced by the raw registration path.
1086    ///
1087    /// # Safety
1088    /// `handle` must have come from `register_action_server_raw` — the
1089    /// DEFAULT-sized entry point. A handle from
1090    /// `register_action_server_raw_sized::<…>` with other const parameters must
1091    /// be detached through the sized call with the same ones.
1092    pub(crate) unsafe fn detach_action_server_raw(
1093        &mut self,
1094        handle: &ActionServerRawHandle,
1095    ) -> bool {
1096        unsafe {
1097            self.detach_action_server_raw_sized::<
1098                { crate::config::DEFAULT_RX_BUF_SIZE },
1099                { crate::config::DEFAULT_RX_BUF_SIZE },
1100                { crate::config::DEFAULT_RX_BUF_SIZE },
1101                4,
1102            >(handle.entry_index)
1103        }
1104    }
1105
1106    /// Re-point a default-sized raw action SERVER entry's callback `context`
1107    /// at `context` — issue 2015, the server half of
1108    /// [`retarget_action_client_raw`](Executor::retarget_action_client_raw).
1109    ///
1110    /// The C++ `rclcpp_action::Server<A>` registers its storage address as the
1111    /// entry's context. Moving the object (into an `rclcpp::Owned`, which is
1112    /// what `rclcpp_action::create_server` returns) relocated the storage and
1113    /// left the entry naming the moved-from bytes, so the first goal after the
1114    /// move was dispatched through dead memory and every later one rejected.
1115    ///
1116    /// # Safety
1117    /// As [`detach_action_server_raw`](Executor::detach_action_server_raw):
1118    /// `handle` must come from the DEFAULT-sized `register_action_server_raw`.
1119    /// `context` must be valid for as long as the entry may dispatch.
1120    pub(crate) unsafe fn retarget_action_server_raw(
1121        &mut self,
1122        handle: &ActionServerRawHandle,
1123        context: *mut core::ffi::c_void,
1124    ) -> bool {
1125        let Some(meta) = self
1126            .entries
1127            .get(handle.entry_index)
1128            .and_then(|e| e.as_ref())
1129        else {
1130            return false;
1131        };
1132        if !matches!(meta.kind, EntryKind::ActionServer) {
1133            return false;
1134        }
1135        let offset = meta.offset;
1136        unsafe {
1137            let entry = &mut *((self.arena.as_mut_ptr() as *mut u8).add(offset)
1138                as *mut ActionServerRawArenaEntry<
1139                    { crate::config::DEFAULT_RX_BUF_SIZE },
1140                    { crate::config::DEFAULT_RX_BUF_SIZE },
1141                    { crate::config::DEFAULT_RX_BUF_SIZE },
1142                    4,
1143                >);
1144            entry.context = context;
1145        }
1146        true
1147    }
1148
1149    /// Detach a raw action CLIENT's arena entry from its owner's storage —
1150    /// issue 1496, the client half.
1151    ///
1152    /// Same shape as
1153    /// [`detach_action_server_raw`](Executor::detach_action_server_raw) and one
1154    /// step simpler: the client entry's three callbacks are already
1155    /// `Option`s that `action_client_raw_try_process` guards with
1156    /// `if let Some(cb)`, so clearing them is enough to make a late reply,
1157    /// feedback sample or result a no-op rather than a call through a dead
1158    /// `context`.
1159    ///
1160    /// # Safety
1161    /// `entry_index` must be the index of an entry registered by
1162    /// [`register_action_client_raw`](Executor::register_action_client_raw) —
1163    /// the DEFAULT-sized entry point, which is the only one the C and C++ sched tasks
1164    /// use and the same assumption
1165    /// [`action_client_core_mut`](Executor::action_client_core_mut) makes on
1166    /// every poll.
1167    pub(crate) unsafe fn detach_action_client_raw(&mut self, entry_index: usize) -> bool {
1168        let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1169            return false;
1170        };
1171        if !matches!(meta.kind, EntryKind::ActionClient) {
1172            return false;
1173        }
1174        let offset = meta.offset;
1175        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1176        unsafe {
1177            let entry = &mut *(arena_ptr.add(offset)
1178                as *mut ActionClientRawArenaEntry<
1179                    { crate::config::DEFAULT_RX_BUF_SIZE },
1180                    { crate::config::DEFAULT_RX_BUF_SIZE },
1181                    { crate::config::DEFAULT_RX_BUF_SIZE },
1182                >);
1183            entry.goal_response_callback = None;
1184            entry.feedback_callback = None;
1185            entry.result_callback = None;
1186            entry.context = core::ptr::null_mut();
1187        }
1188        true
1189    }
1190
1191    /// RE-POINT a raw action client entry's callback `context` — issue 1496.
1192    ///
1193    /// The C++ client registers its own storage address as the entry's
1194    /// context; a move relocates that storage, so the entry must follow it or a
1195    /// moved-from temporary leaves it naming dead bytes. `false`, touching
1196    /// nothing, when `entry_index` is not a live action client.
1197    ///
1198    /// # Safety
1199    /// The entry must have been registered through the default-sized
1200    /// [`register_action_client_raw`](Executor::register_action_client_raw),
1201    /// and `context` must be valid for as long as the entry may dispatch.
1202    pub(crate) unsafe fn retarget_action_client_raw(
1203        &mut self,
1204        entry_index: usize,
1205        context: *mut core::ffi::c_void,
1206    ) -> bool {
1207        let Some(meta) = self.entries.get(entry_index).and_then(|e| e.as_ref()) else {
1208            return false;
1209        };
1210        if !matches!(meta.kind, EntryKind::ActionClient) {
1211            return false;
1212        }
1213        let offset = meta.offset;
1214        unsafe {
1215            let entry = &mut *((self.arena.as_mut_ptr() as *mut u8).add(offset)
1216                as *mut ActionClientRawArenaEntry<
1217                    { crate::config::DEFAULT_RX_BUF_SIZE },
1218                    { crate::config::DEFAULT_RX_BUF_SIZE },
1219                    { crate::config::DEFAULT_RX_BUF_SIZE },
1220                >);
1221            entry.context = context;
1222        }
1223        true
1224    }
1225
1226    /// RELEASE a raw action server — issue 1496's resolution 2.
1227    ///
1228    /// Where [`detach_action_server_raw_sized`](Self::detach_action_server_raw_sized)
1229    /// only cut the entry's edge to its owner, this ends the entry: it is
1230    /// dropped in place, so its three service servers and two publishers are
1231    /// destroyed and the action leaves the graph; its callback slot is freed
1232    /// (`NROS_EXECUTOR_MAX_CBS`), and its arena bytes go back to the
1233    /// executor's free list, where the next registration that fits reuses
1234    /// them. A program that creates and destroys action servers in a loop
1235    /// therefore runs forever instead of exhausting the slot table and then
1236    /// the arena.
1237    ///
1238    /// `false`, touching nothing, when `entry_index` is not a live action
1239    /// server.
1240    ///
1241    /// The const parameters are no longer load-bearing (issue 1631): the
1242    /// bytes released are the ones the registration RECORDED, so a mismatch
1243    /// cannot release the wrong length. They stay so existing callers compile.
1244    ///
1245    /// # Safety
1246    /// No [`ActionServerRawHandle`] naming the entry may be used afterwards —
1247    /// the slot is handed to the next registration.
1248    pub(crate) unsafe fn release_action_server_raw_sized<
1249        const GOAL_BUF: usize,
1250        const RESULT_BUF: usize,
1251        const FEEDBACK_BUF: usize,
1252        const MAX_GOALS: usize,
1253    >(
1254        &mut self,
1255        entry_index: usize,
1256    ) -> bool {
1257        unsafe { self.release_entry(entry_index, EntryKind::ActionServer) }
1258    }
1259
1260    /// [`release_action_server_raw_sized`](Self::release_action_server_raw_sized)
1261    /// for an entry registered through the default-sized
1262    /// [`register_action_server_raw`](Executor::register_action_server_raw).
1263    ///
1264    /// # Safety
1265    /// As the sized form; `handle` must not be used afterwards.
1266    pub(crate) unsafe fn release_action_server_raw(
1267        &mut self,
1268        handle: &ActionServerRawHandle,
1269    ) -> bool {
1270        unsafe {
1271            self.release_action_server_raw_sized::<
1272                { crate::config::DEFAULT_RX_BUF_SIZE },
1273                { crate::config::DEFAULT_RX_BUF_SIZE },
1274                { crate::config::DEFAULT_RX_BUF_SIZE },
1275                4,
1276            >(handle.entry_index)
1277        }
1278    }
1279
1280    /// RELEASE a raw action client registered through the default-sized
1281    /// [`register_action_client_raw`](Executor::register_action_client_raw) —
1282    /// issue 1496. Drops the entry (its three service clients and feedback
1283    /// subscription are destroyed), frees its callback slot and returns its
1284    /// arena bytes for reuse.
1285    ///
1286    /// # Safety
1287    /// As [`release_action_server_raw_sized`](Self::release_action_server_raw_sized),
1288    /// for the default-sized client entry.
1289    pub(crate) unsafe fn release_action_client_raw(&mut self, entry_index: usize) -> bool {
1290        unsafe {
1291            self.release_action_client_raw_sized::<
1292                { crate::config::DEFAULT_RX_BUF_SIZE },
1293                { crate::config::DEFAULT_RX_BUF_SIZE },
1294                { crate::config::DEFAULT_RX_BUF_SIZE },
1295            >(entry_index)
1296        }
1297    }
1298
1299    /// The sized form of [`release_action_client_raw`](Self::release_action_client_raw).
1300    ///
1301    /// As for the server, the const parameters are no longer load-bearing
1302    /// (issue 1631): the released length is the recorded one.
1303    ///
1304    /// # Safety
1305    /// No copy of `entry_index` may be used afterwards.
1306    pub(crate) unsafe fn release_action_client_raw_sized<
1307        const GOAL_BUF: usize,
1308        const RESULT_BUF: usize,
1309        const FEEDBACK_BUF: usize,
1310    >(
1311        &mut self,
1312        entry_index: usize,
1313    ) -> bool {
1314        unsafe { self.release_entry(entry_index, EntryKind::ActionClient) }
1315    }
1316}
1317
1318// ============================================================================
1319// Raw action server handle
1320// ============================================================================
1321
1322/// Handle to a raw (untyped) action server registered in the executor's arena.
1323///
1324/// Returned by [`ExecutorFfi::register_action_server_raw()`](crate::executor::ffi::ExecutorFfi::register_action_server_raw). Provides methods
1325/// to interact with the server using raw CDR bytes.
1326#[repr(C)]
1327#[allow(clippy::type_complexity)]
1328pub struct ActionServerRawHandle {
1329    pub(crate) entry_index: usize,
1330    publish_feedback_fn:
1331        unsafe fn(*mut u8, &nros_core::GoalUuid, *const u8, usize) -> Result<(), NodeError>,
1332    complete_goal_fn: unsafe fn(
1333        *mut u8,
1334        &nros_core::GoalUuid,
1335        nros_core::GoalStatusCode,
1336        *const u8,
1337        usize,
1338    ) -> Result<(), NodeError>,
1339    set_goal_status_fn: unsafe fn(*mut u8, &nros_core::GoalUuid, nros_core::GoalStatusCode),
1340    active_goal_count_fn: unsafe fn(*const u8) -> usize,
1341    goal_exists_fn: unsafe fn(*const u8, &nros_core::GoalUuid) -> bool,
1342    expire_goals_fn: unsafe fn(*mut u8) -> usize,
1343    for_each_active_goal_fn: unsafe fn(*const u8, &mut dyn FnMut(&RawActiveGoal)),
1344}
1345
1346impl Clone for ActionServerRawHandle {
1347    fn clone(&self) -> Self {
1348        *self
1349    }
1350}
1351
1352impl Copy for ActionServerRawHandle {}
1353
1354/// Sentinel value indicating an `ActionServerRawHandle` is not bound to an
1355/// arena entry yet. Used to replace `Option<...>` with a
1356/// `#[repr(C)]`-compatible inline field.
1357///
1358/// Function pointers are populated with `unreachable_*` stubs that panic
1359/// if anyone is reckless enough to dispatch through an unbound handle —
1360/// callers must check `entry_index == INVALID_ENTRY_INDEX` first.
1361pub const INVALID_ENTRY_INDEX: usize = usize::MAX;
1362
1363impl ActionServerRawHandle {
1364    /// Construct a sentinel handle representing "not registered yet".
1365    ///
1366    /// All function pointers are unreachable stubs; only valid use is
1367    /// to populate `#[repr(C)]` storage that is later overwritten by a
1368    /// real handle (or queried via `is_invalid()` to skip operations).
1369    pub(crate) const fn invalid() -> Self {
1370        unsafe fn unreachable_publish_feedback(
1371            _: *mut u8,
1372            _: &nros_core::GoalUuid,
1373            _: *const u8,
1374            _: usize,
1375        ) -> Result<(), NodeError> {
1376            unreachable!("ActionServerRawHandle::publish_feedback called on invalid handle")
1377        }
1378        unsafe fn unreachable_complete_goal(
1379            _: *mut u8,
1380            _: &nros_core::GoalUuid,
1381            _: nros_core::GoalStatusCode,
1382            _: *const u8,
1383            _: usize,
1384        ) -> Result<(), NodeError> {
1385            unreachable!("ActionServerRawHandle::complete_goal called on invalid handle")
1386        }
1387        unsafe fn unreachable_set_goal_status(
1388            _: *mut u8,
1389            _: &nros_core::GoalUuid,
1390            _: nros_core::GoalStatusCode,
1391        ) {
1392            unreachable!("ActionServerRawHandle::set_goal_status called on invalid handle")
1393        }
1394        unsafe fn unreachable_active_goal_count(_: *const u8) -> usize {
1395            unreachable!("ActionServerRawHandle::active_goal_count called on invalid handle")
1396        }
1397        unsafe fn unreachable_goal_exists(_: *const u8, _: &nros_core::GoalUuid) -> bool {
1398            unreachable!("ActionServerRawHandle::goal_exists called on invalid handle")
1399        }
1400        unsafe fn unreachable_expire_goals(_: *mut u8) -> usize {
1401            unreachable!("ActionServerRawHandle::expire_goals called on invalid handle")
1402        }
1403        unsafe fn unreachable_for_each_active_goal(
1404            _: *const u8,
1405            _: &mut dyn FnMut(&RawActiveGoal),
1406        ) {
1407            unreachable!("ActionServerRawHandle::for_each_active_goal called on invalid handle")
1408        }
1409        Self {
1410            entry_index: INVALID_ENTRY_INDEX,
1411            publish_feedback_fn: unreachable_publish_feedback,
1412            complete_goal_fn: unreachable_complete_goal,
1413            set_goal_status_fn: unreachable_set_goal_status,
1414            active_goal_count_fn: unreachable_active_goal_count,
1415            goal_exists_fn: unreachable_goal_exists,
1416            expire_goals_fn: unreachable_expire_goals,
1417            for_each_active_goal_fn: unreachable_for_each_active_goal,
1418        }
1419    }
1420
1421    /// `true` if this handle is the sentinel returned by `Self::invalid()`.
1422    pub(crate) const fn is_invalid(&self) -> bool {
1423        self.entry_index == INVALID_ENTRY_INDEX
1424    }
1425}
1426
1427impl Default for ActionServerRawHandle {
1428    fn default() -> Self {
1429        Self::invalid()
1430    }
1431}
1432
1433impl ActionServerRawHandle {
1434    /// Get the [`HandleId`] for this action server.
1435    pub(crate) fn handle_id(&self) -> HandleId {
1436        HandleId::for_owned_slot(self.entry_index)
1437    }
1438
1439    /// Publish feedback with raw CDR bytes (untyped variant).
1440    ///
1441    /// Used by the C API when feedback is already serialised.
1442    pub(crate) fn publish_feedback_raw(
1443        &self,
1444        executor: &mut Executor,
1445        goal_id: &nros_core::GoalUuid,
1446        feedback_data: &[u8],
1447    ) -> Result<(), NodeError> {
1448        let meta = executor.entries[self.entry_index]
1449            .as_ref()
1450            .ok_or(NodeError::BufferTooSmall)?;
1451        let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1452        unsafe {
1453            let data_ptr = arena_ptr.add(meta.offset);
1454            (self.publish_feedback_fn)(
1455                data_ptr,
1456                goal_id,
1457                feedback_data.as_ptr(),
1458                feedback_data.len(),
1459            )
1460        }
1461    }
1462
1463    /// Complete a goal with raw CDR result bytes (untyped variant).
1464    ///
1465    /// Moves the goal from the active set to the completed-results slab.
1466    ///
1467    /// # Errors
1468    ///
1469    /// `NodeError::BufferTooSmall` when the handle slot has been removed from
1470    /// the executor, or when `result_data` exceeds the server's `RESULT_BUF`
1471    /// and so cannot be retained for a later `get_result` (issue 0796 — this
1472    /// used to return `()` and swallow both).
1473    pub(crate) fn complete_goal_raw(
1474        &self,
1475        executor: &mut Executor,
1476        goal_id: &nros_core::GoalUuid,
1477        status: nros_core::GoalStatusCode,
1478        result_data: &[u8],
1479    ) -> Result<(), NodeError> {
1480        let meta = executor.entries[self.entry_index]
1481            .as_ref()
1482            .ok_or(NodeError::BufferTooSmall)?;
1483        let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1484        unsafe {
1485            let data_ptr = arena_ptr.add(meta.offset);
1486            (self.complete_goal_fn)(
1487                data_ptr,
1488                goal_id,
1489                status,
1490                result_data.as_ptr(),
1491                result_data.len(),
1492            )
1493        }
1494    }
1495
1496    /// Update a goal's status without completing it.
1497    ///
1498    /// Use this to transition a goal to `Executing` or `Canceling`
1499    /// while it is still active. To finish a goal, use [`complete_goal_raw`](Self::complete_goal_raw).
1500    pub(crate) fn set_goal_status(
1501        &self,
1502        executor: &mut Executor,
1503        goal_id: &nros_core::GoalUuid,
1504        status: nros_core::GoalStatusCode,
1505    ) {
1506        if let Some(meta) = executor.entries[self.entry_index].as_ref() {
1507            let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1508            unsafe {
1509                let data_ptr = arena_ptr.add(meta.offset);
1510                (self.set_goal_status_fn)(data_ptr, goal_id, status);
1511            }
1512        }
1513    }
1514
1515    /// Get the number of currently active goals.
1516    ///
1517    /// Returns 0 if the action server handle has been removed from the executor.
1518    pub(crate) fn active_goal_count(&self, executor: &Executor) -> usize {
1519        match executor.entries[self.entry_index].as_ref() {
1520            Some(meta) => {
1521                let arena_ptr = executor.arena.as_ptr() as *const u8;
1522                unsafe {
1523                    let data_ptr = arena_ptr.add(meta.offset);
1524                    (self.active_goal_count_fn)(data_ptr)
1525                }
1526            }
1527            None => 0,
1528        }
1529    }
1530
1531    /// Is `goal_id` a goal this server still knows about? — phase-417 W4.b.
1532    ///
1533    /// The raw twin of [`ActionServerHandle::goal_exists`], and what the C
1534    /// surface's `rclc_action_server_goal_exists` and the C++
1535    /// `Server<A>::goal_exists` both resolve to. Active OR completed-with-a-
1536    /// retained-result; `false` once the slot is gone from the executor.
1537    pub(crate) fn goal_exists(&self, executor: &Executor, goal_id: &nros_core::GoalUuid) -> bool {
1538        match executor.entries[self.entry_index].as_ref() {
1539            Some(meta) => {
1540                let arena_ptr = executor.arena.as_ptr() as *const u8;
1541                unsafe {
1542                    let data_ptr = arena_ptr.add(meta.offset);
1543                    (self.goal_exists_fn)(data_ptr, goal_id)
1544                }
1545            }
1546            None => false,
1547        }
1548    }
1549
1550    /// Eagerly reclaim delivered results — the raw twin of
1551    /// [`ActionServerHandle::expire_goals`], and what C's
1552    /// `rclc_action_expire_goals` resolves to. phase-417 W4.b.
1553    pub(crate) fn expire_goals(&self, executor: &mut Executor) -> usize {
1554        match executor.entries[self.entry_index].as_ref() {
1555            Some(meta) => {
1556                let arena_ptr = executor.arena.as_mut_ptr() as *mut u8;
1557                unsafe {
1558                    let data_ptr = arena_ptr.add(meta.offset);
1559                    (self.expire_goals_fn)(data_ptr)
1560                }
1561            }
1562            None => 0,
1563        }
1564    }
1565
1566    /// Iterate over all currently active goals (raw/untyped variant).
1567    ///
1568    /// Calls `f` for each goal that has been accepted but not yet completed.
1569    pub(crate) fn for_each_active_goal(
1570        &self,
1571        executor: &Executor,
1572        mut f: impl FnMut(&RawActiveGoal),
1573    ) {
1574        if let Some(meta) = executor.entries[self.entry_index].as_ref() {
1575            let arena_ptr = executor.arena.as_ptr() as *const u8;
1576            unsafe {
1577                let data_ptr = arena_ptr.add(meta.offset);
1578                (self.for_each_active_goal_fn)(data_ptr, &mut f);
1579            }
1580        }
1581    }
1582
1583    /// Look up the status of a single active goal by UUID.
1584    ///
1585    /// Returns `Some(status)` while the goal is still in the arena's
1586    /// `active_goals` vector. Returns `None` once the goal has been
1587    /// retired (completed + result delivered, or cancelled + acknowledged).
1588    ///
1589    /// This is the authoritative source of goal status — the C/C++ FFI
1590    /// layers call this from `rclc_action_get_goal_status` rather than
1591    /// reading a cached field on their own handle structs.
1592    pub(crate) fn goal_status(
1593        &self,
1594        executor: &Executor,
1595        goal_id: &nros_core::GoalUuid,
1596    ) -> Option<nros_core::GoalStatusCode> {
1597        let mut found = None;
1598        self.for_each_active_goal(executor, |g| {
1599            if g.goal_id.uuid == goal_id.uuid && found.is_none() {
1600                found = Some(g.status);
1601            }
1602        });
1603        found
1604    }
1605}
1606
1607// ============================================================================
1608// Action client registration
1609// ============================================================================
1610
1611impl<'s> Executor<'s> {
1612    /// Register a raw action client with the executor.
1613    ///
1614    /// Creates service clients for send_goal, cancel_goal, get_result, and a
1615    /// feedback subscriber. The executor polls these during `spin_once` and
1616    /// invokes the provided callbacks when responses/feedback arrive.
1617    ///
1618    /// # Arguments
1619    /// * `action_name` — action name (e.g., "/fibonacci")
1620    /// * `type_name` — action type (e.g., "example_interfaces::action::dds_::Fibonacci_")
1621    /// * `type_hash` — type hash (e.g., "TypeHashNotSupported")
1622    /// * `goal_response_callback` — called when goal is accepted/rejected
1623    /// * `feedback_callback` — called when feedback is received
1624    /// * `result_callback` — called when result is received
1625    /// * `context` — opaque pointer passed to all callbacks
1626    #[doc(hidden)]
1627    #[allow(clippy::too_many_arguments)]
1628    pub(crate) fn register_action_client_raw(
1629        &mut self,
1630        spec: RawActionClientSpec<'_>,
1631    ) -> Result<ActionClientRawHandle, NodeError> {
1632        self.register_action_client_raw_sized::<
1633            { crate::config::DEFAULT_RX_BUF_SIZE },
1634            { crate::config::DEFAULT_RX_BUF_SIZE },
1635            { crate::config::DEFAULT_RX_BUF_SIZE },
1636        >(spec)
1637    }
1638
1639    /// Register a raw action client with explicit buffer sizes.
1640    ///
1641    /// `spec.node_id` selects the target: `None` registers on the
1642    /// executor's own node, `Some(id)` routes the client's 4 underlying
1643    /// handles through the named Node's session.
1644    #[doc(hidden)]
1645    pub fn register_action_client_raw_sized<
1646        const GOAL_BUF: usize,
1647        const RESULT_BUF: usize,
1648        const FEEDBACK_BUF: usize,
1649    >(
1650        &mut self,
1651        spec: RawActionClientSpec<'_>,
1652    ) -> Result<ActionClientRawHandle, NodeError> {
1653        let RawActionClientSpec {
1654            node_id,
1655            action_name,
1656            type_name,
1657            type_hash,
1658            hashes,
1659            goal_response_callback,
1660            feedback_callback,
1661            result_callback,
1662            cancel_response_callback,
1663            context,
1664        } = spec;
1665
1666        type Entry<const GB: usize, const RB: usize, const FB: usize> =
1667            ActionClientRawArenaEntry<GB, RB, FB>;
1668
1669        let slot = self.next_entry_slot()?;
1670
1671        let action_info = ActionInfo::new(action_name, type_name, type_hash);
1672        // Issue 0656 — capture the domain BEFORE the session borrow below, for
1673        // the same reason `node_name`/`ns` are cloned here: the `&mut session`
1674        // in the create scope would otherwise conflict with `&self`.
1675        let domain_id = self.domain_id;
1676        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
1677
1678        let (send_goal_client, cancel_goal_client, get_result_client, feedback_sub) = {
1679            // phase-338 W3 — per-channel types, matching the raw SERVER path.
1680            // Both raw sides used the bare action type, so nano-ros talked to
1681            // itself but was invisible to any `rcl_action` peer; fixing only one
1682            // side would have broken the self-consistent pairs instead.
1683            let send_goal_type: heapless::String<256> =
1684                super::action_core::action_channel_type(type_name, "SendGoal");
1685            let get_result_type: heapless::String<256> =
1686                super::action_core::action_channel_type(type_name, "GetResult");
1687            let feedback_type: heapless::String<256> =
1688                super::action_core::action_channel_type(type_name, "FeedbackMessage");
1689
1690            let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1691            let mut send_goal_info =
1692                ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
1693                    .with_namespace(&ns)
1694                    .with_domain(domain_id);
1695            if !node_name.is_empty() {
1696                send_goal_info = send_goal_info.with_node_name(&node_name);
1697            }
1698
1699            let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1700            let mut cancel_goal_info = ServiceInfo::new(
1701                &cancel_goal_keyexpr,
1702                "action_msgs::srv::dds_::CancelGoal_",
1703                hashes.cancel_goal,
1704            )
1705            .with_namespace(&ns)
1706            .with_domain(domain_id);
1707            if !node_name.is_empty() {
1708                cancel_goal_info = cancel_goal_info.with_node_name(&node_name);
1709            }
1710
1711            let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1712            let mut get_result_info =
1713                ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
1714                    .with_namespace(&ns)
1715                    .with_domain(domain_id);
1716            if !node_name.is_empty() {
1717                get_result_info = get_result_info.with_node_name(&node_name);
1718            }
1719
1720            let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1721            let mut feedback_topic =
1722                TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
1723                    .with_namespace(&ns)
1724                    .with_domain(domain_id);
1725            if !node_name.is_empty() {
1726                feedback_topic = feedback_topic.with_node_name(&node_name);
1727            }
1728
1729            let session = self
1730                .session_at_mut(session_idx)
1731                .ok_or(NodeError::BackendMismatch)?;
1732            // issue 0870 — these were `map_err(|_| NodeError::ActionCreationFailed)`,
1733            // discarding a `TransportError` the caller could have used. An action
1734            // client declares four entities back to back, so "one of them failed"
1735            // is the least useful thing this seam can say. `NodeError` already
1736            // carries `Transport(TransportError)` — nothing needed adding, the
1737            // error simply was not passed on. Swept across all 17 session
1738            // `create_*` sites here. The two `register_protocol_types` sites keep
1739            // `ActionCreationFailed`: their `map_err(|()| …)` has no payload, so
1740            // there the variant IS the whole truth.
1741            (
1742                session
1743                    .create_client(&send_goal_info, QoSProfile::services_default())
1744                    .map_err(|e| {
1745                        nros_log::log_error!(
1746                            nros_log::get_logger("nros_node"),
1747                            "action client: send_goal client failed: {:?}",
1748                            e
1749                        );
1750                        NodeError::Transport(e)
1751                    })?,
1752                session
1753                    .create_client(&cancel_goal_info, QoSProfile::services_default())
1754                    .map_err(|e| {
1755                        nros_log::log_error!(
1756                            nros_log::get_logger("nros_node"),
1757                            "action client: cancel_goal client failed: {:?}",
1758                            e
1759                        );
1760                        NodeError::Transport(e)
1761                    })?,
1762                session
1763                    .create_client(&get_result_info, QoSProfile::services_default())
1764                    .map_err(|e| {
1765                        nros_log::log_error!(
1766                            nros_log::get_logger("nros_node"),
1767                            "action client: get_result client failed: {:?}",
1768                            e
1769                        );
1770                        NodeError::Transport(e)
1771                    })?,
1772                session
1773                    .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1774                    .map_err(|e| {
1775                        nros_log::log_error!(
1776                            nros_log::get_logger("nros_node"),
1777                            "action client: feedback subscription failed: {:?}",
1778                            e
1779                        );
1780                        NodeError::Transport(e)
1781                    })?,
1782            )
1783        };
1784
1785        let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>()?;
1786
1787        // Issue 2360 — written in place: building the core (and its buffers)
1788        // as a value and moving it in kept them on this frame.
1789        unsafe {
1790            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1791            let entry_ptr = arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
1792            ActionClientCore::init_in_place(
1793                core::ptr::addr_of_mut!((*entry_ptr).core),
1794                send_goal_client,
1795                cancel_goal_client,
1796                get_result_client,
1797                feedback_sub,
1798            );
1799            core::ptr::addr_of_mut!((*entry_ptr).goal_response_callback)
1800                .write(goal_response_callback);
1801            core::ptr::addr_of_mut!((*entry_ptr).feedback_callback).write(feedback_callback);
1802            core::ptr::addr_of_mut!((*entry_ptr).result_callback).write(result_callback);
1803            core::ptr::addr_of_mut!((*entry_ptr).cancel_response_callback)
1804                .write(cancel_response_callback);
1805            core::ptr::addr_of_mut!((*entry_ptr).context).write(context);
1806            // The entry's own fields, named with no `..`: a field added to it
1807            // fails here until it is written above.
1808            let Entry {
1809                core: _,
1810                goal_response_callback: _,
1811                feedback_callback: _,
1812                result_callback: _,
1813                cancel_response_callback: _,
1814                context: _,
1815            } = &*entry_ptr;
1816        }
1817
1818        let meta = CallbackMeta {
1819            offset,
1820            kind: EntryKind::ActionClient,
1821            arena_len: super::arena::ArenaLen::UNRECORDED,
1822            has_data: always_ready,
1823            pre_sample: no_pre_sample,
1824            invocation: InvocationMode::Always,
1825            try_process: action_client_raw_try_process::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
1826            drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
1827        };
1828        self.emplace_entry(slot, meta, TraceName::Text(spec.action_name));
1829        self.apply_node_default_sched(slot, node_id, None);
1830
1831        Ok(ActionClientRawHandle { entry_index: slot })
1832    }
1833
1834    /// RFC-0041 / Phase 239.2 — register a **typed callback** action client.
1835    /// Goal-response / feedback / result are eager-drained at `spin_once` and
1836    /// dispatched as deserialized `A::Feedback` / `A::Result` to the typed
1837    /// closures. Returns the scheduling [`HandleId`] and a `*mut` to the arena
1838    /// entry's core (used to build the typed
1839    /// [`ActionClientCallback`](super::handles::ActionClientCallback)).
1840    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
1841    pub(crate) fn register_action_client_callback<
1842        A,
1843        GRespF,
1844        FbF,
1845        ResF,
1846        const GOAL_BUF: usize,
1847        const RESULT_BUF: usize,
1848        const FEEDBACK_BUF: usize,
1849    >(
1850        &mut self,
1851        node_id: Option<super::node_record::NodeId>,
1852        action_name: &str,
1853        type_name: &str,
1854        type_hash: &str,
1855        feedback_depth: u16,
1856        on_goal_response: GRespF,
1857        on_feedback: FbF,
1858        on_result: ResF,
1859    ) -> Result<
1860        (
1861            HandleId,
1862            *mut ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
1863        ),
1864        NodeError,
1865    >
1866    where
1867        A: nros_core::RosAction + 'static,
1868        GRespF: FnMut(&nros_core::GoalUuid, bool) + 'static,
1869        FbF: FnMut(&nros_core::GoalUuid, &A::Feedback) + 'static,
1870        ResF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode, &A::Result) + 'static,
1871    {
1872        type Entry<A, G, Fb, R, const GB: usize, const RB: usize, const FB: usize> =
1873            ActionClientCallbackEntry<A, G, Fb, R, GB, RB, FB>;
1874
1875        let slot = self.next_entry_slot()?;
1876        let action_info = ActionInfo::new(action_name, type_name, type_hash);
1877        // Issue 1913 — each endpoint on its own type's hash.
1878        let hashes = ActionEndpointHashes::of::<A>();
1879        // Phase 244 E3 (RFC-0044) — register the `action_msgs` protocol types
1880        // (CancelGoal_{Request,Response}, GoalStatusArray) the client's cancel
1881        // service + status subscription serialize, before creating those
1882        // entities. Generated `impl RosAction` overrides this (default no-op);
1883        // replaces the example's hand-rolled `#[cfg(rmw-cyclonedds)]` block.
1884        A::register_protocol_types().map_err(|()| NodeError::ActionCreationFailed)?;
1885        // Issue 0656 — capture the domain BEFORE the session borrow below, for
1886        // the same reason `node_name`/`ns` are cloned here: the `&mut session`
1887        // in the create scope would otherwise conflict with `&self`.
1888        let domain_id = self.domain_id;
1889        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
1890
1891        let (send_goal_client, cancel_goal_client, get_result_client, feedback_sub) = {
1892            // phase-338 W3 — per-channel types, matching the raw SERVER path.
1893            // Both raw sides used the bare action type, so nano-ros talked to
1894            // itself but was invisible to any `rcl_action` peer; fixing only one
1895            // side would have broken the self-consistent pairs instead.
1896            let send_goal_type: heapless::String<256> =
1897                super::action_core::action_channel_type(type_name, "SendGoal");
1898            let get_result_type: heapless::String<256> =
1899                super::action_core::action_channel_type(type_name, "GetResult");
1900            let feedback_type: heapless::String<256> =
1901                super::action_core::action_channel_type(type_name, "FeedbackMessage");
1902
1903            let send_goal_keyexpr: heapless::String<256> = action_info.send_goal_key();
1904            let mut send_goal_info =
1905                ServiceInfo::new(&send_goal_keyexpr, &send_goal_type, hashes.send_goal)
1906                    .with_namespace(&ns)
1907                    .with_domain(domain_id);
1908            if !node_name.is_empty() {
1909                send_goal_info = send_goal_info.with_node_name(&node_name);
1910            }
1911            let cancel_goal_keyexpr: heapless::String<256> = action_info.cancel_goal_key();
1912            let mut cancel_goal_info = ServiceInfo::new(
1913                &cancel_goal_keyexpr,
1914                "action_msgs::srv::dds_::CancelGoal_",
1915                hashes.cancel_goal,
1916            )
1917            .with_namespace(&ns)
1918            .with_domain(domain_id);
1919            if !node_name.is_empty() {
1920                cancel_goal_info = cancel_goal_info.with_node_name(&node_name);
1921            }
1922            let get_result_keyexpr: heapless::String<256> = action_info.get_result_key();
1923            let mut get_result_info =
1924                ServiceInfo::new(&get_result_keyexpr, &get_result_type, hashes.get_result)
1925                    .with_namespace(&ns)
1926                    .with_domain(domain_id);
1927            if !node_name.is_empty() {
1928                get_result_info = get_result_info.with_node_name(&node_name);
1929            }
1930            let feedback_keyexpr: heapless::String<256> = action_info.feedback_key();
1931            let mut feedback_topic =
1932                TopicInfo::new(&feedback_keyexpr, &feedback_type, hashes.feedback)
1933                    .with_namespace(&ns)
1934                    .with_domain(domain_id);
1935            if !node_name.is_empty() {
1936                feedback_topic = feedback_topic.with_node_name(&node_name);
1937            }
1938            let session = self
1939                .session_at_mut(session_idx)
1940                .ok_or(NodeError::BackendMismatch)?;
1941            (
1942                session
1943                    .create_client(&send_goal_info, QoSProfile::services_default())
1944                    .map_err(NodeError::Transport)?,
1945                session
1946                    .create_client(&cancel_goal_info, QoSProfile::services_default())
1947                    .map_err(NodeError::Transport)?,
1948                session
1949                    .create_client(&get_result_info, QoSProfile::services_default())
1950                    .map_err(NodeError::Transport)?,
1951                session
1952                    .create_subscription(&feedback_topic, QoSProfile::BEST_EFFORT)
1953                    .map_err(NodeError::Transport)?,
1954            )
1955        };
1956
1957        let core = ActionClientCore::new(
1958            send_goal_client,
1959            cancel_goal_client,
1960            get_result_client,
1961            feedback_sub,
1962        );
1963
1964        // Phase 239.5 — trailing-allocate the feedback QoS-depth buffer alongside
1965        // the entry (ring for depth > 1, triple for depth ≤ 1), then drain
1966        // `core.feedback_subscriber` into it in the dispatcher.
1967        let (_slot_count, trailing_bytes) =
1968            buffered_region_size(feedback_depth as u32, FEEDBACK_BUF);
1969        let (offset, trailing_offset) = self.arena_alloc_with_trailing::<Entry<
1970            A,
1971            GRespF,
1972            FbF,
1973            ResF,
1974            GOAL_BUF,
1975            RESULT_BUF,
1976            FEEDBACK_BUF,
1977        >>(trailing_bytes)?;
1978        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
1979        let feedback_buffer = if feedback_depth <= 1 {
1980            BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, FEEDBACK_BUF) })
1981        } else {
1982            BufferStrategy::Ring(unsafe {
1983                SpscRing::init(buf_ptr, FEEDBACK_BUF, feedback_depth as usize)
1984            })
1985        };
1986        let core_ptr = unsafe {
1987            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
1988            let entry_ptr = arena_ptr.add(offset)
1989                as *mut Entry<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
1990            core::ptr::write(
1991                entry_ptr,
1992                ActionClientCallbackEntry {
1993                    core,
1994                    feedback_buffer,
1995                    on_goal_response,
1996                    on_feedback,
1997                    on_result,
1998                    _phantom: core::marker::PhantomData,
1999                },
2000            );
2001            // Phase-573 W2b — a raw place, not `&mut .. as *mut`: a pointer
2002            // made from a temporary reference is a child of it, and the
2003            // dispatcher's own write to the entry disables it, so the next
2004            // send through the handle would be UB.
2005            core::ptr::addr_of_mut!((*entry_ptr).core)
2006        };
2007
2008        let meta = CallbackMeta {
2009            offset,
2010            kind: EntryKind::ActionClient,
2011            arena_len: super::arena::ArenaLen::UNRECORDED,
2012            has_data: always_ready,
2013            pre_sample: no_pre_sample,
2014            invocation: InvocationMode::Always,
2015            try_process: action_client_callback_try_process::<
2016                A,
2017                GRespF,
2018                FbF,
2019                ResF,
2020                GOAL_BUF,
2021                RESULT_BUF,
2022                FEEDBACK_BUF,
2023            >,
2024            drop_fn: drop_entry::<Entry<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
2025        };
2026        self.emplace_entry(slot, meta, TraceName::Text(action_name));
2027        self.apply_node_default_sched(slot, node_id, None);
2028        Ok((self.handle_for(slot), core_ptr))
2029    }
2030}
2031
2032impl<'s> Executor<'s> {
2033    /// Register an existing `ActionClientCore` with the executor for async polling.
2034    ///
2035    /// Unlike `register_action_client_raw` (which creates new transport handles),
2036    /// this takes ownership of an existing core. Use this when the core was
2037    /// already created by the C/C++ action client init.
2038    #[doc(hidden)]
2039    pub(crate) fn register_action_client_core<
2040        const GOAL_BUF: usize,
2041        const RESULT_BUF: usize,
2042        const FEEDBACK_BUF: usize,
2043    >(
2044        &mut self,
2045        core: ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2046        goal_response_callback: Option<RawGoalResponseCallback>,
2047        feedback_callback: Option<RawFeedbackCallback>,
2048        result_callback: Option<RawResultCallback>,
2049        cancel_response_callback: Option<RawCancelResponseCallback>,
2050        context: *mut core::ffi::c_void,
2051    ) -> Result<ActionClientRawHandle, NodeError> {
2052        type Entry<const GB: usize, const RB: usize, const FB: usize> =
2053            ActionClientRawArenaEntry<GB, RB, FB>;
2054
2055        let slot = self.next_entry_slot()?;
2056        let offset = self.arena_alloc::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>()?;
2057
2058        unsafe {
2059            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
2060            let entry_ptr = arena_ptr.add(offset) as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>;
2061            core::ptr::write(
2062                entry_ptr,
2063                Entry {
2064                    core,
2065                    goal_response_callback,
2066                    feedback_callback,
2067                    result_callback,
2068                    cancel_response_callback,
2069                    context,
2070                },
2071            );
2072        }
2073
2074        let meta = CallbackMeta {
2075            offset,
2076            kind: EntryKind::ActionClient,
2077            arena_len: super::arena::ArenaLen::UNRECORDED,
2078            has_data: always_ready,
2079            pre_sample: no_pre_sample,
2080            invocation: InvocationMode::Always,
2081            try_process: action_client_raw_try_process::<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
2082            drop_fn: drop_entry::<Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>>,
2083        };
2084        self.emplace_entry(slot, meta, TraceName::Slot("action_client", slot));
2085
2086        Ok(ActionClientRawHandle { entry_index: slot })
2087    }
2088}
2089
2090/// Handle returned by [`ExecutorFfi::register_action_client_raw()`](crate::executor::ffi::ExecutorFfi::register_action_client_raw).
2091///
2092/// Provides methods to send goals, request results, and cancel goals
2093/// via the executor's non-blocking path.
2094pub struct ActionClientRawHandle {
2095    entry_index: usize,
2096}
2097
2098impl ActionClientRawHandle {
2099    /// Get the entry index for this action client.
2100    pub(crate) fn entry_index(&self) -> usize {
2101        self.entry_index
2102    }
2103}
2104
2105// ============================================================================
2106// phase-417 W4.b — the three terminal verbs
2107// ============================================================================
2108
2109// Gated exactly like `executor::tests`: MockSession is the `ConcreteSession`
2110// only when no real backend is linked, and `from_session` needs `alloc`.
2111#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
2112mod terminal_verb_tests {
2113    use super::*;
2114    use core::sync::atomic::{AtomicI8, Ordering};
2115    use nros_core::{CdrReader, CdrWriter, DeserError, Deserialize, SerError, Serialize};
2116    use nros_rmw::TransportError;
2117
2118    use crate::mock::MockSession;
2119
2120    /// The status the last `complete_goal_fn` call was handed. `-1` is "no
2121    /// call yet", which is what makes "the verb never reached `complete_goal`"
2122    /// distinguishable from "it reached it with the wrong status".
2123    static LAST_STATUS: AtomicI8 = AtomicI8::new(-1);
2124
2125    #[derive(Default)]
2126    struct Unit;
2127
2128    impl Serialize for Unit {
2129        fn serialize(&self, _w: &mut CdrWriter) -> Result<(), SerError> {
2130            Ok(())
2131        }
2132    }
2133    impl Deserialize for Unit {
2134        fn deserialize(_r: &mut CdrReader) -> Result<Self, DeserError> {
2135            Ok(Self)
2136        }
2137    }
2138    impl nros_core::RosMessage for Unit {
2139        const TYPE_NAME: &'static str = "test/action/Verbs_Unit";
2140        const TYPE_HASH: &'static str = "test_hash";
2141    }
2142
2143    struct VerbAction;
2144
2145    impl RosAction for VerbAction {
2146        type Goal = Unit;
2147        type Result = Unit;
2148        type Feedback = Unit;
2149        type SendGoalRequest = Unit;
2150        type SendGoalResponse = Unit;
2151        type GetResultRequest = Unit;
2152        type GetResultResponse = Unit;
2153        type FeedbackMessage = Unit;
2154        const ACTION_NAME: &'static str = "test/action/dds_/Verbs_";
2155        const ACTION_HASH: &'static str = "test_hash";
2156    }
2157
2158    unsafe fn record_status(
2159        _data: *mut u8,
2160        _goal_id: &nros_core::GoalUuid,
2161        status: nros_core::GoalStatusCode,
2162        _result: Unit,
2163    ) -> Result<(), NodeError> {
2164        LAST_STATUS.store(status as i8, Ordering::SeqCst);
2165        Ok(())
2166    }
2167
2168    unsafe fn unused_feedback(
2169        _data: *mut u8,
2170        _goal_id: &nros_core::GoalUuid,
2171        _fb: &Unit,
2172    ) -> Result<(), NodeError> {
2173        unreachable!("the terminal-verb test never publishes feedback")
2174    }
2175
2176    unsafe fn unused_set_status(
2177        _data: *mut u8,
2178        _goal_id: &nros_core::GoalUuid,
2179        _status: nros_core::GoalStatusCode,
2180    ) {
2181        unreachable!("the terminal-verb test never sets a non-terminal status")
2182    }
2183
2184    unsafe fn unused_count(_data: *const u8) -> usize {
2185        unreachable!("the terminal-verb test never counts active goals")
2186    }
2187
2188    unsafe fn unused_for_each(_data: *const u8, _f: &mut dyn FnMut(&ActiveGoal<VerbAction>)) {
2189        unreachable!("the terminal-verb test never iterates active goals")
2190    }
2191
2192    unsafe fn unused_goal_exists(_data: *const u8, _goal_id: &nros_core::GoalUuid) -> bool {
2193        unreachable!("the terminal-verb test never asks whether a goal exists")
2194    }
2195
2196    unsafe fn unused_expire_goals(_data: *mut u8) -> usize {
2197        unreachable!("the terminal-verb test never expires goals")
2198    }
2199
2200    unsafe fn never_processes(
2201        _data: *mut u8,
2202        _delta_us: u64,
2203        _slot: u8,
2204    ) -> Result<bool, TransportError> {
2205        Ok(false)
2206    }
2207
2208    unsafe fn drops_nothing(_data: *mut u8) {}
2209
2210    fn handle() -> ActionServerHandle<VerbAction> {
2211        ActionServerHandle {
2212            entry_index: 0,
2213            publish_feedback_fn: unused_feedback,
2214            complete_goal_fn: record_status,
2215            set_goal_status_fn: unused_set_status,
2216            active_goal_count_fn: unused_count,
2217            goal_exists_fn: unused_goal_exists,
2218            expire_goals_fn: unused_expire_goals,
2219            for_each_active_goal_fn: unused_for_each,
2220            _phantom: PhantomData,
2221        }
2222    }
2223
2224    fn meta() -> CallbackMeta {
2225        CallbackMeta {
2226            offset: 0,
2227            kind: EntryKind::ActionServer,
2228            arena_len: crate::executor::arena::ArenaLen::UNRECORDED,
2229            try_process: never_processes,
2230            has_data: always_ready,
2231            pre_sample: no_pre_sample,
2232            invocation: InvocationMode::OnNewData,
2233            drop_fn: drops_nothing,
2234        }
2235    }
2236
2237    /// Each verb must reach `complete_goal` with the SPEC state it is named
2238    /// for, and `cancel` must forward to `canceled` rather than be a second
2239    /// code path (RFC-0019: the wrapper spelling may double, the behaviour may
2240    /// not).
2241    ///
2242    /// The observation point is the handle's own `complete_goal_fn`, so a verb
2243    /// that quietly did nothing fails on `-1` and a verb wired to the wrong
2244    /// status fails on the discriminant — the two ways a forwarder goes wrong.
2245    #[test]
2246    fn terminal_verbs_carry_their_spec_state_and_cancel_forwards_to_canceled() {
2247        let mut executor = Executor::from_session(MockSession::new());
2248        executor.entries[0] = Some(meta());
2249
2250        let h = handle();
2251        let goal = nros_core::GoalUuid::zero();
2252
2253        LAST_STATUS.store(-1, Ordering::SeqCst);
2254        h.succeed(&mut executor, &goal, Unit).unwrap();
2255        assert_eq!(
2256            LAST_STATUS.load(Ordering::SeqCst),
2257            nros_core::GoalStatusCode::Succeeded as i8,
2258            "succeed() must terminate the goal as SUCCEEDED"
2259        );
2260
2261        LAST_STATUS.store(-1, Ordering::SeqCst);
2262        h.abort(&mut executor, &goal, Unit).unwrap();
2263        assert_eq!(
2264            LAST_STATUS.load(Ordering::SeqCst),
2265            nros_core::GoalStatusCode::Aborted as i8,
2266            "abort() must terminate the goal as ABORTED"
2267        );
2268
2269        // The renamed verb. `canceled` is the spelling C
2270        // (`rclc_action_canceled`), C++ (`ActionServer<A>::canceled`) and
2271        // rclcpp_action (`ServerGoalHandle::canceled`) all use.
2272        LAST_STATUS.store(-1, Ordering::SeqCst);
2273        h.canceled(&mut executor, &goal, Unit).unwrap();
2274        assert_eq!(
2275            LAST_STATUS.load(Ordering::SeqCst),
2276            nros_core::GoalStatusCode::Canceled as i8,
2277            "canceled() must terminate the goal as CANCELED"
2278        );
2279
2280        // The entry was hand-built, not registered; hand it back before Drop
2281        // walks the arena.
2282        executor.entries[0] = None;
2283    }
2284}