Skip to main content

astrs_wire/ids/
uuid_ids.rs

1//! UUID-shaped identifiers: dataflows, sessions and builds.
2//!
3//! Each is a distinct newtype rather than a bare `Uuid` so the compiler
4//! catches the "passed a session id where a dataflow id belonged" class of
5//! bug, which is otherwise invisible: both are sixteen bytes.
6//!
7//! # Wire encoding
8//!
9//! All three encode as **sixteen raw bytes** — `oxicode` writes a `[u8; 16]`
10//! without a length prefix, so a UUID costs exactly sixteen bytes on the wire,
11//! not the twenty-two a varint `u128` would take (and not the thirty-seven a
12//! string form would).
13//!
14//! # Generation
15//!
16//! Sessions and builds are minted with **UUID v7** (blueprint: time-ordered
17//! ids), so a lexical sort of ids is a chronological sort — which is what makes
18//! `astrs list` and the coordinator's build cache index cheap to page through.
19//! Dataflow ids use the same generator for the same reason.
20//!
21//! # Examples
22//!
23//! ```
24//! use astrs_wire::{DataflowId, SessionId};
25//!
26//! let dataflow = DataflowId::from_u128(1);
27//! assert_eq!(dataflow.to_string(), "00000000-0000-0000-0000-000000000001");
28//!
29//! let a = SessionId::generate();
30//! let b = SessionId::generate();
31//! assert_ne!(a, b);
32//! ```
33
34use core::fmt;
35use core::str::FromStr;
36
37use oxicode::de::Decoder;
38use oxicode::enc::Encoder;
39use oxicode::{Decode, Encode};
40use serde::{Deserialize, Serialize};
41use uuid::Uuid;
42
43/// The number of bytes a UUID occupies on the wire.
44pub const UUID_WIRE_LEN: usize = 16;
45
46/// Defines a UUID-backed identifier newtype.
47macro_rules! define_uuid_id {
48    (
49        $(#[$meta:meta])*
50        $name:ident, $noun:literal
51    ) => {
52        $(#[$meta])*
53        #[derive(
54            Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
55        )]
56        #[serde(transparent)]
57        pub struct $name(Uuid);
58
59        impl $name {
60            /// The all-zero identifier.
61            ///
62            /// A sentinel for "not yet assigned"; never returned by
63            #[doc = concat!("[`", stringify!($name), "::generate`].")]
64            pub const NIL: Self = Self(Uuid::nil());
65
66            #[doc = concat!("Mints a fresh ", $noun, " using UUID v7 (time-ordered).")]
67            ///
68            /// # Examples
69            ///
70            /// ```
71            #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
72            ///
73            #[doc = concat!("let id = ", stringify!($name), "::generate();")]
74            #[doc = concat!("assert_ne!(id, ", stringify!($name), "::NIL);")]
75            /// ```
76            #[must_use]
77            pub fn generate() -> Self {
78                Self(Uuid::now_v7())
79            }
80
81            #[doc = concat!("Wraps an existing [`Uuid`] as a ", $noun, ".")]
82            #[must_use]
83            pub const fn from_uuid(uuid: Uuid) -> Self {
84                Self(uuid)
85            }
86
87            /// The underlying [`Uuid`].
88            #[must_use]
89            pub const fn as_uuid(&self) -> &Uuid {
90                &self.0
91            }
92
93            /// Consumes the identifier and returns the underlying [`Uuid`].
94            #[must_use]
95            pub const fn into_uuid(self) -> Uuid {
96                self.0
97            }
98
99            /// Builds an identifier from a 128-bit integer.
100            ///
101            /// Deterministic — used by tests and by the protocol snapshot,
102            /// which must produce byte-identical samples on every run.
103            #[must_use]
104            pub const fn from_u128(value: u128) -> Self {
105                Self(Uuid::from_u128(value))
106            }
107
108            /// The identifier as a 128-bit integer.
109            #[must_use]
110            pub const fn as_u128(&self) -> u128 {
111                self.0.as_u128()
112            }
113
114            /// Builds an identifier from its sixteen wire bytes.
115            #[must_use]
116            pub const fn from_bytes(bytes: [u8; UUID_WIRE_LEN]) -> Self {
117                Self(Uuid::from_bytes(bytes))
118            }
119
120            /// The identifier's sixteen wire bytes.
121            #[must_use]
122            pub const fn to_bytes(&self) -> [u8; UUID_WIRE_LEN] {
123                *self.0.as_bytes()
124            }
125
126            /// Whether this is the all-zero sentinel.
127            #[must_use]
128            pub fn is_nil(&self) -> bool {
129                self.0.is_nil()
130            }
131        }
132
133        impl fmt::Display for $name {
134            /// The canonical hyphenated lower-case form, e.g.
135            /// `067e6162-3b6f-7c4e-9b4a-1f9d6b2c8a01`.
136            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137                fmt::Display::fmt(&self.0, f)
138            }
139        }
140
141        impl fmt::Debug for $name {
142            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143                write!(f, "{}({})", stringify!($name), self.0)
144            }
145        }
146
147        impl FromStr for $name {
148            type Err = uuid::Error;
149
150            fn from_str(value: &str) -> Result<Self, Self::Err> {
151                Ok(Self(Uuid::parse_str(value)?))
152            }
153        }
154
155        impl From<Uuid> for $name {
156            fn from(uuid: Uuid) -> Self {
157                Self(uuid)
158            }
159        }
160
161        impl From<$name> for Uuid {
162            fn from(id: $name) -> Self {
163                id.0
164            }
165        }
166
167        impl Encode for $name {
168            fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
169                self.0.as_bytes().encode(encoder)
170            }
171        }
172
173        impl<Context> Decode<Context> for $name {
174            fn decode<D: Decoder<Context = Context>>(
175                decoder: &mut D,
176            ) -> Result<Self, oxicode::error::Error> {
177                let bytes = <[u8; UUID_WIRE_LEN]>::decode(decoder)?;
178                Ok(Self(Uuid::from_bytes(bytes)))
179            }
180        }
181    };
182}
183
184define_uuid_id! {
185    /// The identity of a running dataflow.
186    ///
187    /// Minted by the coordinator at `astrs start` and carried by every
188    /// subsequent control message about that dataflow. It also names the
189    /// shared-memory segments of its nodes (`{dataflow_id}/{node_id}/
190    /// {generation}`, blueprint §6.2), which is why a stale segment is always
191    /// attributable.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use astrs_wire::DataflowId;
197    ///
198    /// let id = DataflowId::generate();
199    /// let text = id.to_string();
200    /// assert_eq!(text.parse::<DataflowId>()?, id);
201    /// # Ok::<(), uuid::Error>(())
202    /// ```
203    DataflowId, "dataflow id"
204}
205
206define_uuid_id! {
207    /// The identity of one connection session.
208    ///
209    /// Assigned by the accepting side in `Welcome` and echoed in
210    /// reconnect handshakes so a daemon returning from a partition
211    /// (blueprint §12, *degraded-autonomous* mode) can be recognised as the
212    /// same participant and resynchronised with `StateCatchUp` instead of
213    /// re-registered from scratch.
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use astrs_wire::SessionId;
219    ///
220    /// let session = SessionId::generate();
221    /// assert!(!session.is_nil());
222    /// ```
223    SessionId, "session id"
224}
225
226define_uuid_id! {
227    /// The identity of one build of a dataflow.
228    ///
229    /// `astrs build` returns one; `astrs start --build <id>` consumes it, and
230    /// the coordinator's build cache index is keyed by it.
231    ///
232    /// # Examples
233    ///
234    /// ```
235    /// use astrs_wire::BuildId;
236    ///
237    /// let build = BuildId::from_u128(7);
238    /// assert_eq!(build.as_u128(), 7);
239    /// ```
240    BuildId, "build id"
241}
242
243/// The identity of a log, topic or telemetry subscription.
244///
245/// Blueprint §7.3: log and topic fan-out to the CLI rides the ordinary framing
246/// with a `SubscriptionId` in the payload, rather than a bespoke binary-prefix
247/// side channel. Subscriptions are per-connection, so a monotonically
248/// increasing 64-bit counter is enough — no UUID needed, and the smaller
249/// encoding matters on a high-rate `astrs topic echo`.
250///
251/// # Examples
252///
253/// ```
254/// use astrs_wire::SubscriptionId;
255///
256/// let first = SubscriptionId::FIRST;
257/// let second = first.next();
258/// assert_eq!(first.get(), 1);
259/// assert_eq!(second.get(), 2);
260/// assert!(second > first);
261/// ```
262#[derive(
263    Debug,
264    Clone,
265    Copy,
266    Default,
267    PartialEq,
268    Eq,
269    PartialOrd,
270    Ord,
271    Hash,
272    Serialize,
273    Deserialize,
274    Encode,
275    Decode,
276)]
277#[serde(transparent)]
278pub struct SubscriptionId(u64);
279
280impl SubscriptionId {
281    /// The reserved "no subscription" value.
282    pub const NONE: Self = Self(0);
283
284    /// The first id an allocator hands out.
285    pub const FIRST: Self = Self(1);
286
287    /// Wraps a raw counter value.
288    ///
289    /// # Examples
290    ///
291    /// ```
292    /// use astrs_wire::SubscriptionId;
293    ///
294    /// assert_eq!(SubscriptionId::new(42).get(), 42);
295    /// ```
296    #[must_use]
297    pub const fn new(value: u64) -> Self {
298        Self(value)
299    }
300
301    /// The raw counter value.
302    #[must_use]
303    pub const fn get(&self) -> u64 {
304        self.0
305    }
306
307    /// Whether this is the reserved "no subscription" value.
308    #[must_use]
309    pub const fn is_none(&self) -> bool {
310        self.0 == 0
311    }
312
313    /// The next id in sequence.
314    ///
315    /// Saturates at [`u64::MAX`] rather than wrapping: reusing a live
316    /// subscription id would misroute a stream, which is worse than refusing
317    /// to allocate after 2^64 subscriptions on one connection.
318    ///
319    /// # Examples
320    ///
321    /// ```
322    /// use astrs_wire::SubscriptionId;
323    ///
324    /// assert_eq!(SubscriptionId::new(1).next().get(), 2);
325    /// assert_eq!(SubscriptionId::new(u64::MAX).next().get(), u64::MAX);
326    /// ```
327    #[must_use]
328    pub const fn next(&self) -> Self {
329        Self(self.0.saturating_add(1))
330    }
331}
332
333impl fmt::Display for SubscriptionId {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        fmt::Display::fmt(&self.0, f)
336    }
337}
338
339impl From<u64> for SubscriptionId {
340    fn from(value: u64) -> Self {
341        Self(value)
342    }
343}
344
345impl From<SubscriptionId> for u64 {
346    fn from(id: SubscriptionId) -> Self {
347        id.0
348    }
349}
350
351impl FromStr for SubscriptionId {
352    type Err = core::num::ParseIntError;
353
354    fn from_str(value: &str) -> Result<Self, Self::Err> {
355        Ok(Self(value.parse()?))
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
362
363    use super::*;
364    use crate::codec::{WireDecode, WireEncode};
365
366    #[test]
367    fn uuids_encode_as_sixteen_raw_bytes() {
368        let id = DataflowId::from_u128(0x0102_0304_0506_0708_090A_0B0C_0D0E_0F10);
369        let bytes = id.encode_to_vec().unwrap();
370        assert_eq!(bytes.len(), UUID_WIRE_LEN);
371        assert_eq!(
372            bytes,
373            vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
374        );
375        assert_eq!(id.encode_size_hint().unwrap(), UUID_WIRE_LEN);
376    }
377
378    #[test]
379    fn uuid_ids_round_trip_through_the_codec() {
380        let dataflow = DataflowId::generate();
381        let session = SessionId::generate();
382        let build = BuildId::generate();
383
384        assert_eq!(
385            DataflowId::decode_exact(&dataflow.encode_to_vec().unwrap()).unwrap(),
386            dataflow
387        );
388        assert_eq!(
389            SessionId::decode_exact(&session.encode_to_vec().unwrap()).unwrap(),
390            session
391        );
392        assert_eq!(
393            BuildId::decode_exact(&build.encode_to_vec().unwrap()).unwrap(),
394            build
395        );
396    }
397
398    #[test]
399    fn generated_ids_are_version_seven_and_distinct() {
400        let first = SessionId::generate();
401        let second = SessionId::generate();
402        assert_ne!(first, second);
403        assert_eq!(first.as_uuid().get_version_num(), 7);
404        assert!(!first.is_nil());
405    }
406
407    #[test]
408    fn version_seven_ids_sort_chronologically() {
409        let mut ids: Vec<BuildId> = (0..8).map(|_| BuildId::generate()).collect();
410        let generated = ids.clone();
411        ids.sort();
412        assert_eq!(ids, generated, "v7 ids must already be in creation order");
413    }
414
415    #[test]
416    fn nil_is_the_zero_value() {
417        assert!(DataflowId::NIL.is_nil());
418        assert_eq!(DataflowId::NIL.as_u128(), 0);
419        assert_eq!(DataflowId::NIL.to_bytes(), [0u8; UUID_WIRE_LEN]);
420    }
421
422    #[test]
423    fn text_form_round_trips() {
424        let id = DataflowId::from_u128(0xDEAD_BEEF_CAFE_F00D_0011_2233_4455_6677);
425        let text = id.to_string();
426        assert_eq!(text.len(), 36);
427        assert_eq!(text.parse::<DataflowId>().unwrap(), id);
428        assert!(text.chars().all(|c| c.is_ascii_hexdigit() || c == '-'));
429    }
430
431    #[test]
432    fn parsing_a_non_uuid_fails() {
433        assert!("not-a-uuid".parse::<DataflowId>().is_err());
434        assert!("".parse::<SessionId>().is_err());
435    }
436
437    #[test]
438    fn byte_and_integer_forms_agree() {
439        let id = BuildId::from_u128(0x0102_0304_0506_0708_090A_0B0C_0D0E_0F10);
440        assert_eq!(BuildId::from_bytes(id.to_bytes()), id);
441        assert_eq!(BuildId::from_uuid(id.into_uuid()), id);
442        assert_eq!(Uuid::from(id), *id.as_uuid());
443        assert_eq!(BuildId::from(Uuid::from(id)), id);
444    }
445
446    #[test]
447    fn serde_uses_the_hyphenated_text_form() {
448        let id = SessionId::from_u128(1);
449        let json = serde_json::to_string(&id).unwrap();
450        assert_eq!(json, "\"00000000-0000-0000-0000-000000000001\"");
451        assert_eq!(serde_json::from_str::<SessionId>(&json).unwrap(), id);
452    }
453
454    #[test]
455    fn debug_names_the_type() {
456        let id = SessionId::from_u128(1);
457        assert!(format!("{id:?}").starts_with("SessionId("));
458    }
459
460    #[test]
461    fn subscription_ids_count_and_saturate() {
462        assert!(SubscriptionId::NONE.is_none());
463        assert!(!SubscriptionId::FIRST.is_none());
464        assert_eq!(SubscriptionId::default(), SubscriptionId::NONE);
465        assert_eq!(SubscriptionId::FIRST.next().get(), 2);
466        assert_eq!(SubscriptionId::new(u64::MAX).next().get(), u64::MAX);
467        assert_eq!(SubscriptionId::from(5u64).get(), 5);
468        assert_eq!(u64::from(SubscriptionId::new(5)), 5);
469        assert_eq!("77".parse::<SubscriptionId>().unwrap().get(), 77);
470        assert!("x".parse::<SubscriptionId>().is_err());
471        assert_eq!(SubscriptionId::new(9).to_string(), "9");
472    }
473
474    #[test]
475    fn subscription_ids_round_trip_and_stay_compact() {
476        let id = SubscriptionId::new(1);
477        let bytes = id.encode_to_vec().unwrap();
478        assert_eq!(bytes.len(), 1, "small ids must cost one varint byte");
479        assert_eq!(SubscriptionId::decode_exact(&bytes).unwrap(), id);
480
481        let big = SubscriptionId::new(u64::MAX);
482        assert_eq!(
483            SubscriptionId::decode_exact(&big.encode_to_vec().unwrap()).unwrap(),
484            big
485        );
486    }
487
488    #[test]
489    fn a_truncated_uuid_payload_is_rejected() {
490        let id = DataflowId::from_u128(1);
491        let bytes = id.encode_to_vec().unwrap();
492        assert!(DataflowId::decode_exact(&bytes[..15]).is_err());
493    }
494
495    #[test]
496    fn trailing_bytes_after_a_uuid_are_rejected() {
497        let mut bytes = DataflowId::from_u128(1).encode_to_vec().unwrap();
498        bytes.push(0);
499        assert!(matches!(
500            DataflowId::decode_exact(&bytes),
501            Err(crate::WireError::TrailingBytes { .. })
502        ));
503    }
504}