astrs_wire/metadata/keys.rs
1//! Well-known metadata keys, and the action-goal status they encode.
2//!
3//! Blueprint §6.1 lists the reserved keys; §9.4 explains what they are for:
4//! services, actions and streams all ride ordinary graph edges and are
5//! correlated purely through metadata, with no separate RPC subsystem.
6//!
7//! | Key | Shape | Pattern |
8//! |---|---|---|
9//! | [`REQUEST_ID`] | string | service request ↔ response |
10//! | [`GOAL_ID`] | string | action goal identity |
11//! | [`GOAL_STATUS`] | integer ([`GoalStatus`]) | action goal FSM |
12//! | [`SESSION_ID`] | string | stream session |
13//! | [`SEGMENT_ID`] | integer | stream segment within a session |
14//! | [`SEQ`] | integer | sequence number within a segment |
15//! | [`FIN`] | bool | last chunk of a segment |
16//! | [`FLUSH`] | bool | deliver buffered chunks now |
17//! | [`SCHEMA_HASH`] | string | internal: payload schema fingerprint |
18//!
19//! Keys beginning with `_` are AstRS-internal and are removed by
20//! [`crate::Metadata::strip_internal`] before an event reaches user code.
21//!
22//! # Examples
23//!
24//! ```
25//! use astrs_wire::metadata::keys;
26//!
27//! assert!(keys::is_correlation_key(keys::REQUEST_ID));
28//! assert!(!keys::is_correlation_key(keys::SEQ));
29//! assert!(keys::is_internal_key(keys::SCHEMA_HASH));
30//! ```
31
32use core::fmt;
33
34use oxicode::{Decode, Encode};
35use serde::{Deserialize, Serialize};
36
37/// Correlates a service response with the request that caused it (§9.4).
38pub const REQUEST_ID: &str = "request_id";
39
40/// Identifies one action goal across its whole lifetime (§9.4).
41pub const GOAL_ID: &str = "goal_id";
42
43/// Carries the current [`GoalStatus`] of an action goal (§9.4).
44pub const GOAL_STATUS: &str = "goal_status";
45
46/// Identifies one stream session (§9.4).
47pub const SESSION_ID: &str = "session_id";
48
49/// Identifies one segment within a stream session (§9.4).
50pub const SEGMENT_ID: &str = "segment_id";
51
52/// The sequence number of a chunk within its segment (§9.4).
53pub const SEQ: &str = "seq";
54
55/// Marks the final chunk of a stream segment (§9.4).
56pub const FIN: &str = "fin";
57
58/// Asks the receiver to deliver buffered chunks immediately (§9.4).
59pub const FLUSH: &str = "flush";
60
61/// Internal: the payload's schema fingerprint, stamped by `astrs-data`'s
62/// `SchemaHash` so receivers can cache decoded schemas and detect type drift
63/// cheaply (§6.1).
64pub const SCHEMA_HASH: &str = "_schema_hash";
65
66/// The prefix that marks a key as AstRS-internal.
67pub const INTERNAL_PREFIX: char = '_';
68
69/// Every well-known key, in documentation order.
70///
71/// # Examples
72///
73/// ```
74/// use astrs_wire::metadata::keys;
75///
76/// assert!(keys::WELL_KNOWN.contains(&keys::SEQ));
77/// assert_eq!(keys::WELL_KNOWN.len(), 9);
78/// ```
79pub const WELL_KNOWN: &[&str] = &[
80 REQUEST_ID,
81 GOAL_ID,
82 GOAL_STATUS,
83 SESSION_ID,
84 SEGMENT_ID,
85 SEQ,
86 FIN,
87 FLUSH,
88 SCHEMA_HASH,
89];
90
91/// The keys that make a message *correlated*.
92///
93/// Blueprint §11.2: correlated messages are immune to queue eviction, because
94/// dropping a service response or a goal-status update would wedge a client
95/// forever. This is the exact list the scheduler consults.
96///
97/// # Examples
98///
99/// ```
100/// use astrs_wire::metadata::keys;
101///
102/// assert_eq!(keys::CORRELATION, &["request_id", "goal_id", "goal_status"]);
103/// ```
104pub const CORRELATION: &[&str] = &[REQUEST_ID, GOAL_ID, GOAL_STATUS];
105
106/// The keys that describe a chunk's place in a stream.
107///
108/// # Examples
109///
110/// ```
111/// use astrs_wire::metadata::keys;
112///
113/// assert!(keys::STREAM.contains(&keys::SEGMENT_ID));
114/// ```
115pub const STREAM: &[&str] = &[SESSION_ID, SEGMENT_ID, SEQ, FIN, FLUSH];
116
117/// Whether `key` is AstRS-internal (starts with `_`).
118///
119/// # Examples
120///
121/// ```
122/// use astrs_wire::metadata::keys;
123///
124/// assert!(keys::is_internal_key("_schema_hash"));
125/// assert!(!keys::is_internal_key("seq"));
126/// assert!(!keys::is_internal_key(""));
127/// ```
128#[must_use]
129pub fn is_internal_key(key: &str) -> bool {
130 key.starts_with(INTERNAL_PREFIX)
131}
132
133/// Whether `key` is one of the correlation keys of [`CORRELATION`].
134///
135/// # Examples
136///
137/// ```
138/// use astrs_wire::metadata::keys;
139///
140/// assert!(keys::is_correlation_key("goal_id"));
141/// assert!(!keys::is_correlation_key("fin"));
142/// ```
143#[must_use]
144pub fn is_correlation_key(key: &str) -> bool {
145 CORRELATION.contains(&key)
146}
147
148/// Whether `key` is one of the stream keys of [`STREAM`].
149///
150/// # Examples
151///
152/// ```
153/// use astrs_wire::metadata::keys;
154///
155/// assert!(keys::is_stream_key("seq"));
156/// assert!(!keys::is_stream_key("request_id"));
157/// ```
158#[must_use]
159pub fn is_stream_key(key: &str) -> bool {
160 STREAM.contains(&key)
161}
162
163/// Whether `key` is reserved by AstRS.
164///
165/// Reserved keys are the well-known ones plus anything beginning with `_`.
166/// A node may still set them — that is how patterns are implemented — but a
167/// manifest that names one as a user parameter is making a mistake.
168///
169/// # Examples
170///
171/// ```
172/// use astrs_wire::metadata::keys;
173///
174/// assert!(keys::is_reserved_key("seq"));
175/// assert!(keys::is_reserved_key("_anything"));
176/// assert!(!keys::is_reserved_key("my_key"));
177/// ```
178#[must_use]
179pub fn is_reserved_key(key: &str) -> bool {
180 is_internal_key(key) || WELL_KNOWN.contains(&key)
181}
182
183/// The lifecycle state of an action goal (blueprint §9.4).
184///
185/// The discriminants match ROS 2's `action_msgs/msg/GoalStatus` constants
186/// exactly, so `astrs-ros2` can bridge an action in either direction without
187/// a translation table. The AstRS FSM proper is
188/// `Accepted → Executing → {Succeeded, Aborted, Canceled}`; `Canceling` and
189/// `Unknown` exist for ROS 2 fidelity.
190///
191/// # Examples
192///
193/// ```
194/// use astrs_wire::GoalStatus;
195///
196/// assert_eq!(GoalStatus::Executing.as_i64(), 2);
197/// assert_eq!(GoalStatus::from_i64(4), Some(GoalStatus::Succeeded));
198/// assert!(GoalStatus::Succeeded.is_terminal());
199/// assert!(GoalStatus::Accepted.can_transition_to(GoalStatus::Executing));
200/// assert!(!GoalStatus::Succeeded.can_transition_to(GoalStatus::Executing));
201/// ```
202#[derive(
203 Debug,
204 Clone,
205 Copy,
206 Default,
207 PartialEq,
208 Eq,
209 PartialOrd,
210 Ord,
211 Hash,
212 Serialize,
213 Deserialize,
214 Encode,
215 Decode,
216)]
217#[serde(rename_all = "snake_case")]
218#[non_exhaustive]
219pub enum GoalStatus {
220 /// The goal's state is not known (ROS 2 `STATUS_UNKNOWN`).
221 #[default]
222 #[oxicode(variant = 0)]
223 Unknown,
224 /// The server accepted the goal but has not started it
225 /// (ROS 2 `STATUS_ACCEPTED`).
226 #[oxicode(variant = 1)]
227 Accepted,
228 /// The server is executing the goal (ROS 2 `STATUS_EXECUTING`).
229 #[oxicode(variant = 2)]
230 Executing,
231 /// A cancellation was requested and is being processed
232 /// (ROS 2 `STATUS_CANCELING`).
233 #[oxicode(variant = 3)]
234 Canceling,
235 /// The goal completed successfully (ROS 2 `STATUS_SUCCEEDED`).
236 #[oxicode(variant = 4)]
237 Succeeded,
238 /// The goal was cancelled (ROS 2 `STATUS_CANCELED`).
239 #[oxicode(variant = 5)]
240 Canceled,
241 /// The goal failed (ROS 2 `STATUS_ABORTED`).
242 #[oxicode(variant = 6)]
243 Aborted,
244}
245
246impl GoalStatus {
247 /// Every status, in discriminant order.
248 pub const ALL: &'static [Self] = &[
249 Self::Unknown,
250 Self::Accepted,
251 Self::Executing,
252 Self::Canceling,
253 Self::Succeeded,
254 Self::Canceled,
255 Self::Aborted,
256 ];
257
258 /// The numeric form stored under [`GOAL_STATUS`].
259 #[must_use]
260 pub const fn as_i64(self) -> i64 {
261 match self {
262 Self::Unknown => 0,
263 Self::Accepted => 1,
264 Self::Executing => 2,
265 Self::Canceling => 3,
266 Self::Succeeded => 4,
267 Self::Canceled => 5,
268 Self::Aborted => 6,
269 }
270 }
271
272 /// Parses the numeric form.
273 ///
274 /// Returns `None` for a code this build does not know, rather than
275 /// collapsing it to [`GoalStatus::Unknown`] — a caller that wants that
276 /// fallback should say so.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use astrs_wire::GoalStatus;
282 ///
283 /// assert_eq!(GoalStatus::from_i64(6), Some(GoalStatus::Aborted));
284 /// assert_eq!(GoalStatus::from_i64(7), None);
285 /// assert_eq!(GoalStatus::from_i64(-1), None);
286 /// ```
287 #[must_use]
288 pub const fn from_i64(code: i64) -> Option<Self> {
289 match code {
290 0 => Some(Self::Unknown),
291 1 => Some(Self::Accepted),
292 2 => Some(Self::Executing),
293 3 => Some(Self::Canceling),
294 4 => Some(Self::Succeeded),
295 5 => Some(Self::Canceled),
296 6 => Some(Self::Aborted),
297 _ => None,
298 }
299 }
300
301 /// A stable, lower-case name.
302 #[must_use]
303 pub const fn as_str(self) -> &'static str {
304 match self {
305 Self::Unknown => "unknown",
306 Self::Accepted => "accepted",
307 Self::Executing => "executing",
308 Self::Canceling => "canceling",
309 Self::Succeeded => "succeeded",
310 Self::Canceled => "canceled",
311 Self::Aborted => "aborted",
312 }
313 }
314
315 /// Whether the goal has reached a final state.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use astrs_wire::GoalStatus;
321 ///
322 /// assert!(GoalStatus::Canceled.is_terminal());
323 /// assert!(!GoalStatus::Canceling.is_terminal());
324 /// ```
325 #[must_use]
326 pub const fn is_terminal(self) -> bool {
327 matches!(self, Self::Succeeded | Self::Canceled | Self::Aborted)
328 }
329
330 /// Whether the goal is still in flight.
331 #[must_use]
332 pub const fn is_active(self) -> bool {
333 matches!(self, Self::Accepted | Self::Executing | Self::Canceling)
334 }
335
336 /// Whether `next` is a legal successor of `self` in the goal FSM.
337 ///
338 /// Servers use this to reject a status update that would move a goal
339 /// backwards or out of a terminal state, which is the failure mode that
340 /// leaves a client waiting forever.
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use astrs_wire::GoalStatus;
346 ///
347 /// assert!(GoalStatus::Unknown.can_transition_to(GoalStatus::Accepted));
348 /// assert!(GoalStatus::Executing.can_transition_to(GoalStatus::Canceling));
349 /// assert!(GoalStatus::Canceling.can_transition_to(GoalStatus::Canceled));
350 /// assert!(!GoalStatus::Accepted.can_transition_to(GoalStatus::Unknown));
351 /// assert!(!GoalStatus::Aborted.can_transition_to(GoalStatus::Aborted));
352 /// ```
353 #[must_use]
354 pub const fn can_transition_to(self, next: Self) -> bool {
355 match self {
356 Self::Unknown => matches!(next, Self::Accepted),
357 Self::Accepted => matches!(
358 next,
359 Self::Executing
360 | Self::Canceling
361 | Self::Succeeded
362 | Self::Canceled
363 | Self::Aborted
364 ),
365 Self::Executing => matches!(
366 next,
367 Self::Canceling | Self::Succeeded | Self::Canceled | Self::Aborted
368 ),
369 Self::Canceling => matches!(next, Self::Canceled | Self::Succeeded | Self::Aborted),
370 Self::Succeeded | Self::Canceled | Self::Aborted => false,
371 }
372 }
373}
374
375impl fmt::Display for GoalStatus {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.write_str(self.as_str())
378 }
379}
380
381impl From<GoalStatus> for i64 {
382 fn from(status: GoalStatus) -> Self {
383 status.as_i64()
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
390
391 use super::*;
392 use crate::codec::round_trip;
393
394 #[test]
395 fn well_known_keys_match_the_blueprint() {
396 assert_eq!(
397 WELL_KNOWN,
398 &[
399 "request_id",
400 "goal_id",
401 "goal_status",
402 "session_id",
403 "segment_id",
404 "seq",
405 "fin",
406 "flush",
407 "_schema_hash",
408 ]
409 );
410 }
411
412 #[test]
413 fn well_known_keys_are_unique() {
414 let unique: std::collections::BTreeSet<_> = WELL_KNOWN.iter().collect();
415 assert_eq!(unique.len(), WELL_KNOWN.len());
416 }
417
418 #[test]
419 fn correlation_and_stream_sets_are_disjoint_subsets() {
420 for key in CORRELATION {
421 assert!(WELL_KNOWN.contains(key));
422 assert!(!STREAM.contains(key));
423 }
424 for key in STREAM {
425 assert!(WELL_KNOWN.contains(key));
426 assert!(!CORRELATION.contains(key));
427 }
428 }
429
430 #[test]
431 fn key_predicates_agree_with_the_sets() {
432 for key in WELL_KNOWN {
433 assert!(is_reserved_key(key), "{key}");
434 assert_eq!(is_correlation_key(key), CORRELATION.contains(key));
435 assert_eq!(is_stream_key(key), STREAM.contains(key));
436 }
437 assert!(is_internal_key(SCHEMA_HASH));
438 assert!(!is_internal_key(SEQ));
439 assert!(is_reserved_key("_future_internal_key"));
440 assert!(!is_reserved_key("user_key"));
441 assert!(!is_internal_key(""));
442 }
443
444 #[test]
445 fn goal_status_codes_match_ros2() {
446 // action_msgs/msg/GoalStatus: UNKNOWN=0, ACCEPTED=1, EXECUTING=2,
447 // CANCELING=3, SUCCEEDED=4, CANCELED=5, ABORTED=6.
448 assert_eq!(GoalStatus::Unknown.as_i64(), 0);
449 assert_eq!(GoalStatus::Accepted.as_i64(), 1);
450 assert_eq!(GoalStatus::Executing.as_i64(), 2);
451 assert_eq!(GoalStatus::Canceling.as_i64(), 3);
452 assert_eq!(GoalStatus::Succeeded.as_i64(), 4);
453 assert_eq!(GoalStatus::Canceled.as_i64(), 5);
454 assert_eq!(GoalStatus::Aborted.as_i64(), 6);
455 }
456
457 #[test]
458 fn numeric_form_round_trips_and_rejects_unknown_codes() {
459 for &status in GoalStatus::ALL {
460 assert_eq!(GoalStatus::from_i64(status.as_i64()), Some(status));
461 assert_eq!(i64::from(status), status.as_i64());
462 }
463 for code in [-2i64, -1, 7, 8, i64::MAX, i64::MIN] {
464 assert_eq!(GoalStatus::from_i64(code), None, "code {code}");
465 }
466 }
467
468 #[test]
469 fn terminal_and_active_partition_everything_but_unknown() {
470 for &status in GoalStatus::ALL {
471 assert!(!(status.is_terminal() && status.is_active()));
472 if status != GoalStatus::Unknown {
473 assert!(status.is_terminal() || status.is_active(), "{status}");
474 }
475 }
476 assert!(!GoalStatus::Unknown.is_terminal());
477 assert!(!GoalStatus::Unknown.is_active());
478 }
479
480 #[test]
481 fn terminal_states_have_no_successors() {
482 for status in GoalStatus::ALL.iter().copied().filter(|s| s.is_terminal()) {
483 for &next in GoalStatus::ALL {
484 assert!(
485 !status.can_transition_to(next),
486 "{status} must not move to {next}"
487 );
488 }
489 }
490 }
491
492 #[test]
493 fn the_documented_happy_path_is_legal() {
494 assert!(GoalStatus::Unknown.can_transition_to(GoalStatus::Accepted));
495 assert!(GoalStatus::Accepted.can_transition_to(GoalStatus::Executing));
496 assert!(GoalStatus::Executing.can_transition_to(GoalStatus::Succeeded));
497 assert!(GoalStatus::Executing.can_transition_to(GoalStatus::Aborted));
498 assert!(GoalStatus::Executing.can_transition_to(GoalStatus::Canceling));
499 assert!(GoalStatus::Canceling.can_transition_to(GoalStatus::Canceled));
500 }
501
502 #[test]
503 fn no_status_can_transition_to_itself() {
504 for &status in GoalStatus::ALL {
505 assert!(!status.can_transition_to(status), "{status}");
506 }
507 }
508
509 #[test]
510 fn names_are_unique_and_render() {
511 let mut seen = std::collections::BTreeSet::new();
512 for &status in GoalStatus::ALL {
513 assert!(seen.insert(status.as_str()));
514 assert_eq!(status.to_string(), status.as_str());
515 }
516 }
517
518 #[test]
519 fn codec_and_serde_round_trip() {
520 for &status in GoalStatus::ALL {
521 assert_eq!(round_trip(&status).unwrap(), status);
522 let json = serde_json::to_string(&status).unwrap();
523 assert_eq!(serde_json::from_str::<GoalStatus>(&json).unwrap(), status);
524 }
525 assert_eq!(GoalStatus::default(), GoalStatus::Unknown);
526 }
527}