Skip to main content

tea_protocol/
id.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use thiserror::Error;
6use uuid::{Uuid, Version};
7
8/// Error returned when parsing a canonical protocol identifier.
9#[derive(Debug, Error)]
10pub enum ProtocolIdParseError {
11    /// The text is not a valid UUID.
12    #[error("invalid UUID: {0}")]
13    InvalidUuid(#[from] uuid::Error),
14    /// The UUID is valid but is not canonical lowercase hyphenated text.
15    #[error("protocol ID must use canonical lowercase hyphenated UUID text")]
16    NonCanonical,
17    /// The UUID does not use version 7.
18    #[error("protocol ID must use UUID version 7")]
19    WrongVersion,
20}
21
22fn parse_uuid_v7(value: &str) -> Result<Uuid, ProtocolIdParseError> {
23    let uuid = Uuid::parse_str(value)?;
24    if uuid.get_version() != Some(Version::SortRand) {
25        return Err(ProtocolIdParseError::WrongVersion);
26    }
27    if uuid.hyphenated().to_string() != value {
28        return Err(ProtocolIdParseError::NonCanonical);
29    }
30    Ok(uuid)
31}
32
33macro_rules! protocol_id {
34    ($name:ident, $doc:literal) => {
35        #[doc = $doc]
36        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
37        pub struct $name(Uuid);
38
39        impl $name {
40            /// Returns the underlying UUID value.
41            #[must_use]
42            pub const fn as_uuid(&self) -> &Uuid {
43                &self.0
44            }
45        }
46
47        impl fmt::Display for $name {
48            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49                self.0.hyphenated().fmt(formatter)
50            }
51        }
52
53        impl FromStr for $name {
54            type Err = ProtocolIdParseError;
55
56            fn from_str(value: &str) -> Result<Self, Self::Err> {
57                parse_uuid_v7(value).map(Self)
58            }
59        }
60
61        impl Serialize for $name {
62            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
63            where
64                S: Serializer,
65            {
66                serializer.collect_str(self)
67            }
68        }
69
70        impl<'de> Deserialize<'de> for $name {
71            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
72            where
73                D: Deserializer<'de>,
74            {
75                let value = String::deserialize(deserializer)?;
76                value.parse().map_err(serde::de::Error::custom)
77            }
78        }
79    };
80}
81
82protocol_id!(SessionId, "A stable agent session identifier.");
83protocol_id!(RunId, "A stable agent run identifier.");
84protocol_id!(TurnId, "A stable agent turn identifier.");
85protocol_id!(MessageId, "A stable canonical message identifier.");
86protocol_id!(ToolCallId, "A stable canonical tool-call identifier.");
87protocol_id!(ApprovalId, "A stable approval request identifier.");
88protocol_id!(EventId, "A stable observable event identifier.");
89protocol_id!(CommandId, "A stable command identifier.");
90protocol_id!(BranchId, "A stable session branch identifier.");
91protocol_id!(RecordId, "A stable durable session record identifier.");
92protocol_id!(CorrelationId, "A stable diagnostic correlation identifier.");
93protocol_id!(
94    CausationId,
95    "A stable identifier for the command or record that caused a fact."
96);