nros_node/executor/action_core.rs
1//! Type-agnostic action protocol core types.
2//!
3//! [`ActionServerCore`] and [`ActionClientCore`] handle the raw-bytes
4//! action protocol (GoalUuid framing, status publishing, result slab)
5//! without requiring `RosAction` type parameters. The typed
6//! [`ActionServer`](super::handles::ActionServer) and
7//! [`ActionClient`](super::handles::ActionClient) wrap these cores
8//! and add serialization/deserialization at the boundary.
9
10use nros_core::{
11 CdrReader, CdrWriter, GoalInfo, GoalStatusCode, GoalStatusStamped, GoalUuid, Serialize, Time,
12};
13use nros_rmw::{ClientTrait, Publisher, ServiceTrait, Subscription, TransportError};
14
15use super::types::NodeError;
16use crate::session;
17
18/// Scratch buffer for a decoded CancelGoal request. Cancel payloads are
19/// tiny (a `GoalUuid` + a `builtin_interfaces/Time` stamp), so a fixed
20/// 256-byte buffer covers them without a const-generic parameter like the
21/// goal/result/feedback slabs.
22pub(crate) const CANCEL_BUF: usize = 256;
23
24/// DDS type name of an action's `send_goal` / `get_result` service.
25///
26/// ROS 2 names the action's two services by their per-channel service types —
27/// `<Action>_SendGoal` / `<Action>_GetResult` — **not** the bare action type
28/// (`<Action>`). A real `rcl_action` peer matches on those, so advertising the
29/// bare action type leaves our send_goal/get_result services undiscovered and
30/// every goal times out.
31///
32/// The codegen emits each channel's *request* envelope type name in DDS form,
33/// e.g. `example_interfaces::action::dds_::Fibonacci_SendGoal_Request_`. The
34/// service layer (`xrce_dds_request_type` / the Zenoh shim) extends a base type
35/// ending in `_` with `Request_` / `Response_`, so the base we must pass is the
36/// request type name with its trailing `Request_` stripped:
37/// `…Fibonacci_SendGoal_Request_` → `…Fibonacci_SendGoal_`. Falls back to the
38/// bare action type if the request name has an unexpected shape.
39pub(crate) fn action_service_base_type<'a>(
40 request_type_name: &'a str,
41 fallback_action_type: &'a str,
42) -> &'a str {
43 request_type_name
44 .strip_suffix("Request_")
45 .unwrap_or(fallback_action_type)
46}
47
48/// The per-channel DDS type name for a RAW-registered action server.
49///
50/// The typed path derives these from `A::SendGoalRequest::TYPE_NAME` via
51/// `action_service_base_type`. The raw path (`register_action_server_raw*`)
52/// has only the BARE action type, so it must construct them — and until
53/// a fix it did not, advertising `…Fibonacci_` on send_goal / get_result
54/// / feedback where ROS 2 expects `…Fibonacci_SendGoal_`,
55/// `…Fibonacci_GetResult_` and `…Fibonacci_FeedbackMessage_`. The type name is
56/// baked into the keyexpr, so a client's query never matched the server's
57/// queryable and every goal timed out with `Transport(Timeout)` — exactly the
58/// failure `action_service_base_type`'s own doc warns about, on the other
59/// registration path.
60///
61/// `action_type` is DDS-form and ends in `_` (`…::dds_::Fibonacci_`); the
62/// result replaces that suffix with `_<Channel>_`. Returns the bare type
63/// unchanged if it has an unexpected shape, matching the typed path's
64/// fallback.
65pub fn action_channel_type<const N: usize>(
66 action_type: &str,
67 channel: &str,
68) -> heapless::String<N> {
69 let mut out: heapless::String<N> = heapless::String::new();
70 let base = action_type.strip_suffix('_').unwrap_or(action_type);
71 if out.push_str(base).is_err()
72 || out.push('_').is_err()
73 || out.push_str(channel).is_err()
74 || out.push('_').is_err()
75 {
76 let mut fallback: heapless::String<N> = heapless::String::new();
77 let _ = fallback.push_str(action_type);
78 return fallback;
79 }
80 out
81}
82
83/// Scratch buffer for serializing a `GoalStatusArray` before publishing it
84/// on the status topic. It is a local in
85/// [`publish_status_array`](crate::executor::ffi::ActionServerCoreFfi::publish_status_array), so it is
86/// stack, not static — which is why it is not simply made large enough for any
87/// `MAX_GOALS` anyone might pick. What it must hold is stated exactly by
88/// [`status_array_bytes`] and checked at COMPILE time per instantiation; see
89/// [`ActionServerCore::STATUS_ARRAY_FITS`].
90pub(crate) const STATUS_ARRAY_BUF: usize = 512;
91
92/// Bytes one `GoalStatusStamped` occupies when another entry follows it.
93///
94/// `GoalInfo` is a fixed `uint8[16]` (16 unaligned bytes) + `int32 sec` +
95/// `uint32 nanosec`, then `int8 status` — 25 bytes — and the NEXT entry's `sec`
96/// forces a 4-byte alignment pad, so the stride is 28. MEASURED against the
97/// real `CdrWriter` by `status_array_entry_layout_is_measured`, not
98/// asserted from this comment: the const and the serializer have to agree or
99/// the compile-time bound below is checking the wrong number.
100pub(crate) const STATUS_ENTRY_STRIDE: usize = 28;
101
102/// The LAST entry carries no trailing alignment pad, so it is 3 bytes shorter
103/// than [`STATUS_ENTRY_STRIDE`].
104pub(crate) const STATUS_ENTRY_TAIL: usize = 25;
105
106/// CDR encapsulation header (4) + the sequence length prefix (4).
107pub(crate) const STATUS_ARRAY_PREAMBLE: usize = 8;
108
109/// Exact serialized size of a `GoalStatusArray` carrying `entries` entries.
110pub(crate) const fn status_array_bytes(entries: usize) -> usize {
111 if entries == 0 {
112 STATUS_ARRAY_PREAMBLE
113 } else {
114 STATUS_ARRAY_PREAMBLE + STATUS_ENTRY_STRIDE * (entries - 1) + STATUS_ENTRY_TAIL
115 }
116}
117
118// ============================================================================
119// Supporting types
120// ============================================================================
121
122/// Goal tracked by the core — GoalUuid, status and acceptance stamp; no typed data.
123#[derive(Clone, Copy)]
124pub struct RawActiveGoal {
125 /// Goal ID.
126 pub goal_id: GoalUuid,
127 /// Current status.
128 pub status: GoalStatusCode,
129 /// When the server ACCEPTED the goal, on the ROS clock
130 /// (`Clock::ros_time()`: `/clock` when a source drives it, the port's wall
131 /// clock otherwise — rcl_action stamps with the server's clock the same
132 /// way). A `CancelGoal` request with a stamp cancels the goals accepted at
133 /// or before it, and every `GoalInfo` this server writes carries it. A
134 /// board with no wall clock stamps zero, so a stamped cancel there selects
135 /// every goal.
136 pub stamp: Time,
137}
138
139/// A `get_result` request held until its goal terminates.
140///
141/// `sequence_number` is the service-backend reply-correlation token; the backend
142/// must be able to `send_response(sequence_number, …)` after the handler returned
143/// (Cyclone native; XRCE/Zenoh via seq-keyed reply tables).
144#[derive(Clone, Copy)]
145pub struct PendingGetResult {
146 /// Goal whose terminal result the requester is waiting for.
147 pub goal_id: GoalUuid,
148 /// Backend reply-correlation token for the deferred `send_response`.
149 pub sequence_number: i64,
150}
151
152/// Completed goal result metadata — indexes into the result slab.
153///
154/// Entries are kept in **completion order**, which is also **increasing
155/// `offset` order**: results are appended at `result_slab_used` and the slab is
156/// compacted in place whenever an entry is reclaimed. Every reclamation path
157/// preserves that ordering (`heapless::Vec::remove` / `retain`, never
158/// `swap_remove`) because `ActionServerCore::compact_result_slab` moves
159/// survivors *down* and would clobber a not-yet-moved entry otherwise.
160#[derive(Clone, Copy)]
161pub struct CompletedResultEntry {
162 /// Unique identifier for the completed goal.
163 pub goal_id: GoalUuid,
164 /// Terminal status of the goal.
165 pub status: GoalStatusCode,
166 /// Byte offset into the result slab.
167 pub offset: usize,
168 /// Length of the serialised result in bytes.
169 pub len: usize,
170 /// `true` once a `get_result` reply carrying this result has been sent —
171 /// either the deferred flush in
172 /// [`ActionServerCore::complete_goal_raw`](crate::executor::ffi::ActionServerCoreFfi::complete_goal_raw) or the immediate reply in
173 /// [`ActionServerCore::try_handle_get_result_raw`](crate::executor::ffi::ActionServerCoreFfi::try_handle_get_result_raw).
174 ///
175 /// This is the reclamation priority. A delivered result has
176 /// served its purpose (rcl would let its `result_timeout` retire it), so it
177 /// is evicted before any result nobody has fetched yet.
178 pub delivered: bool,
179}
180
181/// One goal a `CancelGoal` request selected: what its handler is asked
182/// about, copied out of `active_goals` (see
183/// [`ActionServerCore::recv_cancel`]).
184#[derive(Debug, Clone, Copy)]
185pub(crate) struct CancelRow {
186 pub(crate) goal_id: GoalUuid,
187 pub(crate) status: GoalStatusCode,
188 stamp: Time,
189}
190
191/// A received `CancelGoal` request, selected but not yet answered: the
192/// handle between [`ActionServerCore::recv_cancel`] and
193/// [`ActionServerCore::reply_cancel`].
194pub(crate) struct CancelSelection<const MAX_GOALS: usize> {
195 /// The goal id the request named (zero for the cancel-all forms).
196 pub(crate) goal_id: GoalUuid,
197 sequence_number: i64,
198 early: Option<nros_core::CancelResponseCode>,
199 /// Selected goals, in `active_goals` order at selection time.
200 pub(crate) rows: [Option<CancelRow>; MAX_GOALS],
201}
202
203/// Information about a peeked cancel-goal
204/// request. Returned by
205/// [`ActionServerCore::try_recv_cancel_request`](crate::executor::ffi::ActionServerCoreFfi::try_recv_cancel_request).
206pub struct PendingCancelRequest {
207 /// The goal_id named in the cancel request.
208 pub goal_id: GoalUuid,
209 /// Service sequence number — pass back to
210 /// [`ActionServerCore::send_cancel_reply`](crate::executor::ffi::ActionServerCoreFfi::send_cancel_reply).
211 pub sequence_number: i64,
212 /// Snapshot of the goal's current status at peek time
213 /// (`GoalStatusCode::Unknown` if no matching active goal).
214 pub current_status: GoalStatusCode,
215}
216
217/// Information about a received goal request.
218pub struct RawGoalRequest {
219 /// The parsed goal ID.
220 pub goal_id: GoalUuid,
221 /// Sequence number for the service reply.
222 pub sequence_number: i64,
223 /// Offset into the goal buffer where the CDR payload begins.
224 /// Backends may prepend a sequence-number header (DDS) or place
225 /// the payload at offset 0 (zenoh).
226 pub data_offset: usize,
227 /// Length of valid CDR data starting at `data_offset`.
228 pub data_len: usize,
229}
230
231// ============================================================================
232// GoalUuid CDR helpers
233// ============================================================================
234
235/// Read a GoalUuid from a CDR reader as a fixed `uint8[16]` array.
236///
237/// ROS 2 actions carry the goal id as `unique_identifier_msgs/UUID`, whose
238/// single field is a **fixed-size** `uint8[16]` array — CDR fixed arrays have
239/// **no** length prefix. We must read exactly 16 bytes with no leading count,
240/// matching `unique_identifier_msgs::msg::UUID::deserialize`. (The pre-233.6
241/// framing wrote a `u32(16)` sequence prefix, which self-matched nano-ros peers
242/// but added 4 bytes a real `rcl_action` peer rejects.)
243fn read_goal_id(reader: &mut CdrReader<'_>) -> Result<GoalUuid, NodeError> {
244 let mut goal_id = GoalUuid::default();
245 for byte in &mut goal_id.uuid {
246 *byte = reader
247 .read_u8()
248 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
249 }
250 Ok(goal_id)
251}
252
253/// Write a GoalUuid into a CDR writer as a fixed `uint8[16]` array (no length
254/// prefix) — see [`read_goal_id`] for why the prefix must be absent.
255fn write_goal_id(writer: &mut CdrWriter<'_>, goal_id: &GoalUuid) -> Result<(), NodeError> {
256 for b in &goal_id.uuid {
257 writer.write_u8(*b).map_err(|_| NodeError::Serialization)?;
258 }
259 Ok(())
260}
261
262// ============================================================================
263// ActionServerCore
264// ============================================================================
265
266/// Type-agnostic action server core handling the raw-bytes protocol.
267///
268/// Manages active goal tracking (GoalUuid + status), completed result storage
269/// in a fixed-size slab, and all CDR framing for the action protocol.
270///
271/// The typed [`ActionServer`](super::handles::ActionServer) wraps this
272/// and adds `A::Goal` / `A::Feedback` / `A::Result` (de)serialization.
273pub struct ActionServerCore<
274 const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
275 const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
276 const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
277 const MAX_GOALS: usize = 4,
278> {
279 pub(crate) send_goal_server: session::RmwServiceServer,
280 pub(crate) cancel_goal_server: session::RmwServiceServer,
281 pub(crate) get_result_server: session::RmwServiceServer,
282 pub(crate) feedback_publisher: session::RmwPublisher,
283 pub(crate) status_publisher: session::RmwPublisher,
284 pub(crate) active_goals: heapless::Vec<RawActiveGoal, MAX_GOALS>,
285 pub(crate) completed_results: heapless::Vec<CompletedResultEntry, MAX_GOALS>,
286 /// `get_result` requests that arrived while their goal was still active
287 /// (Phase 237). `rclcpp_action` sends `get_result` immediately after
288 /// acceptance and expects the reply only once the goal terminates, so we
289 /// hold the request's correlation token (`sequence_number`) here and flush
290 /// it in [`Self::complete_goal_raw`]. Deferral relies on the service
291 /// backend honoring `send_response(seq)` after the handler returns — the
292 /// seq-keyed reply contract (Cyclone native; XRCE/Zenoh per Phase 237).
293 pub(crate) pending_get_results: heapless::Vec<PendingGetResult, MAX_GOALS>,
294 /// Slab storage for completed result CDR bytes.
295 ///
296 /// A bump region whose survivors are compacted on reclamation — see
297 /// [`CompletedResultEntry`] and
298 /// [`reserve_result_space`](Self::reserve_result_space).
299 pub(crate) result_slab: [u8; RESULT_BUF],
300 /// Bytes of [`result_slab`](Self::result_slab) currently held by the
301 /// entries in `completed_results`. Compaction keeps the live bytes in
302 /// `[0, result_slab_used)` with no holes, so this is exactly the sum of the
303 /// entries' `len`.
304 pub(crate) result_slab_used: usize,
305 pub(crate) goal_buffer: [u8; GOAL_BUF],
306 pub(crate) feedback_buffer: [u8; FEEDBACK_BUF],
307 pub(crate) cancel_buffer: [u8; CANCEL_BUF],
308}
309
310impl<
311 const GOAL_BUF: usize,
312 const RESULT_BUF: usize,
313 const FEEDBACK_BUF: usize,
314 const MAX_GOALS: usize,
315> ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>
316{
317 /// Issue 2360 — build a core IN PLACE at `dst`, never on the stack.
318 ///
319 /// The core holds every buffer the server uses (goal, result, feedback,
320 /// cancel: 3 KiB plus 256 B at the default sizes, plus the pending-goal
321 /// vectors), and building it as a value then moving it into the arena kept
322 /// those bytes on the registering thread's stack: 15,916 B of frame on a
323 /// Rust Zephyr action server, whose 32 KiB main stack overflowed. Each
324 /// field is written through its own pointer, the buffers by `write_bytes`.
325 ///
326 /// # Safety
327 ///
328 /// `dst` must be valid for writes of `Self` and properly aligned. Every
329 /// field is initialised on return; [`Self::_every_field_is_written`] makes
330 /// a field added later and not written here a compile error.
331 pub(crate) unsafe fn init_in_place(
332 dst: *mut Self,
333 send_goal_server: session::RmwServiceServer,
334 cancel_goal_server: session::RmwServiceServer,
335 get_result_server: session::RmwServiceServer,
336 feedback_publisher: session::RmwPublisher,
337 status_publisher: session::RmwPublisher,
338 ) {
339 use core::ptr::addr_of_mut;
340 // SAFETY: the caller's contract — `dst` is valid and aligned, so each
341 // field projection is too; every write targets a distinct field.
342 unsafe {
343 addr_of_mut!((*dst).send_goal_server).write(send_goal_server);
344 addr_of_mut!((*dst).cancel_goal_server).write(cancel_goal_server);
345 addr_of_mut!((*dst).get_result_server).write(get_result_server);
346 addr_of_mut!((*dst).feedback_publisher).write(feedback_publisher);
347 addr_of_mut!((*dst).status_publisher).write(status_publisher);
348 addr_of_mut!((*dst).active_goals).write(heapless::Vec::new());
349 addr_of_mut!((*dst).completed_results).write(heapless::Vec::new());
350 addr_of_mut!((*dst).pending_get_results).write(heapless::Vec::new());
351 addr_of_mut!((*dst).result_slab).write_bytes(0, 1);
352 addr_of_mut!((*dst).result_slab_used).write(0);
353 addr_of_mut!((*dst).goal_buffer).write_bytes(0, 1);
354 addr_of_mut!((*dst).feedback_buffer).write_bytes(0, 1);
355 addr_of_mut!((*dst).cancel_buffer).write_bytes(0, 1);
356 }
357 }
358
359 /// Never called: names every field with no `..`, so adding one to the
360 /// struct fails to compile until [`Self::init_in_place`] writes it too.
361 #[allow(dead_code)]
362 fn _every_field_is_written(&self) {
363 let Self {
364 send_goal_server: _,
365 cancel_goal_server: _,
366 get_result_server: _,
367 feedback_publisher: _,
368 status_publisher: _,
369 active_goals: _,
370 completed_results: _,
371 pending_get_results: _,
372 result_slab: _,
373 result_slab_used: _,
374 goal_buffer: _,
375 feedback_buffer: _,
376 cancel_buffer: _,
377 } = self;
378 }
379
380 /// Phase 122.3.c.6.b — construct an `ActionServerCore` from the
381 /// 5 already-built transport channels. Caller (typically the C
382 /// API's `rclc_polling_action_server_init`) owns wiring the
383 /// channels via the session's `create_*` methods.
384 pub(crate) fn from_channels(
385 send_goal_server: session::RmwServiceServer,
386 cancel_goal_server: session::RmwServiceServer,
387 get_result_server: session::RmwServiceServer,
388 feedback_publisher: session::RmwPublisher,
389 status_publisher: session::RmwPublisher,
390 ) -> Self {
391 Self {
392 send_goal_server,
393 cancel_goal_server,
394 get_result_server,
395 feedback_publisher,
396 status_publisher,
397 active_goals: heapless::Vec::new(),
398 completed_results: heapless::Vec::new(),
399 pending_get_results: heapless::Vec::new(),
400 result_slab: [0u8; RESULT_BUF],
401 result_slab_used: 0,
402 goal_buffer: [0u8; GOAL_BUF],
403 feedback_buffer: [0u8; FEEDBACK_BUF],
404 cancel_buffer: [0u8; CANCEL_BUF],
405 }
406 }
407
408 /// Try to receive a goal request from the send_goal service.
409 ///
410 /// Returns the parsed GoalUuid, sequence number, and data length.
411 /// The full CDR data (including GoalUuid) remains in `goal_buffer`.
412 pub(crate) fn try_recv_goal_request(&mut self) -> Result<Option<RawGoalRequest>, NodeError> {
413 // Capture buf base ptr before borrowing through `take_request`
414 // so we can recover the data offset after the borrow ends.
415 // DDS-style backends place a sequence-number prefix before the
416 // CDR payload; reading the buffer from offset 0 unconditionally
417 // would feed the prefix bytes to the deserializer.
418 let buf_start = self.goal_buffer.as_ptr() as usize;
419 // Phase 120: NoData (no pending request) is the steady-state
420 // expected condition — collapse it to `Ok(None)` instead of
421 // surfacing as ServiceRequestFailed. Any other transport
422 // error remains ServiceRequestFailed.
423 let request = match self.send_goal_server.take_request(&mut self.goal_buffer) {
424 Ok(opt) => opt,
425 Err(TransportError::NoData) => return Ok(None),
426 // issue 1088 — pending but no free reply slot: keep the kind.
427 Err(TransportError::WouldBlock) => {
428 return Err(NodeError::Transport(TransportError::WouldBlock));
429 }
430 Err(_) => return Err(NodeError::Transport(TransportError::ServiceRequestFailed)),
431 };
432
433 let request = match request {
434 Some(r) => r,
435 None => return Ok(None),
436 };
437
438 let data_offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
439 let data_len = request.data.len();
440 let sequence_number = request.sequence_number;
441 #[allow(clippy::drop_non_drop)]
442 drop(request);
443
444 let mut reader =
445 CdrReader::new_with_header(&self.goal_buffer[data_offset..data_offset + data_len])
446 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
447
448 let goal_id = read_goal_id(&mut reader)?;
449
450 Ok(Some(RawGoalRequest {
451 goal_id,
452 sequence_number,
453 data_offset,
454 data_len,
455 }))
456 }
457
458 /// Get a reference to the goal buffer (valid after `try_recv_goal_request`).
459 pub(crate) fn goal_buffer(&self) -> &[u8] {
460 &self.goal_buffer
461 }
462
463 /// Accept a goal: records it, sends the acceptance reply, publishes status.
464 ///
465 /// # Ordering
466 ///
467 /// The goal is recorded in `active_goals` **before** the reply goes out,
468 /// and the recording is rolled back if the reply fails. Issue 0322: this
469 /// used to reply first and then `let _ = self.active_goals.push(...)`, so
470 /// once `MAX_GOALS` (default 4) were active, a 5th `send_goal` was
471 /// answered `accepted=true` and then dropped — no execution, no feedback,
472 /// no result, no terminal status. An rclcpp/rclpy client that saw
473 /// `accepted=true` waited on its result future forever.
474 ///
475 /// A full table is now answered truthfully with `accepted=false` via
476 /// [`Self::reject_goal`], which is a contract the client already handles.
477 pub(crate) fn accept_goal(&mut self, goal_id: GoalUuid, seq: i64) -> Result<(), NodeError> {
478 // Serialize first: a serialization failure here must leave no trace,
479 // and nothing below depends on the table.
480 // Issue 2029 — the acceptance stamp: written into the reply (upstream's
481 // `SendGoal_Response.stamp`) and kept for cancel-before.
482 let stamp = Self::accept_stamp();
483 let mut writer =
484 crate::tx_writer(&mut self.cancel_buffer).map_err(|_| NodeError::BufferTooSmall)?;
485 writer.write_u8(1).map_err(|_| NodeError::Serialization)?;
486 writer
487 .write_i32(stamp.sec)
488 .map_err(|_| NodeError::Serialization)?;
489 writer
490 .write_u32(stamp.nanosec)
491 .map_err(|_| NodeError::Serialization)?;
492 let reply_len = writer.position();
493
494 // Capacity is decided BEFORE anything reaches the wire, so a full
495 // table becomes an honest rejection rather than a lie.
496 if self
497 .active_goals
498 .push(RawActiveGoal {
499 goal_id,
500 status: GoalStatusCode::Accepted,
501 stamp,
502 })
503 .is_err()
504 {
505 return self.reject_goal(seq);
506 }
507
508 if self
509 .send_goal_server
510 .send_response(seq, &self.cancel_buffer[..reply_len])
511 .is_err()
512 {
513 // The client never learned it was accepted, so un-record it —
514 // otherwise the slot leaks and lowers the effective capacity for
515 // every later goal. `pop` removes the entry pushed just above:
516 // `&mut self` means nothing else can have touched the table.
517 self.active_goals.pop();
518 return Err(NodeError::ServiceReplyFailed);
519 }
520
521 // Past this point the acceptance is on the wire and irreversible.
522 //
523 // The status-array publish is therefore NOT propagated: both C and C++
524 // callers collapse `Err` to a generic error code
525 // (`nros-c/src/action/server.rs`, `nros-cpp/src/action.rs`), so
526 // returning one here would report "accept failed" for a goal that IS
527 // accepted and running — inviting the caller to reject or retry it.
528 // The client already holds `accepted=true` and will still receive the
529 // result; a missed status sample is degraded, not broken. Issue 0322
530 // proposed propagating this; see that issue for why it is deliberately
531 // not done.
532 let _status = self.publish_status_array();
533 Ok(())
534 }
535
536 /// Issue 2029 — "now" for a goal being accepted, on the ROS clock (see
537 /// [`RawActiveGoal::stamp`]).
538 fn accept_stamp() -> Time {
539 nros_core::clock::Clock::ros_time().now()
540 }
541
542 /// Reject a goal: sends the rejection reply.
543 pub(crate) fn reject_goal(&mut self, seq: i64) -> Result<(), NodeError> {
544 // Serialize response: accepted=false + stamp
545 let mut writer =
546 crate::tx_writer(&mut self.cancel_buffer).map_err(|_| NodeError::BufferTooSmall)?;
547 writer.write_u8(0).map_err(|_| NodeError::Serialization)?;
548 writer.write_i32(0).map_err(|_| NodeError::Serialization)?;
549 writer.write_u32(0).map_err(|_| NodeError::Serialization)?;
550 let reply_len = writer.position();
551
552 self.send_goal_server
553 .send_response(seq, &self.cancel_buffer[..reply_len])
554 .map_err(|_| NodeError::ServiceReplyFailed)
555 }
556
557 /// Publish feedback with raw CDR bytes.
558 ///
559 /// Writes GoalUuid framing + raw feedback bytes into the feedback buffer
560 /// and publishes.
561 pub(crate) fn publish_feedback_raw(
562 &mut self,
563 goal_id: &GoalUuid,
564 feedback_cdr: &[u8],
565 ) -> Result<(), NodeError> {
566 // CDR header + GoalUuid + feedback must fit in FEEDBACK_BUF. Issue 2014 —
567 // the framing from `action_frame`; this read `4 + 20`, the pre-233.6
568 // GoalUuid with a sequence-length prefix.
569 let needed = crate::action_frame::FEEDBACK_PAYLOAD_OFFSET + feedback_cdr.len();
570 if needed > FEEDBACK_BUF {
571 return Err(NodeError::BufferTooSmall);
572 }
573
574 let mut writer =
575 crate::tx_writer(&mut self.feedback_buffer).map_err(|_| NodeError::BufferTooSmall)?;
576
577 write_goal_id(&mut writer, goal_id)?;
578
579 // Copy raw feedback bytes directly after GoalUuid
580 let pos = writer.position();
581 if pos + feedback_cdr.len() > FEEDBACK_BUF {
582 return Err(NodeError::BufferTooSmall);
583 }
584 self.feedback_buffer[pos..pos + feedback_cdr.len()].copy_from_slice(feedback_cdr);
585 let len = pos + feedback_cdr.len();
586
587 self.feedback_publisher
588 .publish_raw(&self.feedback_buffer[..len])
589 // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
590 // SessionLost ...), not a flattened PublishFailed.
591 .map_err(NodeError::Transport)
592 }
593
594 /// Set a goal's status and publish the updated GoalStatusArray.
595 pub(crate) fn set_goal_status(&mut self, goal_id: &GoalUuid, status: GoalStatusCode) {
596 for goal in &mut self.active_goals {
597 if goal.goal_id.uuid == goal_id.uuid {
598 goal.status = status;
599 break;
600 }
601 }
602 let _ = self.publish_status_array();
603 }
604
605 /// Compact the result slab: walk the retained entries in offset order,
606 /// move each survivor down to the first free byte, and rewrite its offset.
607 ///
608 /// Issue 0796. `completed_results` is ordered by `offset` (see
609 /// [`CompletedResultEntry`]), so `write <= entry.offset` at every step and
610 /// the `copy_within` can never clobber an entry that has not moved yet.
611 /// Bounded work: at most `MAX_GOALS` (default 4) moves totalling at most
612 /// `RESULT_BUF` bytes, and only on a reclamation.
613 fn compact_result_slab(&mut self) {
614 let mut write = 0usize;
615 for entry in self.completed_results.iter_mut() {
616 debug_assert!(
617 write <= entry.offset,
618 "completed_results must stay in increasing-offset order"
619 );
620 if entry.offset != write {
621 self.result_slab
622 .copy_within(entry.offset..entry.offset + entry.len, write);
623 entry.offset = write;
624 }
625 write += entry.len;
626 }
627 self.result_slab_used = write;
628 }
629
630 /// Drop the retained result for `goal_id`, if any, and compact.
631 /// Returns `true` when an entry was dropped.
632 fn drop_completed_result(&mut self, goal_id: &GoalUuid) -> bool {
633 match self
634 .completed_results
635 .iter()
636 .position(|e| e.goal_id.uuid == goal_id.uuid)
637 {
638 Some(idx) => {
639 self.completed_results.remove(idx);
640 self.compact_result_slab();
641 true
642 }
643 None => false,
644 }
645 }
646
647 /// Reclaim exactly one completed result. Returns `false` when there is
648 /// nothing left to reclaim.
649 ///
650 /// **Eviction policy** (issue 0796). rcl keeps a terminated goal's result
651 /// until it has been collected *and* a per-goal `result_timeout` elapses,
652 /// then `rcl_action_expire_goals()` reclaims it. We have no clock in the
653 /// core — every RTOS port spells one differently and the core is `no_std`
654 /// with no time source threaded through it — so reclamation is **on demand
655 /// and priority-ordered** instead of timed:
656 ///
657 /// 1. the oldest **delivered** result (a client already has these bytes;
658 /// this is the case rcl's timeout is really for), else
659 /// 2. the oldest result overall.
660 ///
661 /// Rule 1 means a fetched result never pins storage. Rule 2 means a client
662 /// that asks for nothing cannot wedge the server: its stale result is
663 /// displaced by newer ones rather than blocking every later goal. A goal
664 /// evicted under rule 2 whose client asks *later* is answered
665 /// `GoalStatusCode::Unknown` with the default result by
666 /// [`try_handle_get_result_raw`](Self::try_handle_get_result_raw) — degraded,
667 /// but an answer, where the pre-0796 code left the requester hanging
668 /// forever.
669 fn evict_one_completed_result(&mut self) -> bool {
670 if self.completed_results.is_empty() {
671 return false;
672 }
673 let idx = self
674 .completed_results
675 .iter()
676 .position(|e| e.delivered)
677 .unwrap_or(0);
678 self.completed_results.remove(idx);
679 self.compact_result_slab();
680 true
681 }
682
683 /// Make room for one more entry of `needed` bytes, reclaiming completed
684 /// results as required.
685 ///
686 /// `Err(NodeError::BufferTooSmall)` means the result can never be retained
687 /// because it exceeds `RESULT_BUF` outright — an empty slab would not hold
688 /// it either, so the caller must raise the action server's `RESULT_BUF`.
689 /// That is the ONLY failure: a full slab or a full entry table is
690 /// reclaimed, not refused.
691 fn reserve_result_space(&mut self, needed: usize) -> Result<(), NodeError> {
692 if needed > RESULT_BUF {
693 return Err(NodeError::BufferTooSmall);
694 }
695 loop {
696 if self.completed_results.len() < MAX_GOALS
697 && RESULT_BUF - self.result_slab_used >= needed
698 {
699 return Ok(());
700 }
701 if !self.evict_one_completed_result() {
702 // Unreachable while `needed <= RESULT_BUF` and `MAX_GOALS >= 1`,
703 // but the loop must not spin on a degenerate instantiation.
704 return Err(NodeError::BufferTooSmall);
705 }
706 }
707 }
708
709 /// Mark `goal_id`'s retained result as fetched, making it the first
710 /// candidate for reclamation.
711 fn mark_result_delivered(&mut self, goal_id: &GoalUuid) {
712 for entry in self.completed_results.iter_mut() {
713 if entry.goal_id.uuid == goal_id.uuid {
714 entry.delivered = true;
715 break;
716 }
717 }
718 }
719
720 /// Reclaim every completed result whose `get_result` reply has already been
721 /// sent — nano-ros's analogue of `rcl_action_expire_goals()`. Returns the
722 /// number of entries reclaimed.
723 ///
724 /// Calling this is **optional**: [`complete_goal_raw`](Self::complete_goal_raw)
725 /// reclaims on demand, so a server that never calls it still runs forever.
726 /// It exists for a server that would rather return the memory eagerly (e.g.
727 /// before a long idle period) than at the next completion.
728 pub(crate) fn expire_completed_results(&mut self) -> usize {
729 let before = self.completed_results.len();
730 self.completed_results.retain(|e| !e.delivered);
731 let removed = before - self.completed_results.len();
732 if removed > 0 {
733 self.compact_result_slab();
734 }
735 removed
736 }
737
738 /// Number of completed results currently retained.
739 pub(crate) fn completed_result_count(&self) -> usize {
740 self.completed_results.len()
741 }
742
743 /// Bytes of the result slab currently held by retained results.
744 pub(crate) fn result_slab_used(&self) -> usize {
745 self.result_slab_used
746 }
747
748 /// Is `goal_id` a goal this server still knows about?
749 ///
750 /// rcl's `rcl_action_server_goal_exists` — phase-417 W4.b, ledger row
751 /// `c:action_server_goal_exists`. rcl searches the server's goal-handle
752 /// table, which retains a goal after it terminates until
753 /// `rcl_action_expire_goals` reclaims it, so a terminated-but-unreclaimed
754 /// goal EXISTS there. Ours asks the same question over the two places a
755 /// goal can live here: the active set, and the completed-result slab.
756 ///
757 /// Both halves are load-bearing, and that is why this row could not be
758 /// closed as a documentation fix pointing at the status lookup. A status
759 /// lookup reads the ACTIVE set only, so it answers "not found" — which the
760 /// C surface maps to `RCLC_RET_NOT_FOUND` — for a goal that has completed
761 /// and whose result is still sitting there to be fetched. "Not found" and
762 /// "does not exist" therefore disagreed over exactly the window in which a
763 /// client is expected to call `get_result`.
764 pub(crate) fn goal_exists(&self, goal_id: &GoalUuid) -> bool {
765 self.active_goals
766 .iter()
767 .any(|g| g.goal_id.uuid == goal_id.uuid)
768 || self.has_completed_result(goal_id)
769 }
770
771 /// `true` while `goal_id`'s completed result is still retained (i.e. a
772 /// `get_result` for it would be answered from the slab rather than as
773 /// `Unknown`).
774 pub(crate) fn has_completed_result(&self, goal_id: &GoalUuid) -> bool {
775 self.completed_results
776 .iter()
777 .any(|e| e.goal_id.uuid == goal_id.uuid)
778 }
779
780 /// Complete a goal: remove from active, store raw result CDR in slab,
781 /// publish status.
782 ///
783 /// The goal moves from `active_goals` to `completed_results`, and the
784 /// status array published at the end of this function carries BOTH lists
785 /// (issue 1361), so the terminal status is on the wire. See
786 /// [`publish_status_array`](Self::publish_status_array) for how long it
787 /// stays there.
788 ///
789 /// One case still publishes no terminal entry, and it is the `Err` arm
790 /// below: when `result_cdr` exceeds `RESULT_BUF` the goal enters NEITHER
791 /// list, so the array omits it exactly as it omitted every terminated goal
792 /// before 1361. That is not a regression — it was already the behaviour —
793 /// and the fix for it is the one this function's `Err` already names: raise
794 /// `RESULT_BUF`.
795 ///
796 /// # Errors
797 ///
798 /// `NodeError::BufferTooSmall` when `result_cdr` is larger than
799 /// `RESULT_BUF` and therefore cannot be retained for a later `get_result`.
800 /// Any client already waiting on `~/_action/get_result` is still answered
801 /// (straight from `result_cdr`), and a status array is still published —
802 /// but it carries no entry for this goal (see above), and a *later*
803 /// `get_result` for it gets `GoalStatusCode::Unknown`. Raise the server's
804 /// `RESULT_BUF`.
805 ///
806 /// Issue 0796: this returned `()`, so the pre-fix slab exhaustion — the
807 /// server silently dropping every result once the bump allocator hit
808 /// `RESULT_BUF`, and silently stranding every waiting requester with it —
809 /// was invisible to the caller. A full slab is no longer a failure at all
810 /// (it is reclaimed), and the one remaining failure is reported.
811 pub(crate) fn complete_goal_raw(
812 &mut self,
813 goal_id: &GoalUuid,
814 status: GoalStatusCode,
815 result_cdr: &[u8],
816 ) -> Result<(), NodeError> {
817 // Remove from active goals
818 if let Some(pos) = self
819 .active_goals
820 .iter()
821 .position(|g| g.goal_id.uuid == goal_id.uuid)
822 {
823 self.active_goals.swap_remove(pos);
824 }
825
826 // Re-completing a goal replaces its retained result rather than
827 // stacking a second copy of it in the slab.
828 self.drop_completed_result(goal_id);
829
830 // Store result CDR in the slab, reclaiming older results if needed.
831 let stored = match self.reserve_result_space(result_cdr.len()) {
832 Ok(()) => {
833 let offset = self.result_slab_used;
834 let end = offset + result_cdr.len();
835 self.result_slab[offset..end].copy_from_slice(result_cdr);
836 self.result_slab_used = end;
837 // `reserve_result_space` guaranteed a free entry slot.
838 let pushed = self
839 .completed_results
840 .push(CompletedResultEntry {
841 goal_id: *goal_id,
842 status,
843 offset,
844 len: result_cdr.len(),
845 delivered: false,
846 })
847 .is_ok();
848 debug_assert!(pushed, "reserve_result_space must leave an entry slot");
849 Some((offset, result_cdr.len()))
850 }
851 Err(_) => None,
852 };
853
854 // Phase 237 — flush any get_result requests that arrived while this goal
855 // was still active. Reply to each held requester via its retained
856 // `sequence_number`.
857 //
858 // Issue 0796: this used to be skipped entirely when the result could not
859 // be stored, so an oversized (or, pre-fix, merely unlucky) result left
860 // an `rclcpp_action` client waiting on its result future forever. The
861 // waiter is now answered from `result_cdr` directly when the slab could
862 // not take it — the bytes are right here; only the *retention* failed.
863 let mut delivered_any = false;
864 let mut i = 0;
865 while i < self.pending_get_results.len() {
866 if self.pending_get_results[i].goal_id.uuid == goal_id.uuid {
867 let seq = self.pending_get_results[i].sequence_number;
868 // swap_remove moves the last entry into slot `i`; re-check `i`.
869 let _ = self.pending_get_results.swap_remove(i);
870 let sent = match stored {
871 Some((offset, len)) => {
872 self.reply_get_result_from_slab(seq, status, offset, len)
873 }
874 None => self.reply_get_result_bytes(seq, status, result_cdr),
875 };
876 delivered_any |= sent.is_ok();
877 } else {
878 i += 1;
879 }
880 }
881 if delivered_any {
882 self.mark_result_delivered(goal_id);
883 }
884
885 let _ = self.publish_status_array();
886
887 if stored.is_some() {
888 Ok(())
889 } else {
890 Err(NodeError::BufferTooSmall)
891 }
892 }
893
894 /// Phase 122.3.c.6.e — register a `Waker` that fires when a new
895 /// send_goal request arrives. Event-driven action servers
896 /// register here in place of polling `try_recv_goal_request` on
897 /// a timer.
898 pub(crate) fn register_goal_waker(&self, waker: &core::task::Waker) -> bool {
899 use nros_rmw::ServiceTrait;
900 self.send_goal_server.register_waker(waker)
901 }
902
903 /// Phase 122.3.c.6.e — register a `Waker` that fires when a
904 /// cancel-goal request arrives.
905 pub(crate) fn register_cancel_waker(&self, waker: &core::task::Waker) -> bool {
906 use nros_rmw::ServiceTrait;
907 self.cancel_goal_server.register_waker(waker)
908 }
909
910 /// Phase 122.3.c.6.e — register a `Waker` that fires when a
911 /// get_result query arrives.
912 pub(crate) fn register_get_result_waker(&self, waker: &core::task::Waker) -> bool {
913 use nros_rmw::ServiceTrait;
914 self.get_result_server.register_waker(waker)
915 }
916
917 /// Phase 122.3.c.6.d — peek a pending cancel-goal request without
918 /// generating a reply. Returns the goal_id named in the request,
919 /// the matching service sequence number (use it with
920 /// [`send_cancel_reply`](Self::send_cancel_reply)), and the
921 /// goal's current status (`GoalStatusCode::Unknown` if no such
922 /// active goal). Returns `Ok(None)` when no cancel request is
923 /// pending.
924 ///
925 /// Used by L1 polling-mode action servers (nros-c / nros-cpp C
926 /// FFI) that want to drive cancel-decision policy without
927 /// passing a Rust closure across the C ABI. See the matching
928 /// [`send_cancel_reply`](Self::send_cancel_reply) for the reply
929 /// side. The high-level closure-based
930 /// [`try_handle_cancel`](Self::try_handle_cancel) keeps working
931 /// and now delegates to this pair.
932 pub(crate) fn try_recv_cancel_request(
933 &mut self,
934 ) -> Result<Option<PendingCancelRequest>, NodeError> {
935 let buf_start = self.cancel_buffer.as_ptr() as usize;
936 let request = match self
937 .cancel_goal_server
938 .take_request(&mut self.cancel_buffer)
939 {
940 Ok(Some(r)) => r,
941 Ok(None) | Err(TransportError::NoData) => return Ok(None),
942 // issue 1088 — pending but no free reply slot: keep the kind.
943 Err(TransportError::WouldBlock) => {
944 return Err(NodeError::Transport(TransportError::WouldBlock));
945 }
946 Err(_) => return Err(NodeError::Transport(TransportError::ServiceRequestFailed)),
947 };
948
949 let data_offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
950 let data_len = request.data.len();
951 let sequence_number = request.sequence_number;
952 #[allow(clippy::drop_non_drop)]
953 drop(request);
954
955 let mut reader =
956 CdrReader::new_with_header(&self.cancel_buffer[data_offset..data_offset + data_len])
957 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
958
959 let goal_id = read_goal_id(&mut reader)?;
960 let current_status = self.find_goal_status(&goal_id);
961
962 Ok(Some(PendingCancelRequest {
963 goal_id,
964 sequence_number,
965 current_status,
966 }))
967 }
968
969 /// Phase 122.3.c.6.d — send the reply to a previously-peeked
970 /// cancel-goal request. `sequence_number` must match the value
971 /// returned by [`try_recv_cancel_request`](Self::try_recv_cancel_request).
972 ///
973 /// `return_code` is the overall RPC status (`CancelResponseCode::Ok`
974 /// = at least one cancel honoured; other variants = whole-request
975 /// failure). `accepted` lists the goals that transition to
976 /// `Canceling`; this function flips their stored status before
977 /// publishing the status array.
978 ///
979 /// Issue 0796 — the parameter is a [`nros_core::CancelResponseCode`], not
980 /// the per-goal [`nros_core::CancelResponse`] a cancel callback returns.
981 /// The two were one type and their discriminants overlap with opposite
982 /// meanings (`Reject`/`Ok` are both 0), so this signature is what stops a
983 /// per-goal answer being written into the RPC field.
984 pub(crate) fn send_cancel_reply(
985 &mut self,
986 sequence_number: i64,
987 return_code: nros_core::CancelResponseCode,
988 accepted: &[GoalUuid],
989 ) -> Result<(), NodeError> {
990 for id in accepted {
991 self.set_goal_status(id, GoalStatusCode::Canceling);
992 }
993
994 let mut writer =
995 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
996 writer
997 .write_i8(return_code as i8)
998 .map_err(|_| NodeError::Serialization)?;
999 let count = u32::try_from(accepted.len()).unwrap_or(u32::MAX);
1000 writer
1001 .write_u32(count)
1002 .map_err(|_| NodeError::Serialization)?;
1003 for id in accepted {
1004 write_goal_id(&mut writer, id)?;
1005 // GoalInfo.stamp — the goal's acceptance stamp (issue 2029), zero
1006 // for an id this server does not hold.
1007 let stamp = self
1008 .active_goals
1009 .iter()
1010 .find(|g| g.goal_id.uuid == id.uuid)
1011 .map(|g| g.stamp)
1012 .unwrap_or_default();
1013 writer
1014 .write_i32(stamp.sec)
1015 .map_err(|_| NodeError::Serialization)?;
1016 writer
1017 .write_u32(stamp.nanosec)
1018 .map_err(|_| NodeError::Serialization)?;
1019 }
1020 let reply_len = writer.position();
1021
1022 self.cancel_goal_server
1023 .send_response(sequence_number, &self.goal_buffer[..reply_len])
1024 .map_err(|_| NodeError::ServiceReplyFailed)?;
1025
1026 if !accepted.is_empty() {
1027 let _ = self.publish_status_array();
1028 }
1029
1030 Ok(())
1031 }
1032
1033 /// Try to handle a cancel_goal request (type-agnostic) — upstream
1034 /// `rcl_action_process_cancel_request` + rclcpp's per-goal callback loop.
1035 ///
1036 /// Issue 2029 — the request's `GoalInfo` is read as a PAIR, the way
1037 /// `action_msgs/srv/CancelGoal` defines it:
1038 ///
1039 /// | goal id | stamp | goals selected |
1040 /// |----------|----------|--------------------------------------------------|
1041 /// | zero | zero | every cancelable goal (cancel-all) |
1042 /// | zero | non-zero | every cancelable goal accepted at or before it |
1043 /// | non-zero | zero | that goal |
1044 /// | non-zero | non-zero | that goal, plus those accepted at or before it |
1045 ///
1046 /// A goal is cancelable while `Accepted` or `Executing`. `cancel_handler`
1047 /// is asked ONCE PER SELECTED GOAL; the goals it accepts move to
1048 /// `Canceling` and are listed in the reply's `goals_canceling`, each with
1049 /// its acceptance stamp. Return codes: a non-zero id naming no active goal
1050 /// answers `UnknownGoal` (or `GoalTerminated` when its result is still
1051 /// retained) without asking the handler, exactly as `rcl_action` does;
1052 /// otherwise an empty `goals_canceling` is `Rejected` and a non-empty one
1053 /// `Ok`. The status array is published once if anything moved.
1054 ///
1055 /// Before 2029 only the goal id was read: the zero id was an unknown goal,
1056 /// so cancel-all and cancel-before cancelled nothing — and the handler was
1057 /// asked about a goal that did not exist.
1058 ///
1059 /// Returns the goal id the request NAMED (zero for the two zero-id forms)
1060 /// and [`nros_core::CancelResponse::Accept`] if at least one goal moved to
1061 /// `Canceling`.
1062 pub(crate) fn try_handle_cancel(
1063 &mut self,
1064 mut cancel_handler: impl FnMut(&GoalUuid, GoalStatusCode) -> nros_core::CancelResponse,
1065 ) -> Result<Option<(GoalUuid, nros_core::CancelResponse)>, NodeError> {
1066 let Some(selection) = self.recv_cancel()? else {
1067 return Ok(None);
1068 };
1069 // (issue 0796) the handler answers about ONE goal; `reply_cancel`
1070 // carries the RPC-level return code.
1071 let mut accepted = [false; MAX_GOALS];
1072 for (slot, row) in accepted.iter_mut().zip(&selection.rows) {
1073 if let Some(row) = row {
1074 *slot =
1075 cancel_handler(&row.goal_id, row.status) == nros_core::CancelResponse::Accept;
1076 }
1077 }
1078 let response = self.reply_cancel(&selection, &accepted)?;
1079 Ok(Some((selection.goal_id, response)))
1080 }
1081
1082 /// The first half of [`try_handle_cancel`](Self::try_handle_cancel): take
1083 /// one pending `CancelGoal` request and select the goals it names, without
1084 /// asking anyone about them.
1085 ///
1086 /// The selection is a COPY of what the handler needs (id, status,
1087 /// acceptance stamp per goal), so the caller asks its handler with no
1088 /// borrow of this core held. A C handler may complete the goal it is
1089 /// asked about, which removes it from `active_goals` and moves the goals
1090 /// behind it; a handler asked from inside a loop over that array would
1091 /// have its answers applied to the wrong goals (phase-573 W2b).
1092 pub(crate) fn recv_cancel(&mut self) -> Result<Option<CancelSelection<MAX_GOALS>>, NodeError> {
1093 let buf_start = self.cancel_buffer.as_ptr() as usize;
1094 // Phase 120: NoData == steady-state idle; map to Ok(None).
1095 let request = match self
1096 .cancel_goal_server
1097 .take_request(&mut self.cancel_buffer)
1098 {
1099 Ok(Some(r)) => r,
1100 Ok(None) | Err(TransportError::NoData) => return Ok(None),
1101 // issue 1088 — pending but no free reply slot: keep the kind.
1102 Err(TransportError::WouldBlock) => {
1103 return Err(NodeError::Transport(TransportError::WouldBlock));
1104 }
1105 Err(_) => return Err(NodeError::Transport(TransportError::ServiceRequestFailed)),
1106 };
1107
1108 let data_offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
1109 let data_len = request.data.len();
1110 let sequence_number = request.sequence_number;
1111 #[allow(clippy::drop_non_drop)]
1112 drop(request);
1113
1114 let mut reader =
1115 CdrReader::new_with_header(&self.cancel_buffer[data_offset..data_offset + data_len])
1116 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1117
1118 let goal_id = read_goal_id(&mut reader)?;
1119 // GoalInfo.stamp (builtin_interfaces/Time). A pre-2029 nano-ros client
1120 // sent the id alone; a missing stamp reads as zero, which is what that
1121 // client meant.
1122 let stamp_sec = reader.read_i32().unwrap_or(0);
1123 let stamp_nanosec = reader.read_u32().unwrap_or(0);
1124 let request_stamp = Time::new(stamp_sec, stamp_nanosec);
1125
1126 let (selected, early) = self.select_cancel_goals(&goal_id, request_stamp);
1127 let mut rows = [None; MAX_GOALS];
1128 for ((row, goal), picked) in rows.iter_mut().zip(&self.active_goals).zip(selected) {
1129 if picked {
1130 *row = Some(CancelRow {
1131 goal_id: goal.goal_id,
1132 status: goal.status,
1133 stamp: goal.stamp,
1134 });
1135 }
1136 }
1137 Ok(Some(CancelSelection {
1138 goal_id,
1139 sequence_number,
1140 early,
1141 rows,
1142 }))
1143 }
1144
1145 /// The second half of [`try_handle_cancel`](Self::try_handle_cancel):
1146 /// answer a [`recv_cancel`](Self::recv_cancel) selection. `accepted[i]`
1147 /// is the handler's answer for `selection.rows[i]`.
1148 ///
1149 /// Goals are found again BY ID, never by position, because the handler
1150 /// may have changed `active_goals`. An accepted goal still `Accepted` or
1151 /// `Executing` moves to `Canceling`; one the handler already finished
1152 /// keeps its terminal status. Either way it is listed in the reply's
1153 /// `goals_canceling`, with the acceptance stamp it had when selected.
1154 pub(crate) fn reply_cancel(
1155 &mut self,
1156 selection: &CancelSelection<MAX_GOALS>,
1157 accepted: &[bool; MAX_GOALS],
1158 ) -> Result<nros_core::CancelResponse, NodeError> {
1159 let canceling = || {
1160 selection
1161 .rows
1162 .iter()
1163 .zip(accepted)
1164 .filter_map(|(row, yes)| row.filter(|_| *yes))
1165 };
1166 let mut any = false;
1167 for row in canceling() {
1168 any = true;
1169 if let Some(goal) = self.active_goals.iter_mut().find(|g| {
1170 g.goal_id.uuid == row.goal_id.uuid
1171 && matches!(
1172 g.status,
1173 GoalStatusCode::Accepted | GoalStatusCode::Executing
1174 )
1175 }) {
1176 goal.status = GoalStatusCode::Canceling;
1177 }
1178 }
1179
1180 let return_code = match selection.early {
1181 Some(code) => code,
1182 None if any => nros_core::CancelResponseCode::Ok,
1183 None => nros_core::CancelResponseCode::Rejected,
1184 };
1185
1186 // Serialize response: return_code (i8) + goals_canceling (sequence of GoalInfo)
1187 let mut writer =
1188 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
1189 writer
1190 .write_i8(return_code as i8)
1191 .map_err(|_| NodeError::Serialization)?;
1192 let count = canceling().count() as u32;
1193 writer
1194 .write_u32(count)
1195 .map_err(|_| NodeError::Serialization)?;
1196 for row in canceling() {
1197 write_goal_id(&mut writer, &row.goal_id)?;
1198 writer
1199 .write_i32(row.stamp.sec)
1200 .map_err(|_| NodeError::Serialization)?;
1201 writer
1202 .write_u32(row.stamp.nanosec)
1203 .map_err(|_| NodeError::Serialization)?;
1204 }
1205 let reply_len = writer.position();
1206
1207 self.cancel_goal_server
1208 .send_response(selection.sequence_number, &self.goal_buffer[..reply_len])
1209 .map_err(|_| NodeError::ServiceReplyFailed)?;
1210
1211 if any {
1212 let _ = self.publish_status_array();
1213 }
1214
1215 Ok(if any {
1216 nros_core::CancelResponse::Accept
1217 } else {
1218 nros_core::CancelResponse::Reject
1219 })
1220 }
1221
1222 /// Issue 2029 — which active goals a `CancelGoal` request selects, and the
1223 /// return code that ends it before any handler runs. See
1224 /// [`try_handle_cancel`](Self::try_handle_cancel) for the table.
1225 fn select_cancel_goals(
1226 &self,
1227 goal_id: &GoalUuid,
1228 request_stamp: Time,
1229 ) -> ([bool; MAX_GOALS], Option<nros_core::CancelResponseCode>) {
1230 let mut selected = [false; MAX_GOALS];
1231 let zero_id = goal_id.uuid == [0u8; 16];
1232 let zero_stamp = request_stamp.sec == 0 && request_stamp.nanosec == 0;
1233 let cancelable = |g: &RawActiveGoal| {
1234 matches!(
1235 g.status,
1236 GoalStatusCode::Accepted | GoalStatusCode::Executing
1237 )
1238 };
1239 let before = |g: &RawActiveGoal| g.stamp.to_nanos() <= request_stamp.to_nanos();
1240
1241 if !zero_id {
1242 match self
1243 .active_goals
1244 .iter()
1245 .position(|g| g.goal_id.uuid == goal_id.uuid)
1246 {
1247 Some(i) => {
1248 if cancelable(&self.active_goals[i]) {
1249 selected[i] = true;
1250 }
1251 }
1252 None => {
1253 let code = if self
1254 .completed_results
1255 .iter()
1256 .any(|c| c.goal_id.uuid == goal_id.uuid)
1257 {
1258 nros_core::CancelResponseCode::GoalTerminated
1259 } else {
1260 nros_core::CancelResponseCode::UnknownGoal
1261 };
1262 return (selected, Some(code));
1263 }
1264 }
1265 if zero_stamp {
1266 return (selected, None);
1267 }
1268 }
1269 for (i, g) in self.active_goals.iter().enumerate() {
1270 if cancelable(g) && (zero_stamp || before(g)) {
1271 selected[i] = true;
1272 }
1273 }
1274 (selected, None)
1275 }
1276
1277 /// Try to handle a get_result request using raw bytes.
1278 ///
1279 /// For completed goals, sends the stored raw result CDR from the slab.
1280 /// For active/unknown goals, sends the provided `default_result_cdr` bytes.
1281 ///
1282 /// `default_result_cdr` should contain serialized result data (without CDR
1283 /// header or status byte) — typically `A::Result::default()` serialized.
1284 pub(crate) fn try_handle_get_result_raw(
1285 &mut self,
1286 default_result_cdr: &[u8],
1287 ) -> Result<Option<GoalUuid>, NodeError> {
1288 let buf_start = self.goal_buffer.as_ptr() as usize;
1289 // Phase 120: NoData == steady-state idle; map to Ok(None).
1290 let request = match self.get_result_server.take_request(&mut self.goal_buffer) {
1291 Ok(Some(r)) => r,
1292 Ok(None) | Err(TransportError::NoData) => return Ok(None),
1293 // issue 1088 — pending but no free reply slot: keep the kind.
1294 Err(TransportError::WouldBlock) => {
1295 return Err(NodeError::Transport(TransportError::WouldBlock));
1296 }
1297 Err(_) => return Err(NodeError::Transport(TransportError::ServiceRequestFailed)),
1298 };
1299
1300 let data_offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
1301 let data_len = request.data.len();
1302 let sequence_number = request.sequence_number;
1303 #[allow(clippy::drop_non_drop)]
1304 drop(request);
1305
1306 let mut reader =
1307 CdrReader::new_with_header(&self.goal_buffer[data_offset..data_offset + data_len])
1308 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1309
1310 let goal_id = read_goal_id(&mut reader)?;
1311
1312 // Look up in completed results
1313 let completed = self
1314 .completed_results
1315 .iter()
1316 .find(|c| c.goal_id.uuid == goal_id.uuid);
1317
1318 if let Some(entry) = completed {
1319 // Completed: send status + stored result CDR from the slab.
1320 let (off, len, status) = (entry.offset, entry.len, entry.status);
1321 self.reply_get_result_from_slab(sequence_number, status, off, len)?;
1322 // Issue 0796 — the client now holds these bytes, so this entry
1323 // becomes the first candidate for reclamation.
1324 self.mark_result_delivered(&goal_id);
1325 } else if self
1326 .active_goals
1327 .iter()
1328 .any(|g| g.goal_id.uuid == goal_id.uuid)
1329 {
1330 // Active goal → DEFER (Phase 237). `rclcpp_action` sends get_result
1331 // right after acceptance and expects the reply only once the goal
1332 // terminates; replying now with a non-terminal status makes the
1333 // client treat an unfinished goal as done. Hold the request's
1334 // correlation token; `complete_goal_raw` flushes it. The backend
1335 // retains the reply token keyed by `sequence_number`.
1336 if self
1337 .pending_get_results
1338 .push(PendingGetResult {
1339 goal_id,
1340 sequence_number,
1341 })
1342 .is_err()
1343 {
1344 // Table full — fail loud rather than silently strand the
1345 // requester (caller surfaces it; the request is not re-queued).
1346 return Err(NodeError::BufferTooSmall);
1347 }
1348 } else {
1349 // Unknown goal → reply immediately with UNKNOWN + default result.
1350 // Issue 0796: a goal whose result was reclaimed (evicted by a newer
1351 // completion) lands here too. That is deliberate — an honest
1352 // `Unknown` beats an unanswered query.
1353 self.reply_get_result_bytes(
1354 sequence_number,
1355 GoalStatusCode::Unknown,
1356 default_result_cdr,
1357 )?;
1358 }
1359
1360 Ok(Some(goal_id))
1361 }
1362
1363 /// Write the `get_result` reply prologue — `[CDR header][status i8][pad to
1364 /// 4]` — into `goal_buffer` and return the offset the result bytes go at.
1365 ///
1366 /// The align-to-4 matters: the result CDR starts with a `u32` sequence
1367 /// length the reader will `align(4)` to.
1368 fn write_get_result_header(&mut self, status: GoalStatusCode) -> Result<usize, NodeError> {
1369 let mut writer =
1370 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
1371 writer
1372 .write_i8(status as i8)
1373 .map_err(|_| NodeError::Serialization)?;
1374 writer.align(4).map_err(|_| NodeError::Serialization)?;
1375 Ok(writer.position())
1376 }
1377
1378 /// Build + send a `get_result` reply — `[status i8][align(4)][result CDR]`
1379 /// — copying the result bytes from the slab. Shared by the immediate
1380 /// completed-goal path and the deferred flush in `complete_goal_raw`
1381 /// (Phase 237). `goal_buffer` and `result_slab` are disjoint fields, so the
1382 /// header build (into `goal_buffer`) and the slab copy don't alias.
1383 fn reply_get_result_from_slab(
1384 &mut self,
1385 sequence_number: i64,
1386 status: GoalStatusCode,
1387 slab_offset: usize,
1388 slab_len: usize,
1389 ) -> Result<(), NodeError> {
1390 let pos = self.write_get_result_header(status)?;
1391 if pos + slab_len > GOAL_BUF {
1392 return Err(NodeError::BufferTooSmall);
1393 }
1394 self.goal_buffer[pos..pos + slab_len]
1395 .copy_from_slice(&self.result_slab[slab_offset..slab_offset + slab_len]);
1396 let reply_len = pos + slab_len;
1397 self.get_result_server
1398 .send_response(sequence_number, &self.goal_buffer[..reply_len])
1399 .map_err(|_| NodeError::ServiceReplyFailed)
1400 }
1401
1402 /// Same reply, from a caller-owned slice instead of the slab.
1403 ///
1404 /// Used for the `Unknown` reply and — issue 0796 — for a waiter whose
1405 /// result was too large to retain: the bytes exist in the caller's buffer
1406 /// even when the slab could not take a copy. `bytes` must NOT alias
1407 /// `self` (the slab path is [`reply_get_result_from_slab`]).
1408 fn reply_get_result_bytes(
1409 &mut self,
1410 sequence_number: i64,
1411 status: GoalStatusCode,
1412 bytes: &[u8],
1413 ) -> Result<(), NodeError> {
1414 let pos = self.write_get_result_header(status)?;
1415 if pos + bytes.len() > GOAL_BUF {
1416 return Err(NodeError::BufferTooSmall);
1417 }
1418 self.goal_buffer[pos..pos + bytes.len()].copy_from_slice(bytes);
1419 let reply_len = pos + bytes.len();
1420 self.get_result_server
1421 .send_response(sequence_number, &self.goal_buffer[..reply_len])
1422 .map_err(|_| NodeError::ServiceReplyFailed)
1423 }
1424
1425 /// Get the number of active goals.
1426 pub(crate) fn active_goal_count(&self) -> usize {
1427 self.active_goals.len()
1428 }
1429
1430 /// Get a reference to all active goals.
1431 pub(crate) fn active_goals(&self) -> &[RawActiveGoal] {
1432 &self.active_goals
1433 }
1434
1435 /// Issue 2029 — the acceptance stamp of an active goal, zero if unknown.
1436 pub(crate) fn goal_stamp(&self, goal_id: &GoalUuid) -> Time {
1437 self.active_goals
1438 .iter()
1439 .find(|g| g.goal_id.uuid == goal_id.uuid)
1440 .map(|g| g.stamp)
1441 .unwrap_or_default()
1442 }
1443
1444 /// Find the status of a goal (active or unknown).
1445 pub(crate) fn find_goal_status(&self, goal_id: &GoalUuid) -> GoalStatusCode {
1446 self.active_goals
1447 .iter()
1448 .find(|g| g.goal_id.uuid == goal_id.uuid)
1449 .map(|g| g.status)
1450 .unwrap_or(GoalStatusCode::Unknown)
1451 }
1452
1453 /// Compile-time bound on the status array (issue 1361).
1454 ///
1455 /// `publish_status_array` now writes up to `2 * MAX_GOALS` entries, and the
1456 /// scratch buffer is a fixed [`STATUS_ARRAY_BUF`]. An instantiation whose
1457 /// worst case does not fit would not fail loudly — `CdrWriter` would answer
1458 /// `BufferTooSmall`, `publish_status_array` would return `Err`, and every
1459 /// caller discards that with `let _ =`, so the terminal status would go
1460 /// missing exactly the way 1361 is about. That silent overflow was reachable
1461 /// BEFORE this change too (at `MAX_GOALS > 18`, active goals alone); nothing
1462 /// guarded it. This is the guard, and it names the numbers.
1463 ///
1464 /// 512 bytes hold 18 entries, so `MAX_GOALS` may be at most 9. The default
1465 /// is 4 and no in-tree instantiation exceeds it.
1466 const STATUS_ARRAY_FITS: () = assert!(
1467 status_array_bytes(2 * MAX_GOALS) <= STATUS_ARRAY_BUF,
1468 "MAX_GOALS is too large for STATUS_ARRAY_BUF: the status array carries \
1469 active goals AND retained completed results, i.e. up to 2 * MAX_GOALS \
1470 entries of 28 bytes. 512 bytes hold 18 entries, so MAX_GOALS <= 9."
1471 );
1472
1473 /// Publish the current `GoalStatusArray` on the status topic.
1474 ///
1475 /// The array carries **active goals and retained completed results**, not
1476 /// active goals alone (issue 1361, option 2). Before that, a terminated goal
1477 /// left `active_goals` in `complete_goal_raw`'s first statement and the
1478 /// publish at the end of the same function was therefore structurally
1479 /// guaranteed to omit the goal it was about: every client saw ACCEPTED and
1480 /// then an empty array, on every backend, and a transient-local late joiner
1481 /// retained that empty array.
1482 ///
1483 /// **The visibility promise this makes, which is NOT upstream's.**
1484 /// `rcl_action` retires a terminated goal on a per-goal `result_timeout`
1485 /// (15 minutes by default). The core has no clock, so a nano-ros action
1486 /// server promises instead: *a terminated goal stays in `/status` until its
1487 /// result is reclaimed* — that is, until the client fetches it and
1488 /// [`expire_completed_results`](Self::expire_completed_results) runs, or
1489 /// until `MAX_GOALS` newer goals displace it through
1490 /// `evict_one_completed_result`. It is a
1491 /// rule a caller can reason about, and it is the closest thing to upstream
1492 /// reachable without a time source; it is deliberately not a duration.
1493 ///
1494 /// Reclamation itself does NOT republish, which is what the late joiner
1495 /// rides on: the last sample the publisher retained still names the terminal
1496 /// status after the result behind it has been returned to the slab.
1497 ///
1498 /// Consequence for a reader: an entry in the array is no longer necessarily
1499 /// an ACTIVE goal, so a count of entries is not a count of active goals —
1500 /// read each entry's `status`. That is what `rcl_action` has always
1501 /// published, so a stock `rclcpp_action` client already does it, and
1502 /// nothing in this tree subscribes to `/status` at all
1503 /// (`ActionClientCore` holds three service clients and a feedback
1504 /// subscriber, no status subscriber). Callers wanting the active count have
1505 /// [`active_goal_count`](Self::active_goal_count), which still reads
1506 /// `active_goals` alone.
1507 pub(crate) fn publish_status_array(&self) -> Result<(), NodeError> {
1508 // Force the bound above to be evaluated for this instantiation.
1509 let () = Self::STATUS_ARRAY_FITS;
1510
1511 let mut buf = [0u8; STATUS_ARRAY_BUF];
1512 let mut writer = crate::tx_writer(&mut buf).map_err(|_| NodeError::BufferTooSmall)?;
1513
1514 let entries = self.active_goals.len() + self.completed_results.len();
1515 writer
1516 .write_u32(entries as u32)
1517 .map_err(|_| NodeError::Serialization)?;
1518
1519 for goal in &self.active_goals {
1520 let info = GoalInfo::new(goal.goal_id, goal.stamp.sec, goal.stamp.nanosec);
1521 let stamped = GoalStatusStamped::new(info, goal.status);
1522 stamped
1523 .serialize(&mut writer)
1524 .map_err(|_| NodeError::Serialization)?;
1525 }
1526
1527 for done in &self.completed_results {
1528 let stamped = GoalStatusStamped::new(GoalInfo::with_id(done.goal_id), done.status);
1529 stamped
1530 .serialize(&mut writer)
1531 .map_err(|_| NodeError::Serialization)?;
1532 }
1533
1534 let len = writer.position();
1535 self.status_publisher
1536 .publish_raw(&buf[..len])
1537 // Issue 2978 -- the backend's own refusal (MessageTooLarge, WouldBlock,
1538 // SessionLost ...), not a flattened PublishFailed.
1539 .map_err(NodeError::Transport)
1540 }
1541}
1542
1543// ============================================================================
1544// ActionClientCore
1545// ============================================================================
1546
1547/// Type-agnostic action client core handling the raw-bytes protocol.
1548///
1549/// The typed [`ActionClient`](super::handles::ActionClient) wraps this
1550/// and adds serialization/deserialization at the boundary.
1551pub struct ActionClientCore<
1552 const GOAL_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
1553 const RESULT_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
1554 const FEEDBACK_BUF: usize = { crate::config::DEFAULT_RX_BUF_SIZE },
1555> {
1556 pub(crate) send_goal_client: session::RmwServiceClient,
1557 pub(crate) cancel_goal_client: session::RmwServiceClient,
1558 pub(crate) get_result_client: session::RmwServiceClient,
1559 pub(crate) feedback_subscriber: session::RmwSubscriber,
1560 pub(crate) goal_buffer: [u8; GOAL_BUF],
1561 pub(crate) result_buffer: [u8; RESULT_BUF],
1562 pub(crate) feedback_buffer: [u8; FEEDBACK_BUF],
1563 pub(crate) goal_counter: u64,
1564 /// Phase 84.D3: per-sub-client in-flight flags. Each of the three
1565 /// sub-clients (send_goal / cancel / get_result) is an independent
1566 /// request/reply channel and tracks its own "unconsumed reply"
1567 /// state. Cleared by `Promise::take` on success.
1568 pub(crate) in_flight_send_goal: bool,
1569 pub(crate) in_flight_cancel: bool,
1570 pub(crate) in_flight_get_result: bool,
1571 /// Issue 2009 — the requests each sub-client has in flight, keyed by the
1572 /// sequence id the backend assigned and carrying the goal each one is
1573 /// about. A reply is attributed to the goal of the request it NAMES, and a
1574 /// reply naming no pending request (an abandoned one's) is dropped. Before
1575 /// this, every reply was attributed to the most recently SENT goal
1576 /// (`goal_counter`), so two goals in flight swapped acceptances and
1577 /// results, and an abandoned `get_result`'s late reply answered the next.
1578 pub(crate) pending_send_goal: ActionRequests,
1579 pub(crate) pending_cancel: ActionRequests,
1580 pub(crate) pending_get_result: ActionRequests,
1581}
1582
1583/// One action sub-client's requests in flight: at most
1584/// [`MAX_CONCURRENT_GOALS`](crate::limits::MAX_CONCURRENT_GOALS) — the number of
1585/// goals a server holds at once — each keyed by its sequence id and carrying
1586/// its goal. A send past that is refused with
1587/// [`NodeError::RequestInFlight`] before it reaches the wire.
1588pub type ActionRequests =
1589 nros_rmw::RequestCorrelator<GoalUuid, { crate::limits::MAX_CONCURRENT_GOALS }>;
1590
1591impl<const GOAL_BUF: usize, const RESULT_BUF: usize, const FEEDBACK_BUF: usize>
1592 ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>
1593{
1594 /// Whether the action server's `send_goal` service is CURRENTLY visible.
1595 /// See `ActionClient::action_server_is_ready` for the semantic; the C and
1596 /// C++ `wait_for_action_server` bindings spin on this (phase-428 W13 — the
1597 /// asynchronous discovery pair they used to drive is gone).
1598 ///
1599 /// phase-379 W6 / issue 1008 — `Err` (the backend cannot answer) reports
1600 /// NOT ready. The deleted `is_server_ready` defaulted to `true`, so an
1601 /// image whose backend has no discovery claimed the server was up.
1602 /// Answering `false` makes a caller wait; answering `true` makes it send
1603 /// into the void.
1604 pub(crate) fn is_server_ready(&self) -> bool {
1605 matches!(self.server_readiness(), Ok(true))
1606 }
1607
1608 /// The raw three-answer probe behind [`Self::is_server_ready`] — what a
1609 /// WAIT loop reads, through `ServerVisibility::of`, so that "the backend
1610 /// cannot know" ends the wait instead of being waited out (issue 1686).
1611 pub(crate) fn server_readiness(&self) -> Result<bool, nros_rmw::TransportError> {
1612 use nros_rmw::ClientTrait;
1613 self.send_goal_client.service_is_ready()
1614 }
1615
1616 /// Issue 2360 — [`Self::new`] written IN PLACE at `dst`, never on the
1617 /// stack: the core's three buffers (3 KiB at the default sizes) made the
1618 /// raw client's registration frame 13,972 B when it was built as a value
1619 /// and moved into the arena. Same values as `new`, field by field.
1620 ///
1621 /// # Safety
1622 ///
1623 /// `dst` must be valid for writes of `Self` and properly aligned. Every
1624 /// field is initialised on return; [`Self::_every_field_is_written`] makes
1625 /// a field added later and not written here a compile error.
1626 pub(crate) unsafe fn init_in_place(
1627 dst: *mut Self,
1628 send_goal_client: session::RmwServiceClient,
1629 cancel_goal_client: session::RmwServiceClient,
1630 get_result_client: session::RmwServiceClient,
1631 feedback_subscriber: session::RmwSubscriber,
1632 ) {
1633 use core::ptr::addr_of_mut;
1634 // SAFETY: the caller's contract — `dst` is valid and aligned, so each
1635 // field projection is too; every write targets a distinct field.
1636 unsafe {
1637 addr_of_mut!((*dst).send_goal_client).write(send_goal_client);
1638 addr_of_mut!((*dst).cancel_goal_client).write(cancel_goal_client);
1639 addr_of_mut!((*dst).get_result_client).write(get_result_client);
1640 addr_of_mut!((*dst).feedback_subscriber).write(feedback_subscriber);
1641 addr_of_mut!((*dst).goal_buffer).write_bytes(0, 1);
1642 addr_of_mut!((*dst).result_buffer).write_bytes(0, 1);
1643 addr_of_mut!((*dst).feedback_buffer).write_bytes(0, 1);
1644 addr_of_mut!((*dst).goal_counter).write(0);
1645 addr_of_mut!((*dst).in_flight_send_goal).write(false);
1646 addr_of_mut!((*dst).in_flight_cancel).write(false);
1647 addr_of_mut!((*dst).in_flight_get_result).write(false);
1648 addr_of_mut!((*dst).pending_send_goal).write(ActionRequests::new());
1649 addr_of_mut!((*dst).pending_cancel).write(ActionRequests::new());
1650 addr_of_mut!((*dst).pending_get_result).write(ActionRequests::new());
1651 }
1652 }
1653
1654 /// Never called: names every field with no `..`, so adding one to the
1655 /// struct fails to compile until [`Self::init_in_place`] writes it too.
1656 #[allow(dead_code)]
1657 fn _every_field_is_written(&self) {
1658 let Self {
1659 send_goal_client: _,
1660 cancel_goal_client: _,
1661 get_result_client: _,
1662 feedback_subscriber: _,
1663 goal_buffer: _,
1664 result_buffer: _,
1665 feedback_buffer: _,
1666 goal_counter: _,
1667 in_flight_send_goal: _,
1668 in_flight_cancel: _,
1669 in_flight_get_result: _,
1670 pending_send_goal: _,
1671 pending_cancel: _,
1672 pending_get_result: _,
1673 } = self;
1674 }
1675
1676 /// Create a new action client core from the raw transport handles.
1677 pub(crate) fn new(
1678 send_goal_client: session::RmwServiceClient,
1679 cancel_goal_client: session::RmwServiceClient,
1680 get_result_client: session::RmwServiceClient,
1681 feedback_subscriber: session::RmwSubscriber,
1682 ) -> Self {
1683 Self {
1684 send_goal_client,
1685 cancel_goal_client,
1686 get_result_client,
1687 feedback_subscriber,
1688 goal_buffer: [0u8; GOAL_BUF],
1689 result_buffer: [0u8; RESULT_BUF],
1690 feedback_buffer: [0u8; FEEDBACK_BUF],
1691 goal_counter: 0,
1692 in_flight_send_goal: false,
1693 in_flight_cancel: false,
1694 in_flight_get_result: false,
1695 pending_send_goal: ActionRequests::new(),
1696 pending_cancel: ActionRequests::new(),
1697 pending_get_result: ActionRequests::new(),
1698 }
1699 }
1700
1701 /// Send a goal with raw CDR bytes. Returns the generated GoalUuid.
1702 ///
1703 /// The `goal_cdr` bytes are the serialized goal data (without GoalUuid framing).
1704 /// This writes GoalUuid + goal_cdr into the goal buffer and sends the request.
1705 ///
1706 /// After calling, use `send_goal_client` and `result_buffer` to construct
1707 /// a Promise for the acceptance reply.
1708 pub(crate) fn send_goal_raw(&mut self, goal_cdr: &[u8]) -> Result<GoalUuid, NodeError> {
1709 // Issue 2009 — refuse BEFORE the counter moves or the request is sent.
1710 self.pending_send_goal
1711 .can_send()
1712 .map_err(|_| NodeError::RequestInFlight)?;
1713 self.goal_counter += 1;
1714 let mut goal_id = GoalUuid::default();
1715 let counter_bytes = self.goal_counter.to_le_bytes();
1716 goal_id.uuid[..8].copy_from_slice(&counter_bytes);
1717
1718 let mut writer =
1719 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
1720
1721 write_goal_id(&mut writer, &goal_id)?;
1722
1723 // Copy raw goal CDR bytes after GoalUuid
1724 let pos = writer.position();
1725 if pos + goal_cdr.len() > GOAL_BUF {
1726 return Err(NodeError::BufferTooSmall);
1727 }
1728 self.goal_buffer[pos..pos + goal_cdr.len()].copy_from_slice(goal_cdr);
1729 let req_len = pos + goal_cdr.len();
1730
1731 let seq = self
1732 .send_goal_client
1733 .send_request_raw(&self.goal_buffer[..req_len])
1734 .map_err(|_| NodeError::ServiceRequestFailed)?;
1735 let _ = self.pending_send_goal.insert(seq, goal_id);
1736
1737 Ok(goal_id)
1738 }
1739
1740 /// Try to receive feedback (non-blocking, raw bytes).
1741 ///
1742 /// Returns the GoalUuid and total data length. The full CDR data
1743 /// (including GoalUuid) is in `feedback_buffer`.
1744 pub(crate) fn try_recv_feedback_raw(&mut self) -> Result<Option<(GoalUuid, usize)>, NodeError> {
1745 let data = self
1746 .feedback_subscriber
1747 .take_serialized(&mut self.feedback_buffer)
1748 .map_err(NodeError::Transport)?;
1749
1750 let len = match data {
1751 Some(len) => len,
1752 None => return Ok(None),
1753 };
1754
1755 let mut reader = CdrReader::new_with_header(&self.feedback_buffer[..len])
1756 .map_err(|_| NodeError::Transport(TransportError::DeserializationError))?;
1757
1758 let goal_id = read_goal_id(&mut reader)?;
1759
1760 Ok(Some((goal_id, len)))
1761 }
1762
1763 /// Cancel a goal (non-blocking). Sends the cancel request.
1764 ///
1765 /// After calling, use `cancel_goal_client` and `result_buffer` to construct
1766 /// a Promise for the cancel response.
1767 pub(crate) fn send_cancel_request(&mut self, goal_id: &GoalUuid) -> Result<(), NodeError> {
1768 self.send_cancel_request_stamped(goal_id, 0, 0)
1769 .map(|_seq| ())
1770 }
1771
1772 /// [`Self::send_cancel_request`] with the request's `GoalInfo.stamp` — issue 2027.
1773 ///
1774 /// `action_msgs/srv/CancelGoal` reads the pair (goal id, stamp): a zero id
1775 /// with a zero stamp cancels EVERY goal, a zero id with a stamp cancels
1776 /// the goals accepted at or before it, and a non-zero id cancels that goal
1777 /// (plus, with a stamp, those before it). The reply is correlated under
1778 /// `goal_id` — the zero id for the two broadcast forms. Returns the
1779 /// request's sequence id, which is what tells two pending requests about
1780 /// the SAME goal (or two broadcasts) apart when their replies come back
1781 /// ([`Self::try_recv_cancel_reply_seq`]).
1782 pub(crate) fn send_cancel_request_stamped(
1783 &mut self,
1784 goal_id: &GoalUuid,
1785 stamp_sec: i32,
1786 stamp_nanosec: u32,
1787 ) -> Result<i64, NodeError> {
1788 self.pending_cancel
1789 .can_send()
1790 .map_err(|_| NodeError::RequestInFlight)?;
1791 let mut writer =
1792 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
1793
1794 write_goal_id(&mut writer, goal_id)?;
1795 writer
1796 .write_i32(stamp_sec)
1797 .map_err(|_| NodeError::Serialization)?;
1798 writer
1799 .write_u32(stamp_nanosec)
1800 .map_err(|_| NodeError::Serialization)?;
1801
1802 let req_len = writer.position();
1803
1804 let seq = self
1805 .cancel_goal_client
1806 .send_request_raw(&self.goal_buffer[..req_len])
1807 .map_err(|_| NodeError::ServiceRequestFailed)?;
1808 let _ = self.pending_cancel.insert(seq, *goal_id);
1809 Ok(seq)
1810 }
1811
1812 /// Send a get_result request.
1813 ///
1814 /// After calling, use `get_result_client` and `result_buffer` to construct
1815 /// a Promise for the result response.
1816 pub(crate) fn send_get_result_request(&mut self, goal_id: &GoalUuid) -> Result<(), NodeError> {
1817 self.pending_get_result
1818 .can_send()
1819 .map_err(|_| NodeError::RequestInFlight)?;
1820 let mut writer =
1821 crate::tx_writer(&mut self.goal_buffer).map_err(|_| NodeError::BufferTooSmall)?;
1822
1823 write_goal_id(&mut writer, goal_id)?;
1824
1825 let req_len = writer.position();
1826
1827 let seq = self
1828 .get_result_client
1829 .send_request_raw(&self.goal_buffer[..req_len])
1830 .map_err(|_| NodeError::ServiceRequestFailed)?;
1831 let _ = self.pending_get_result.insert(seq, *goal_id);
1832 Ok(())
1833 }
1834
1835 /// Phase 122.3.c.6.e — register a `Waker` that fires when the
1836 /// send_goal RPC reply lands.
1837 pub(crate) fn register_goal_response_waker(&self, waker: &core::task::Waker) -> bool {
1838 use nros_rmw::ClientTrait;
1839 self.send_goal_client.register_waker(waker)
1840 }
1841
1842 /// Phase 122.3.c.6.e — register a `Waker` for cancel-RPC replies.
1843 pub(crate) fn register_cancel_response_waker(&self, waker: &core::task::Waker) -> bool {
1844 use nros_rmw::ClientTrait;
1845 self.cancel_goal_client.register_waker(waker)
1846 }
1847
1848 /// Phase 122.3.c.6.e — register a `Waker` for get_result replies.
1849 pub(crate) fn register_result_waker(&self, waker: &core::task::Waker) -> bool {
1850 use nros_rmw::ClientTrait;
1851 self.get_result_client.register_waker(waker)
1852 }
1853
1854 /// Phase 122.3.c.6.e — register a `Waker` for feedback messages.
1855 pub(crate) fn register_feedback_waker(&self, waker: &core::task::Waker) -> bool {
1856 use nros_rmw::Subscription;
1857 self.feedback_subscriber.register_waker(waker)
1858 }
1859
1860 /// Phase 122.3.c.6.c — poll for a cancel reply (non-blocking,
1861 /// raw bytes). Returns `Ok(Some(len))` when a reply landed; the
1862 /// CDR payload is in `result_buffer_ref()[..len]`. Reply layout
1863 /// is action_msgs/srv/CancelGoal_Response wire CDR.
1864 pub(crate) fn try_recv_cancel_reply(&mut self) -> Result<Option<usize>, NodeError> {
1865 Ok(self.try_recv_cancel_reply_for()?.map(|(len, _goal)| len))
1866 }
1867
1868 /// Issue 2009 — [`Self::try_recv_cancel_reply`] with the goal the reply is ABOUT: the
1869 /// goal of the request whose sequence id it names. A reply naming no
1870 /// pending request is dropped (it answers an abandoned request).
1871 pub(crate) fn try_recv_cancel_reply_for(
1872 &mut self,
1873 ) -> Result<Option<(usize, GoalUuid)>, NodeError> {
1874 Ok(self
1875 .try_recv_cancel_reply_seq()?
1876 .map(|(len, _seq, goal)| (len, goal)))
1877 }
1878
1879 /// Issue 2027 — [`Self::try_recv_cancel_reply_for`] with the sequence id
1880 /// of the request the reply answers too ([`nros_rmw::SEQUENCE_ID_UNKNOWN`]
1881 /// from a backend that assigns none — it then holds one cancel in flight).
1882 pub(crate) fn try_recv_cancel_reply_seq(
1883 &mut self,
1884 ) -> Result<Option<(usize, i64, GoalUuid)>, NodeError> {
1885 // Phase 120: NoData == steady-state polling; map to Ok(None).
1886 match nros_rmw::take_correlated(
1887 &mut self.cancel_goal_client,
1888 &mut self.result_buffer,
1889 &mut self.pending_cancel,
1890 ) {
1891 Ok(opt) => Ok(opt),
1892 Err(TransportError::NoData) => Ok(None),
1893 Err(_) => Err(NodeError::Transport(TransportError::DeserializationError)),
1894 }
1895 }
1896
1897 /// Poll for a get_result reply (non-blocking, raw bytes).
1898 ///
1899 /// Returns `Ok(Some(total_len))` if a reply arrived (data in result buffer),
1900 /// `Ok(None)` if no reply yet.
1901 ///
1902 /// After receiving, use [`result_buffer_ref()`](Self::result_buffer_ref)
1903 /// to access the raw CDR data. The layout is: CDR header (4) + status
1904 /// byte (1) + result data.
1905 pub(crate) fn try_recv_get_result_reply(&mut self) -> Result<Option<usize>, NodeError> {
1906 Ok(self
1907 .try_recv_get_result_reply_for()?
1908 .map(|(len, _goal)| len))
1909 }
1910
1911 /// Issue 2009 — [`Self::try_recv_get_result_reply`] with the goal the reply is ABOUT: the
1912 /// goal of the request whose sequence id it names. A reply naming no
1913 /// pending request is dropped (it answers an abandoned request).
1914 pub(crate) fn try_recv_get_result_reply_for(
1915 &mut self,
1916 ) -> Result<Option<(usize, GoalUuid)>, NodeError> {
1917 // Phase 120: NoData == steady-state polling; map to Ok(None).
1918 match nros_rmw::take_correlated(
1919 &mut self.get_result_client,
1920 &mut self.result_buffer,
1921 &mut self.pending_get_result,
1922 ) {
1923 Ok(opt) => Ok(opt.map(|(len, _seq, goal)| (len, goal))),
1924 Err(TransportError::NoData) => Ok(None),
1925 Err(_) => Err(NodeError::Transport(TransportError::DeserializationError)),
1926 }
1927 }
1928
1929 /// Poll for the send_goal acceptance reply (non-blocking, raw bytes).
1930 ///
1931 /// Returns `Ok(Some(total_len))` if a reply arrived (data in result buffer),
1932 /// `Ok(None)` if no reply yet.
1933 ///
1934 /// The reply CDR contains: header (4) + accepted (u8) + stamp (i32 + u32).
1935 pub(crate) fn try_recv_send_goal_reply(&mut self) -> Result<Option<usize>, NodeError> {
1936 Ok(self.try_recv_send_goal_reply_for()?.map(|(len, _goal)| len))
1937 }
1938
1939 /// Issue 2009 — [`Self::try_recv_send_goal_reply`] with the goal the reply is ABOUT: the
1940 /// goal of the request whose sequence id it names. A reply naming no
1941 /// pending request is dropped (it answers an abandoned request).
1942 pub(crate) fn try_recv_send_goal_reply_for(
1943 &mut self,
1944 ) -> Result<Option<(usize, GoalUuid)>, NodeError> {
1945 // Phase 120: NoData == steady-state polling; map to Ok(None).
1946 match nros_rmw::take_correlated(
1947 &mut self.send_goal_client,
1948 &mut self.result_buffer,
1949 &mut self.pending_send_goal,
1950 ) {
1951 Ok(opt) => Ok(opt.map(|(len, _seq, goal)| (len, goal))),
1952 Err(TransportError::NoData) => Ok(None),
1953 Err(_) => Err(NodeError::Transport(TransportError::DeserializationError)),
1954 }
1955 }
1956
1957 /// Issue 2027 — forget the oldest pending `send_goal` request for
1958 /// `goal_id`: its slot (one of
1959 /// [`MAX_CONCURRENT_GOALS`](crate::limits::MAX_CONCURRENT_GOALS)) is free
1960 /// for the next goal, and its reply, if it still comes, is dropped. For a
1961 /// binding whose last owner of that request let go before the reply came
1962 /// (a dropped C++ future). `true` if one was pending.
1963 pub(crate) fn forget_send_goal(&mut self, goal_id: &GoalUuid) -> bool {
1964 self.pending_send_goal.remove_key(goal_id)
1965 }
1966
1967 /// Issue 2027 — [`Self::forget_send_goal`] for a `get_result` request.
1968 pub(crate) fn forget_get_result(&mut self, goal_id: &GoalUuid) -> bool {
1969 self.pending_get_result.remove_key(goal_id)
1970 }
1971
1972 /// Issue 2027 — [`Self::forget_send_goal`] for a `cancel_goal` request
1973 /// (the zero id names a cancel-all / cancel-before request).
1974 pub(crate) fn forget_cancel(&mut self, goal_id: &GoalUuid) -> bool {
1975 self.pending_cancel.remove_key(goal_id)
1976 }
1977
1978 /// Read-only access to the result buffer (after polling a reply).
1979 pub(crate) fn result_buffer_ref(&self) -> &[u8] {
1980 &self.result_buffer
1981 }
1982
1983 /// Read-only access to the feedback buffer (after receiving feedback).
1984 pub(crate) fn feedback_buffer_ref(&self) -> &[u8] {
1985 &self.feedback_buffer
1986 }
1987
1988 /// Get the current goal counter (used to reconstruct the last goal ID).
1989 pub(crate) fn goal_counter(&self) -> u64 {
1990 self.goal_counter
1991 }
1992}