tea_kernel/id.rs
1use std::str::FromStr;
2
3use tea_policy::GrantId;
4use tea_protocol::{ApprovalId, EventId, MessageId, RecordId, RunId, ToolCallId, TurnId};
5use uuid::Uuid;
6
7use crate::{KernelError, KernelErrorCode};
8
9/// Replaceable source of typed `UUIDv7` runtime identities.
10///
11/// # Errors
12///
13/// Every method returns [`KernelErrorCode::IdExhausted`](crate::KernelErrorCode::IdExhausted)
14/// when the configured source cannot provide the requested identity.
15pub trait KernelIdSource: std::fmt::Debug + Send + Sync {
16 /// Produces a run ID.
17 ///
18 /// # Errors
19 ///
20 /// Returns an error when the ID source is exhausted.
21 fn next_run_id(&self) -> Result<RunId, KernelError>;
22 /// Produces a turn ID.
23 ///
24 /// # Errors
25 ///
26 /// Returns an error when the ID source is exhausted.
27 fn next_turn_id(&self) -> Result<TurnId, KernelError>;
28 /// Produces a canonical message ID.
29 ///
30 /// # Errors
31 ///
32 /// Returns an error when the ID source is exhausted.
33 fn next_message_id(&self) -> Result<MessageId, KernelError>;
34 /// Produces a canonical tool-call ID.
35 ///
36 /// # Errors
37 ///
38 /// Returns an error when the ID source is exhausted.
39 fn next_tool_call_id(&self) -> Result<ToolCallId, KernelError>;
40 /// Produces an approval ID.
41 ///
42 /// # Errors
43 ///
44 /// Returns an error when the ID source is exhausted.
45 fn next_approval_id(&self) -> Result<ApprovalId, KernelError>;
46 /// Produces a durable policy-grant ID.
47 ///
48 /// # Errors
49 ///
50 /// Returns an error when the ID source is exhausted.
51 fn next_grant_id(&self) -> Result<GrantId, KernelError>;
52 /// Produces an observable event ID.
53 ///
54 /// # Errors
55 ///
56 /// Returns an error when the ID source is exhausted.
57 fn next_event_id(&self) -> Result<EventId, KernelError>;
58 /// Produces a durable record ID.
59 ///
60 /// # Errors
61 ///
62 /// Returns an error when the ID source is exhausted.
63 fn next_record_id(&self) -> Result<RecordId, KernelError>;
64}
65
66/// Production `UUIDv7` identity source.
67#[derive(Debug, Clone, Copy, Default)]
68pub struct UuidV7KernelIdSource;
69
70macro_rules! next_id {
71 ($method:ident, $type:ty) => {
72 fn $method(&self) -> Result<$type, KernelError> {
73 <$type>::from_str(&Uuid::now_v7().hyphenated().to_string()).map_err(|_| {
74 KernelError::new(
75 KernelErrorCode::IdExhausted,
76 "UUIDv7 source produced an invalid protocol ID",
77 )
78 })
79 }
80 };
81}
82
83impl KernelIdSource for UuidV7KernelIdSource {
84 next_id!(next_run_id, RunId);
85 next_id!(next_turn_id, TurnId);
86 next_id!(next_message_id, MessageId);
87 next_id!(next_tool_call_id, ToolCallId);
88 next_id!(next_approval_id, ApprovalId);
89 next_id!(next_grant_id, GrantId);
90 next_id!(next_event_id, EventId);
91 next_id!(next_record_id, RecordId);
92}