1use 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
43pub const UUID_WIRE_LEN: usize = 16;
45
46macro_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 #[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 #[doc = concat!("use astrs_wire::", stringify!($name), ";")]
72 #[doc = concat!("let id = ", stringify!($name), "::generate();")]
74 #[doc = concat!("assert_ne!(id, ", stringify!($name), "::NIL);")]
75 #[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 #[must_use]
89 pub const fn as_uuid(&self) -> &Uuid {
90 &self.0
91 }
92
93 #[must_use]
95 pub const fn into_uuid(self) -> Uuid {
96 self.0
97 }
98
99 #[must_use]
104 pub const fn from_u128(value: u128) -> Self {
105 Self(Uuid::from_u128(value))
106 }
107
108 #[must_use]
110 pub const fn as_u128(&self) -> u128 {
111 self.0.as_u128()
112 }
113
114 #[must_use]
116 pub const fn from_bytes(bytes: [u8; UUID_WIRE_LEN]) -> Self {
117 Self(Uuid::from_bytes(bytes))
118 }
119
120 #[must_use]
122 pub const fn to_bytes(&self) -> [u8; UUID_WIRE_LEN] {
123 *self.0.as_bytes()
124 }
125
126 #[must_use]
128 pub fn is_nil(&self) -> bool {
129 self.0.is_nil()
130 }
131 }
132
133 impl fmt::Display for $name {
134 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 DataflowId, "dataflow id"
204}
205
206define_uuid_id! {
207 SessionId, "session id"
224}
225
226define_uuid_id! {
227 BuildId, "build id"
241}
242
243#[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 pub const NONE: Self = Self(0);
283
284 pub const FIRST: Self = Self(1);
286
287 #[must_use]
297 pub const fn new(value: u64) -> Self {
298 Self(value)
299 }
300
301 #[must_use]
303 pub const fn get(&self) -> u64 {
304 self.0
305 }
306
307 #[must_use]
309 pub const fn is_none(&self) -> bool {
310 self.0 == 0
311 }
312
313 #[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}