Skip to main content

stateknot_core/
ids.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Validated scheduler/tenant identifiers and canonical generated `UUIDv7` IDs.
5
6use std::{borrow::Borrow, fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11use uuid::{Uuid, Variant, Version};
12
13use crate::Digest;
14
15const UUID_V7_PATTERN: &str =
16    "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
17
18/// A validated tenant boundary identifier.
19///
20/// Tenant IDs contain 1 to 128 ASCII letters, digits, `.`, `_`, `:`, or `-`.
21/// The path-like special values `.` and `..` are rejected. This validation is
22/// applied equally to constructors, string parsing, and deserialization.
23#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub struct TenantId(Box<str>);
25
26impl TenantId {
27    /// Maximum encoded length of a tenant identifier in bytes.
28    pub const MAX_LEN: usize = 128;
29
30    /// Validates and constructs a tenant identifier without copying a `String`.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`TenantIdError`] when `value` is empty, too long, path-like, or
35    /// contains a byte outside the allowed ASCII grammar.
36    pub fn new(value: impl Into<String>) -> Result<Self, TenantIdError> {
37        let value = value.into();
38        validate_tenant_id(&value)?;
39        Ok(Self(value.into_boxed_str()))
40    }
41
42    /// Returns the canonical tenant identifier text.
43    #[must_use]
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47}
48
49impl AsRef<str> for TenantId {
50    fn as_ref(&self) -> &str {
51        self.as_str()
52    }
53}
54
55impl Borrow<str> for TenantId {
56    fn borrow(&self) -> &str {
57        self.as_str()
58    }
59}
60
61impl fmt::Debug for TenantId {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        formatter
64            .debug_tuple("TenantId")
65            .field(&self.as_str())
66            .finish()
67    }
68}
69
70impl fmt::Display for TenantId {
71    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72        formatter.write_str(self.as_str())
73    }
74}
75
76impl FromStr for TenantId {
77    type Err = TenantIdError;
78
79    fn from_str(value: &str) -> Result<Self, Self::Err> {
80        Self::new(value)
81    }
82}
83
84impl TryFrom<String> for TenantId {
85    type Error = TenantIdError;
86
87    fn try_from(value: String) -> Result<Self, Self::Error> {
88        Self::new(value)
89    }
90}
91
92impl TryFrom<&str> for TenantId {
93    type Error = TenantIdError;
94
95    fn try_from(value: &str) -> Result<Self, Self::Error> {
96        Self::new(value)
97    }
98}
99
100impl From<TenantId> for String {
101    fn from(value: TenantId) -> Self {
102        value.0.into()
103    }
104}
105
106impl Serialize for TenantId {
107    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
108    where
109        S: Serializer,
110    {
111        serializer.serialize_str(self.as_str())
112    }
113}
114
115impl<'de> Deserialize<'de> for TenantId {
116    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117    where
118        D: Deserializer<'de>,
119    {
120        deserializer.deserialize_str(TenantIdVisitor)
121    }
122}
123
124impl JsonSchema for TenantId {
125    fn schema_name() -> std::borrow::Cow<'static, str> {
126        "TenantId".into()
127    }
128
129    fn schema_id() -> std::borrow::Cow<'static, str> {
130        concat!(module_path!(), "::TenantId").into()
131    }
132
133    fn json_schema(_: &mut SchemaGenerator) -> Schema {
134        json_schema!({
135            "type": "string",
136            "minLength": 1,
137            "maxLength": 128,
138            "pattern": "^(?!\\.{1,2}$)[A-Za-z0-9._:-]+$"
139        })
140    }
141
142    fn inline_schema() -> bool {
143        true
144    }
145}
146
147/// Validation failure for a [`TenantId`].
148#[derive(Clone, Debug, Eq, Error, PartialEq)]
149#[non_exhaustive]
150pub enum TenantIdError {
151    /// The identifier contained no bytes.
152    #[error("tenant identifier must not be empty")]
153    Empty,
154
155    /// The identifier exceeded [`TenantId::MAX_LEN`].
156    #[error("tenant identifier is {actual} bytes; maximum is {max}")]
157    TooLong {
158        /// Maximum accepted byte length.
159        max: usize,
160        /// Observed byte length.
161        actual: usize,
162    },
163
164    /// The identifier was `.` or `..`.
165    #[error("tenant identifier must not be path-like")]
166    PathLike,
167
168    /// A byte did not belong to the allowed ASCII grammar.
169    #[error("tenant identifier contains an invalid byte at offset {index}")]
170    InvalidByte {
171        /// Zero-based byte offset of the first invalid byte.
172        index: usize,
173    },
174}
175
176struct TenantIdVisitor;
177
178impl de::Visitor<'_> for TenantIdVisitor {
179    type Value = TenantId;
180
181    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        formatter.write_str("a canonical StateKnot tenant identifier")
183    }
184
185    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
186    where
187        E: de::Error,
188    {
189        TenantId::try_from(value).map_err(E::custom)
190    }
191
192    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
193    where
194        E: de::Error,
195    {
196        TenantId::try_from(value).map_err(E::custom)
197    }
198}
199
200fn validate_tenant_id(value: &str) -> Result<(), TenantIdError> {
201    if value.is_empty() {
202        return Err(TenantIdError::Empty);
203    }
204    if value.len() > TenantId::MAX_LEN {
205        return Err(TenantIdError::TooLong {
206            max: TenantId::MAX_LEN,
207            actual: value.len(),
208        });
209    }
210    if matches!(value, "." | "..") {
211        return Err(TenantIdError::PathLike);
212    }
213
214    if let Some((index, _)) = value.bytes().enumerate().find(|(_, byte)| {
215        !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'-')
216    }) {
217        return Err(TenantIdError::InvalidByte { index });
218    }
219
220    Ok(())
221}
222
223/// Opaque caller key for durable Agent-submission idempotency.
224///
225/// Keys contain 16 to 128 header-safe ASCII bytes. Clients should generate at
226/// least 128 bits of unpredictability and reuse the same key only for the same
227/// logical submission. The raw value is never included in `Debug`; durability
228/// providers store only its tenant-scoped digest.
229#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
230pub struct AgentSubmissionKey(Box<str>);
231
232impl AgentSubmissionKey {
233    /// Smallest accepted encoded key length.
234    pub const MIN_LEN: usize = 16;
235    /// Largest accepted encoded key length.
236    pub const MAX_LEN: usize = 128;
237
238    /// Validates one externally supplied idempotency key.
239    ///
240    /// # Errors
241    ///
242    /// Rejects short, oversized, non-ASCII, whitespace, disallowed punctuation,
243    /// or control input instead of normalizing two caller keys into one durable
244    /// identity.
245    pub fn new(value: impl Into<String>) -> Result<Self, AgentSubmissionKeyError> {
246        let value = value.into();
247        validate_agent_submission_key(&value)?;
248        Ok(Self(value.into_boxed_str()))
249    }
250
251    /// Generates two canonical `UUIDv7` values carrying 148 random bits in total.
252    ///
253    /// A single `UUIDv7` carries 74 random bits; joining two independently
254    /// generated values keeps timestamp sortability while meeting the public
255    /// recommendation of at least 128 bits of unpredictability.
256    #[must_use]
257    pub fn generate() -> Self {
258        Self(format!("{}.{}", Uuid::now_v7(), Uuid::now_v7()).into_boxed_str())
259    }
260
261    /// Returns the exact caller key for an outbound idempotency header.
262    #[must_use]
263    pub fn as_str(&self) -> &str {
264        &self.0
265    }
266
267    /// Derives the one-way tenant-scoped storage key.
268    ///
269    /// Scoping prevents equal raw keys in different tenants from sharing a
270    /// database lookup value. The domain and delimiter make the encoding
271    /// unambiguous and versioned.
272    #[must_use]
273    pub fn digest_for(&self, tenant_id: &TenantId) -> Digest {
274        const DOMAIN: &[u8] = b"stateknot.agent-submission-key.v1\0";
275
276        let mut preimage =
277            Vec::with_capacity(DOMAIN.len() + tenant_id.as_str().len() + 1 + self.as_str().len());
278        preimage.extend_from_slice(DOMAIN);
279        preimage.extend_from_slice(tenant_id.as_str().as_bytes());
280        preimage.push(0);
281        preimage.extend_from_slice(self.as_str().as_bytes());
282        Digest::sha256(preimage)
283    }
284}
285
286impl fmt::Debug for AgentSubmissionKey {
287    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
288        formatter
289            .debug_struct("AgentSubmissionKey")
290            .field("byte_length", &self.as_str().len())
291            .finish_non_exhaustive()
292    }
293}
294
295impl FromStr for AgentSubmissionKey {
296    type Err = AgentSubmissionKeyError;
297
298    fn from_str(value: &str) -> Result<Self, Self::Err> {
299        Self::new(value)
300    }
301}
302
303impl TryFrom<String> for AgentSubmissionKey {
304    type Error = AgentSubmissionKeyError;
305
306    fn try_from(value: String) -> Result<Self, Self::Error> {
307        Self::new(value)
308    }
309}
310
311impl TryFrom<&str> for AgentSubmissionKey {
312    type Error = AgentSubmissionKeyError;
313
314    fn try_from(value: &str) -> Result<Self, Self::Error> {
315        Self::new(value)
316    }
317}
318
319impl Serialize for AgentSubmissionKey {
320    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
321    where
322        S: Serializer,
323    {
324        serializer.serialize_str(self.as_str())
325    }
326}
327
328impl<'de> Deserialize<'de> for AgentSubmissionKey {
329    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
330    where
331        D: Deserializer<'de>,
332    {
333        deserializer.deserialize_str(AgentSubmissionKeyVisitor)
334    }
335}
336
337impl JsonSchema for AgentSubmissionKey {
338    fn schema_name() -> std::borrow::Cow<'static, str> {
339        "AgentSubmissionKey".into()
340    }
341
342    fn schema_id() -> std::borrow::Cow<'static, str> {
343        concat!(module_path!(), "::AgentSubmissionKey").into()
344    }
345
346    fn json_schema(_: &mut SchemaGenerator) -> Schema {
347        json_schema!({
348            "type": "string",
349            "minLength": 16,
350            "maxLength": 128,
351            "pattern": "^[A-Za-z0-9._~-]{16,128}$"
352        })
353    }
354
355    fn inline_schema() -> bool {
356        true
357    }
358}
359
360/// Invalid external Agent-submission idempotency key.
361#[derive(Clone, Debug, Eq, Error, PartialEq)]
362#[non_exhaustive]
363pub enum AgentSubmissionKeyError {
364    /// The key did not meet the minimum length required for safe caller IDs.
365    #[error("Agent submission key is {actual} bytes; minimum is {minimum}")]
366    TooShort {
367        /// Required minimum byte length.
368        minimum: usize,
369        /// Observed byte length.
370        actual: usize,
371    },
372    /// The key exceeded the hard request/header bound.
373    #[error("Agent submission key is {actual} bytes; maximum is {maximum}")]
374    TooLong {
375        /// Accepted maximum byte length.
376        maximum: usize,
377        /// Observed byte length.
378        actual: usize,
379    },
380    /// A byte did not belong to the exact opaque-key grammar.
381    #[error("Agent submission key contains an invalid byte at offset {index}")]
382    InvalidByte {
383        /// Zero-based byte offset of the first rejected byte.
384        index: usize,
385    },
386}
387
388struct AgentSubmissionKeyVisitor;
389
390impl de::Visitor<'_> for AgentSubmissionKeyVisitor {
391    type Value = AgentSubmissionKey;
392
393    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
394        formatter.write_str("a bounded opaque StateKnot Agent submission key")
395    }
396
397    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
398    where
399        E: de::Error,
400    {
401        AgentSubmissionKey::try_from(value).map_err(E::custom)
402    }
403
404    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
405    where
406        E: de::Error,
407    {
408        AgentSubmissionKey::try_from(value).map_err(E::custom)
409    }
410}
411
412fn validate_agent_submission_key(value: &str) -> Result<(), AgentSubmissionKeyError> {
413    if value.len() < AgentSubmissionKey::MIN_LEN {
414        return Err(AgentSubmissionKeyError::TooShort {
415            minimum: AgentSubmissionKey::MIN_LEN,
416            actual: value.len(),
417        });
418    }
419    if value.len() > AgentSubmissionKey::MAX_LEN {
420        return Err(AgentSubmissionKeyError::TooLong {
421            maximum: AgentSubmissionKey::MAX_LEN,
422            actual: value.len(),
423        });
424    }
425    if let Some((index, _)) = value.bytes().enumerate().find(|(_, byte)| {
426        !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b'~' | b'-')
427    }) {
428        return Err(AgentSubmissionKeyError::InvalidByte { index });
429    }
430    Ok(())
431}
432
433/// A stable distributed-scheduler shard identifier.
434///
435/// Shard IDs use the same bounded ASCII grammar as tenant IDs but represent a
436/// control-plane ownership boundary, never a tenant authorization boundary.
437/// A policy change should normally publish a new shard identifier so rolling
438/// deployments cannot silently run different weighted schedules.
439#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
440pub struct SchedulerShardId(Box<str>);
441
442impl SchedulerShardId {
443    /// Maximum encoded shard identifier length in bytes.
444    pub const MAX_LEN: usize = 128;
445
446    /// Validates and constructs a scheduler shard identifier.
447    ///
448    /// # Errors
449    ///
450    /// Returns [`SchedulerShardIdError`] for an empty, oversized, path-like,
451    /// or non-canonical ASCII value.
452    pub fn new(value: impl Into<String>) -> Result<Self, SchedulerShardIdError> {
453        let value = value.into();
454        validate_scheduler_shard_id(&value)?;
455        Ok(Self(value.into_boxed_str()))
456    }
457
458    /// Returns the exact durable shard identifier.
459    #[must_use]
460    pub fn as_str(&self) -> &str {
461        &self.0
462    }
463}
464
465impl AsRef<str> for SchedulerShardId {
466    fn as_ref(&self) -> &str {
467        self.as_str()
468    }
469}
470
471impl Borrow<str> for SchedulerShardId {
472    fn borrow(&self) -> &str {
473        self.as_str()
474    }
475}
476
477impl fmt::Debug for SchedulerShardId {
478    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
479        formatter
480            .debug_tuple("SchedulerShardId")
481            .field(&self.as_str())
482            .finish()
483    }
484}
485
486impl fmt::Display for SchedulerShardId {
487    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
488        formatter.write_str(self.as_str())
489    }
490}
491
492impl FromStr for SchedulerShardId {
493    type Err = SchedulerShardIdError;
494
495    fn from_str(value: &str) -> Result<Self, Self::Err> {
496        Self::new(value)
497    }
498}
499
500impl TryFrom<String> for SchedulerShardId {
501    type Error = SchedulerShardIdError;
502
503    fn try_from(value: String) -> Result<Self, Self::Error> {
504        Self::new(value)
505    }
506}
507
508impl TryFrom<&str> for SchedulerShardId {
509    type Error = SchedulerShardIdError;
510
511    fn try_from(value: &str) -> Result<Self, Self::Error> {
512        Self::new(value)
513    }
514}
515
516impl From<SchedulerShardId> for String {
517    fn from(value: SchedulerShardId) -> Self {
518        value.0.into()
519    }
520}
521
522impl Serialize for SchedulerShardId {
523    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
524    where
525        S: Serializer,
526    {
527        serializer.serialize_str(self.as_str())
528    }
529}
530
531impl<'de> Deserialize<'de> for SchedulerShardId {
532    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
533    where
534        D: Deserializer<'de>,
535    {
536        deserializer.deserialize_str(SchedulerShardIdVisitor)
537    }
538}
539
540impl JsonSchema for SchedulerShardId {
541    fn schema_name() -> std::borrow::Cow<'static, str> {
542        "SchedulerShardId".into()
543    }
544
545    fn schema_id() -> std::borrow::Cow<'static, str> {
546        concat!(module_path!(), "::SchedulerShardId").into()
547    }
548
549    fn json_schema(_: &mut SchemaGenerator) -> Schema {
550        json_schema!({
551            "type": "string",
552            "minLength": 1,
553            "maxLength": 128,
554            "pattern": "^(?!\\.{1,2}$)[A-Za-z0-9._:-]+$"
555        })
556    }
557
558    fn inline_schema() -> bool {
559        true
560    }
561}
562
563/// Validation failure for a [`SchedulerShardId`].
564#[derive(Clone, Debug, Eq, Error, PartialEq)]
565#[non_exhaustive]
566pub enum SchedulerShardIdError {
567    /// The identifier contained no bytes.
568    #[error("scheduler shard identifier must not be empty")]
569    Empty,
570    /// The identifier exceeded [`SchedulerShardId::MAX_LEN`].
571    #[error("scheduler shard identifier is {actual} bytes; maximum is {max}")]
572    TooLong {
573        /// Maximum accepted byte length.
574        max: usize,
575        /// Observed byte length.
576        actual: usize,
577    },
578    /// The identifier was `.` or `..`.
579    #[error("scheduler shard identifier must not be path-like")]
580    PathLike,
581    /// A byte did not belong to the allowed ASCII grammar.
582    #[error("scheduler shard identifier contains an invalid byte at offset {index}")]
583    InvalidByte {
584        /// Zero-based byte offset of the first invalid byte.
585        index: usize,
586    },
587}
588
589struct SchedulerShardIdVisitor;
590
591impl de::Visitor<'_> for SchedulerShardIdVisitor {
592    type Value = SchedulerShardId;
593
594    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
595        formatter.write_str("a canonical StateKnot scheduler shard identifier")
596    }
597
598    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
599    where
600        E: de::Error,
601    {
602        SchedulerShardId::try_from(value).map_err(E::custom)
603    }
604
605    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
606    where
607        E: de::Error,
608    {
609        SchedulerShardId::try_from(value).map_err(E::custom)
610    }
611}
612
613fn validate_scheduler_shard_id(value: &str) -> Result<(), SchedulerShardIdError> {
614    if value.is_empty() {
615        return Err(SchedulerShardIdError::Empty);
616    }
617    if value.len() > SchedulerShardId::MAX_LEN {
618        return Err(SchedulerShardIdError::TooLong {
619            max: SchedulerShardId::MAX_LEN,
620            actual: value.len(),
621        });
622    }
623    if matches!(value, "." | "..") {
624        return Err(SchedulerShardIdError::PathLike);
625    }
626    if let Some((index, _)) = value.bytes().enumerate().find(|(_, byte)| {
627        !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'-')
628    }) {
629        return Err(SchedulerShardIdError::InvalidByte { index });
630    }
631    Ok(())
632}
633
634/// Parse or construction failure for a StateKnot-generated identifier.
635#[derive(Clone, Debug, Eq, Error, PartialEq)]
636#[non_exhaustive]
637pub enum GeneratedIdError {
638    /// The input was not a UUID.
639    #[error("identifier is not a valid UUID")]
640    InvalidUuid,
641
642    /// The input used a valid but non-canonical UUID representation.
643    #[error("identifier must use lowercase hyphenated UUID text")]
644    NonCanonical,
645
646    /// The UUID was not version 7.
647    #[error("identifier must be UUID version 7")]
648    WrongVersion,
649
650    /// The UUID did not use the RFC 4122/RFC 9562 variant.
651    #[error("identifier must use the RFC 4122 variant")]
652    WrongVariant,
653}
654
655fn validate_generated_uuid(value: Uuid) -> Result<Uuid, GeneratedIdError> {
656    if value.get_variant() != Variant::RFC4122 {
657        return Err(GeneratedIdError::WrongVariant);
658    }
659    if value.get_version() != Some(Version::SortRand) {
660        return Err(GeneratedIdError::WrongVersion);
661    }
662    Ok(value)
663}
664
665fn parse_generated_uuid(value: &str) -> Result<Uuid, GeneratedIdError> {
666    let parsed = Uuid::parse_str(value).map_err(|_| GeneratedIdError::InvalidUuid)?;
667    if parsed.hyphenated().to_string() != value {
668        return Err(GeneratedIdError::NonCanonical);
669    }
670    validate_generated_uuid(parsed)
671}
672
673fn serialize_generated_uuid<S>(value: &Uuid, serializer: S) -> Result<S::Ok, S::Error>
674where
675    S: Serializer,
676{
677    serializer.collect_str(&value.hyphenated())
678}
679
680struct GeneratedUuidVisitor;
681
682impl de::Visitor<'_> for GeneratedUuidVisitor {
683    type Value = Uuid;
684
685    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
686        formatter.write_str("a lowercase hyphenated UUID version 7 identifier")
687    }
688
689    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
690    where
691        E: de::Error,
692    {
693        parse_generated_uuid(value).map_err(E::custom)
694    }
695}
696
697fn deserialize_generated_uuid<'de, D>(deserializer: D) -> Result<Uuid, D::Error>
698where
699    D: Deserializer<'de>,
700{
701    deserializer.deserialize_str(GeneratedUuidVisitor)
702}
703
704macro_rules! define_generated_id {
705    ($name:ident, $documentation:literal) => {
706        #[doc = $documentation]
707        #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
708        pub struct $name(Uuid);
709
710        impl $name {
711            /// Generates a `UUIDv7` identifier using the process UUID generator.
712            #[must_use]
713            pub fn generate() -> Self {
714                Self(Uuid::now_v7())
715            }
716
717            /// Constructs the typed identifier from a `UUIDv7` value.
718            ///
719            /// # Errors
720            ///
721            /// Returns [`GeneratedIdError`] when the UUID has the wrong version
722            /// or variant.
723            pub fn from_uuid(value: Uuid) -> Result<Self, GeneratedIdError> {
724                validate_generated_uuid(value).map(Self)
725            }
726
727            /// Returns the underlying UUID value.
728            #[must_use]
729            pub const fn as_uuid(&self) -> &Uuid {
730                &self.0
731            }
732
733            /// Consumes this identifier and returns its UUID value.
734            #[must_use]
735            pub const fn into_uuid(self) -> Uuid {
736                self.0
737            }
738        }
739
740        impl TryFrom<Uuid> for $name {
741            type Error = GeneratedIdError;
742
743            fn try_from(value: Uuid) -> Result<Self, Self::Error> {
744                Self::from_uuid(value)
745            }
746        }
747
748        impl From<$name> for Uuid {
749            fn from(value: $name) -> Self {
750                value.into_uuid()
751            }
752        }
753
754        impl FromStr for $name {
755            type Err = GeneratedIdError;
756
757            fn from_str(value: &str) -> Result<Self, Self::Err> {
758                parse_generated_uuid(value).map(Self)
759            }
760        }
761
762        impl fmt::Debug for $name {
763            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
764                formatter
765                    .debug_tuple(stringify!($name))
766                    .field(&self.0.hyphenated())
767                    .finish()
768            }
769        }
770
771        impl fmt::Display for $name {
772            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
773                fmt::Display::fmt(&self.0.hyphenated(), formatter)
774            }
775        }
776
777        impl Serialize for $name {
778            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
779            where
780                S: Serializer,
781            {
782                serialize_generated_uuid(&self.0, serializer)
783            }
784        }
785
786        impl<'de> Deserialize<'de> for $name {
787            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
788            where
789                D: Deserializer<'de>,
790            {
791                deserialize_generated_uuid(deserializer).map(Self)
792            }
793        }
794
795        impl JsonSchema for $name {
796            fn schema_name() -> std::borrow::Cow<'static, str> {
797                stringify!($name).into()
798            }
799
800            fn schema_id() -> std::borrow::Cow<'static, str> {
801                concat!(module_path!(), "::", stringify!($name)).into()
802            }
803
804            fn json_schema(_: &mut SchemaGenerator) -> Schema {
805                json_schema!({
806                    "type": "string",
807                    "format": "uuid",
808                    "minLength": 36,
809                    "maxLength": 36,
810                    "pattern": UUID_V7_PATTERN
811                })
812            }
813
814            fn inline_schema() -> bool {
815                true
816            }
817        }
818    };
819}
820
821define_generated_id!(RunId, "A tenant-scoped durable run identifier.");
822define_generated_id!(ThreadId, "A tenant-scoped conversation thread identifier.");
823define_generated_id!(EventId, "A tenant-scoped durable event identifier.");
824define_generated_id!(FailureId, "A tenant-scoped failure occurrence identifier.");
825define_generated_id!(MessageId, "A tenant-scoped durable message identifier.");
826define_generated_id!(ArtifactId, "A tenant-scoped artifact identifier.");
827define_generated_id!(
828    AuthorizationReceiptId,
829    "A tenant-scoped durable authorization receipt identifier."
830);
831define_generated_id!(
832    SkillActivationApprovalId,
833    "A tenant-scoped durable Skill activation approval identifier."
834);
835define_generated_id!(
836    SkillActingWindowId,
837    "A tenant-scoped durable Skill acting-window identifier."
838);
839define_generated_id!(
840    InvocationId,
841    "A tenant-scoped external invocation identifier."
842);
843define_generated_id!(InterruptId, "A tenant-scoped interrupt identifier.");
844define_generated_id!(TimerId, "A tenant-scoped durable timer identifier.");
845define_generated_id!(
846    DeliveryId,
847    "A tenant-scoped durable outbox delivery identifier."
848);
849define_generated_id!(
850    DestinationId,
851    "A tenant-scoped durable outbox destination identifier."
852);
853define_generated_id!(
854    CheckpointId,
855    "A tenant-scoped immutable checkpoint identifier."
856);
857define_generated_id!(
858    QuarantineId,
859    "A tenant-scoped durable run-quarantine observation identifier."
860);
861define_generated_id!(
862    AttemptId,
863    "A tenant-scoped node or dependency attempt identifier."
864);
865define_generated_id!(
866    SchedulerReservationId,
867    "A durable distributed-scheduler slot-reservation identifier."
868);
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873    use serde_json::{Value, from_str, from_value, to_string};
874
875    #[test]
876    fn tenant_id_accepts_the_documented_grammar() {
877        for value in ["a", "tenant-42", "org.example:production", "A_B"] {
878            let tenant = TenantId::try_from(value).expect("valid tenant ID");
879            assert_eq!(tenant.as_str(), value);
880            assert_eq!(tenant.to_string(), value);
881        }
882
883        let longest = "a".repeat(TenantId::MAX_LEN);
884        assert_eq!(TenantId::new(longest.clone()).unwrap().as_str(), longest);
885    }
886
887    #[test]
888    fn tenant_id_rejects_ambiguous_or_unbounded_values() {
889        assert_eq!(TenantId::try_from(""), Err(TenantIdError::Empty));
890        assert_eq!(TenantId::try_from("."), Err(TenantIdError::PathLike));
891        assert_eq!(TenantId::try_from(".."), Err(TenantIdError::PathLike));
892        assert_eq!(
893            TenantId::try_from("a".repeat(TenantId::MAX_LEN + 1)),
894            Err(TenantIdError::TooLong {
895                max: TenantId::MAX_LEN,
896                actual: TenantId::MAX_LEN + 1,
897            })
898        );
899
900        for value in ["tenant name", "tenant/name", "tenant\\name", "租户"] {
901            assert!(matches!(
902                TenantId::try_from(value),
903                Err(TenantIdError::InvalidByte { .. })
904            ));
905        }
906    }
907
908    #[test]
909    fn scheduler_shard_id_has_an_independent_bounded_control_plane_type() {
910        let shard = SchedulerShardId::try_from("prod:fairness-01").unwrap();
911        assert_eq!(shard.as_str(), "prod:fairness-01");
912        assert_eq!(shard.to_string(), "prod:fairness-01");
913        assert_eq!(
914            SchedulerShardId::try_from("."),
915            Err(SchedulerShardIdError::PathLike)
916        );
917        assert!(matches!(
918            SchedulerShardId::try_from("bad/shard"),
919            Err(SchedulerShardIdError::InvalidByte { index: 3 })
920        ));
921    }
922
923    #[test]
924    fn tenant_id_serde_revalidates_input() {
925        let tenant = TenantId::try_from("org.example:prod").unwrap();
926        let encoded = to_string(&tenant).unwrap();
927        assert_eq!(encoded, "\"org.example:prod\"");
928        assert_eq!(from_str::<TenantId>(&encoded).unwrap(), tenant);
929        assert!(from_str::<TenantId>("\"../other\"").is_err());
930        assert!(from_str::<TenantId>("42").is_err());
931    }
932
933    #[test]
934    fn tenant_id_schema_matches_runtime_validation_bounds() {
935        let schema = serde_json::to_value(schemars::schema_for!(TenantId)).unwrap();
936        assert_eq!(schema["type"], "string");
937        assert_eq!(schema["minLength"], 1);
938        assert_eq!(schema["maxLength"], TenantId::MAX_LEN);
939        assert_eq!(schema["pattern"], "^(?!\\.{1,2}$)[A-Za-z0-9._:-]+$");
940    }
941
942    #[test]
943    fn agent_submission_keys_are_bounded_redacted_and_tenant_scoped() {
944        let key = AgentSubmissionKey::new("request_01K4Z8Q6QH7W5X3M2N1P").unwrap();
945        assert_eq!(
946            from_str::<AgentSubmissionKey>(&to_string(&key).unwrap()).unwrap(),
947            key
948        );
949        let debug = format!("{key:?}");
950        assert!(!debug.contains(key.as_str()));
951        assert!(debug.contains("byte_length"));
952
953        let first = TenantId::new("tenant-a").unwrap();
954        let second = TenantId::new("tenant-b").unwrap();
955        assert_eq!(key.digest_for(&first), key.digest_for(&first));
956        assert_ne!(key.digest_for(&first), key.digest_for(&second));
957
958        let generated = AgentSubmissionKey::generate();
959        assert_eq!(generated.as_str().len(), 73);
960        let generated_parts = generated.as_str().split('.').collect::<Vec<_>>();
961        assert_eq!(generated_parts.len(), 2);
962        for part in generated_parts {
963            assert_eq!(
964                part.parse::<Uuid>().unwrap().get_version(),
965                Some(Version::SortRand)
966            );
967        }
968        assert!(AgentSubmissionKey::new("too-short").is_err());
969        assert!(AgentSubmissionKey::new("x".repeat(AgentSubmissionKey::MAX_LEN + 1)).is_err());
970        assert!(AgentSubmissionKey::new("request key with spaces").is_err());
971    }
972
973    #[test]
974    fn agent_submission_key_schema_matches_runtime_grammar() {
975        let schema = serde_json::to_value(schemars::schema_for!(AgentSubmissionKey)).unwrap();
976        assert_eq!(schema["type"], "string");
977        assert_eq!(schema["minLength"], AgentSubmissionKey::MIN_LEN);
978        assert_eq!(schema["maxLength"], AgentSubmissionKey::MAX_LEN);
979        assert_eq!(schema["pattern"], "^[A-Za-z0-9._~-]{16,128}$");
980    }
981
982    #[test]
983    fn generated_ids_are_canonical_uuid_v7_values() {
984        macro_rules! assert_id {
985            ($id_type:ty) => {{
986                let id = <$id_type>::generate();
987                assert_eq!(id.as_uuid().get_version(), Some(Version::SortRand));
988                assert_eq!(id.as_uuid().get_variant(), Variant::RFC4122);
989
990                let text = id.to_string();
991                assert_eq!(text.len(), 36);
992                assert_eq!(text, text.to_ascii_lowercase());
993                assert_eq!(text.parse::<$id_type>().unwrap(), id);
994            }};
995        }
996
997        assert_id!(RunId);
998        assert_id!(ThreadId);
999        assert_id!(EventId);
1000        assert_id!(FailureId);
1001        assert_id!(MessageId);
1002        assert_id!(ArtifactId);
1003        assert_id!(AuthorizationReceiptId);
1004        assert_id!(SkillActivationApprovalId);
1005        assert_id!(SkillActingWindowId);
1006        assert_id!(InvocationId);
1007        assert_id!(InterruptId);
1008        assert_id!(TimerId);
1009        assert_id!(DeliveryId);
1010        assert_id!(DestinationId);
1011        assert_id!(CheckpointId);
1012        assert_id!(QuarantineId);
1013        assert_id!(AttemptId);
1014        assert_id!(SchedulerReservationId);
1015    }
1016
1017    #[test]
1018    fn generated_ids_reject_noncanonical_and_non_v7_values() {
1019        let id = RunId::generate();
1020        let canonical = id.to_string();
1021
1022        assert_eq!(
1023            canonical.to_ascii_uppercase().parse::<RunId>(),
1024            Err(GeneratedIdError::NonCanonical)
1025        );
1026        assert_eq!(
1027            canonical.replace('-', "").parse::<RunId>(),
1028            Err(GeneratedIdError::NonCanonical)
1029        );
1030        assert_eq!(
1031            "not-a-uuid".parse::<RunId>(),
1032            Err(GeneratedIdError::InvalidUuid)
1033        );
1034        assert_eq!(
1035            "550e8400-e29b-41d4-a716-446655440000".parse::<RunId>(),
1036            Err(GeneratedIdError::WrongVersion)
1037        );
1038
1039        let mut wrong_variant_bytes = *id.as_uuid().as_bytes();
1040        wrong_variant_bytes[8] &= 0b0011_1111;
1041        let wrong_variant = Uuid::from_bytes(wrong_variant_bytes);
1042        assert_eq!(
1043            RunId::from_uuid(wrong_variant),
1044            Err(GeneratedIdError::WrongVariant)
1045        );
1046    }
1047
1048    #[test]
1049    fn generated_id_serde_uses_and_enforces_canonical_text() {
1050        let id = InvocationId::generate();
1051        let encoded = to_string(&id).unwrap();
1052        assert_eq!(encoded, format!("\"{id}\""));
1053        assert_eq!(from_str::<InvocationId>(&encoded).unwrap(), id);
1054
1055        let uppercase = Value::String(id.to_string().to_ascii_uppercase());
1056        assert!(from_value::<InvocationId>(uppercase).is_err());
1057        assert!(from_value::<InvocationId>(Value::Null).is_err());
1058    }
1059
1060    #[test]
1061    fn generated_id_schema_requires_canonical_uuid_v7_text() {
1062        let schema = serde_json::to_value(schemars::schema_for!(RunId)).unwrap();
1063        assert_eq!(schema["type"], "string");
1064        assert_eq!(schema["format"], "uuid");
1065        assert_eq!(schema["minLength"], 36);
1066        assert_eq!(schema["maxLength"], 36);
1067        assert_eq!(schema["pattern"], UUID_V7_PATTERN);
1068    }
1069}