Skip to main content

tea_context/
identity.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7macro_rules! context_id {
8    ($name:ident, $doc:literal) => {
9        #[doc = $doc]
10        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
11        #[serde(transparent)]
12        pub struct $name(String);
13
14        impl $name {
15            /// Returns canonical selector text.
16            #[must_use]
17            pub fn as_str(&self) -> &str {
18                &self.0
19            }
20        }
21
22        impl FromStr for $name {
23            type Err = ContextIdentityError;
24            fn from_str(value: &str) -> Result<Self, Self::Err> {
25                validate_id(value)?;
26                Ok(Self(value.to_owned()))
27            }
28        }
29
30        impl<'de> Deserialize<'de> for $name {
31            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
32            where
33                D: serde::Deserializer<'de>,
34            {
35                String::deserialize(deserializer)?
36                    .parse()
37                    .map_err(serde::de::Error::custom)
38            }
39        }
40
41        impl fmt::Display for $name {
42            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
43                formatter.write_str(&self.0)
44            }
45        }
46    };
47}
48
49context_id!(PromptModuleId, "Canonical prompt-module identity.");
50context_id!(PromptSegmentId, "Canonical prompt-segment identity.");
51context_id!(ContextProviderId, "Canonical context-provider identity.");
52context_id!(
53    ConflictKey,
54    "Canonical key for mutually exclusive prompt claims."
55);
56context_id!(SkillId, "Canonical skill metadata identity.");
57
58/// Invalid canonical context selector.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
60#[error("context identifier is not canonical")]
61pub struct ContextIdentityError;
62
63fn validate_id(value: &str) -> Result<(), ContextIdentityError> {
64    let mut bytes = value.bytes();
65    if value.len() > 128
66        || value.contains("..")
67        || !bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
68        || !bytes.all(|byte| {
69            byte.is_ascii_lowercase()
70                || byte.is_ascii_digit()
71                || matches!(byte, b'_' | b'-' | b'.' | b'/')
72        })
73    {
74        Err(ContextIdentityError)
75    } else {
76        Ok(())
77    }
78}