Skip to main content

adk_core/subject/
registry.rs

1//! The subject registry: pseudonyms, links, and erasure state.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use crate::principal::{SubjectKind, SubjectRef};
11use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
12
13/// The prefix of every pseudonym a registry issues.
14pub const PSEUDONYM_PREFIX: &str = "psn:";
15
16/// The error code of a write, link, or grant refused because the subject is being erased.
17pub const SUBJECT_ERASING_CODE: &str = "subject.erasing";
18
19/// The error code of a link refused because the visitor id is already linked.
20pub const SUBJECT_LINK_CONSUMED_CODE: &str = "subject.link.consumed";
21
22/// The error code of a link between subjects of the wrong kinds.
23pub const SUBJECT_LINK_INVALID_CODE: &str = "subject.link.invalid";
24
25/// Returns a new random pseudonym: [`PSEUDONYM_PREFIX`] and 32 hex characters.
26///
27/// # Example
28///
29/// ```rust
30/// use adk_core::subject::new_pseudonym;
31///
32/// assert!(new_pseudonym().starts_with("psn:"));
33/// assert_ne!(new_pseudonym(), new_pseudonym());
34/// ```
35pub fn new_pseudonym() -> String {
36    format!("{PSEUDONYM_PREFIX}{}", uuid::Uuid::new_v4().simple())
37}
38
39/// The error returned for an action on a subject that is being erased.
40pub fn erasing_error(subject: &SubjectRef) -> AdkError {
41    AdkError::new(
42        ErrorComponent::Auth,
43        ErrorCategory::Conflict,
44        SUBJECT_ERASING_CODE,
45        format!(
46            "{} is being erased, so nothing is written for it; finish the erasure with \
47             SubjectRights::erase before acting for this subject again",
48            subject.kind
49        ),
50    )
51}
52
53/// The error a [`SubjectRegistry`] returns when a visitor id is linked a second time.
54pub fn link_consumed_error() -> AdkError {
55    AdkError::new(
56        ErrorComponent::Auth,
57        ErrorCategory::Conflict,
58        SUBJECT_LINK_CONSUMED_CODE,
59        "this visitor id is already linked; a visitor id links once, so issue a new one",
60    )
61}
62
63/// The error a [`SubjectRegistry`] returns when a link names subjects of the wrong kinds.
64pub fn link_invalid_error(visitor: &SubjectRef, identified: &SubjectRef) -> AdkError {
65    AdkError::new(
66        ErrorComponent::Auth,
67        ErrorCategory::InvalidInput,
68        SUBJECT_LINK_INVALID_CODE,
69        format!(
70            "a link joins a visitor to an identified subject; got a {} and a {}",
71            visitor.kind, identified.kind
72        ),
73    )
74}
75
76/// Where a subject stands in the registry.
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79#[non_exhaustive]
80pub enum SubjectState {
81    /// Data may be written for the subject, subject to consent.
82    #[default]
83    Active,
84    /// An erasure has started and not completed: nothing is written for the subject.
85    Erasing,
86}
87
88/// What a registry holds about one subject. Never the subject's data.
89///
90/// # Example
91///
92/// ```rust
93/// use adk_core::principal::SubjectRef;
94/// use adk_core::subject::{SubjectRegistry, InMemorySubjectRegistry, SubjectState};
95///
96/// # async fn demo() -> adk_core::Result<()> {
97/// let registry = InMemorySubjectRegistry::new();
98/// let record = registry.ensure(&SubjectRef::human("alice")).await?;
99/// assert!(record.pseudonym.starts_with("psn:"));
100/// assert_eq!(record.state, SubjectState::Active);
101/// # Ok(())
102/// # }
103/// ```
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "camelCase")]
106pub struct SubjectRecord {
107    /// The subject.
108    pub subject: SubjectRef,
109    /// The random name audit records and telemetry use for the subject. Erasing the
110    /// subject deletes it, so records that carry it no longer lead back to the subject.
111    pub pseudonym: String,
112    /// Whether the subject is being erased.
113    pub state: SubjectState,
114    /// The identified subject this visitor id is linked to.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub linked_to: Option<SubjectRef>,
117    /// When the link was made.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub linked_at: Option<DateTime<Utc>>,
120    /// When the subject was registered.
121    pub created_at: DateTime<Utc>,
122}
123
124impl SubjectRecord {
125    /// A new active record for `subject` with a fresh pseudonym, registered at `at`.
126    pub fn new(subject: SubjectRef, at: DateTime<Utc>) -> Self {
127        Self {
128            subject,
129            pseudonym: new_pseudonym(),
130            state: SubjectState::Active,
131            linked_to: None,
132            linked_at: None,
133            created_at: at,
134        }
135    }
136}
137
138/// Each subject's pseudonym, links, and erasure state.
139///
140/// The registry holds no index of a subject's records: stores find a subject by its id.
141/// Its guarantees, checked by `adk_core::subject_registry_conformance_tests!` (feature
142/// `conformance`):
143///
144/// - [`ensure`](Self::ensure) registers a subject once; concurrent calls return one
145///   pseudonym.
146/// - A visitor id links to one identified subject, once ([`SUBJECT_LINK_CONSUMED_CODE`]).
147/// - [`remove`](Self::remove) forgets the subject, its pseudonym, and its link.
148///
149/// [`InMemorySubjectRegistry`] is the reference implementation; `adk-session` ships the
150/// durable ones.
151#[async_trait]
152pub trait SubjectRegistry: Send + Sync {
153    /// Returns the record of `subject`; `None` when it was never registered or was removed.
154    async fn get(&self, subject: &SubjectRef) -> Result<Option<SubjectRecord>>;
155
156    /// Returns the record of `subject`, registering it with a fresh pseudonym when it has
157    /// none.
158    async fn ensure(&self, subject: &SubjectRef) -> Result<SubjectRecord>;
159
160    /// Returns the subject `pseudonym` stands for.
161    async fn by_pseudonym(&self, pseudonym: &str) -> Result<Option<SubjectRef>>;
162
163    /// Links the visitor id `visitor` to `identified`, registering both, and returns the
164    /// visitor's record.
165    ///
166    /// # Errors
167    ///
168    /// - [`SUBJECT_LINK_INVALID_CODE`] unless `visitor` is a
169    ///   [`Visitor`](SubjectKind::Visitor) and `identified` is not.
170    /// - [`SUBJECT_LINK_CONSUMED_CODE`] when `visitor` is already linked, to anyone.
171    /// - [`SUBJECT_ERASING_CODE`] when either subject is being erased.
172    async fn link(&self, visitor: &SubjectRef, identified: &SubjectRef) -> Result<SubjectRecord>;
173
174    /// Returns the visitor ids linked to `identified`.
175    async fn linked(&self, identified: &SubjectRef) -> Result<Vec<SubjectRef>>;
176
177    /// Sets the state of `subject`, registering it when absent, and returns its record.
178    async fn set_state(&self, subject: &SubjectRef, state: SubjectState) -> Result<SubjectRecord>;
179
180    /// Forgets `subject`: its record, its pseudonym, and its link. Returns whether it was
181    /// registered.
182    async fn remove(&self, subject: &SubjectRef) -> Result<bool>;
183}
184
185/// Checks a link's kinds; every backend calls this before writing, so all of them refuse
186/// the same links.
187///
188/// # Errors
189///
190/// [`SUBJECT_LINK_INVALID_CODE`] unless `visitor` is a visitor and `identified` is not.
191pub fn validate_link(visitor: &SubjectRef, identified: &SubjectRef) -> Result<()> {
192    if visitor.kind == SubjectKind::Visitor && identified.kind != SubjectKind::Visitor {
193        Ok(())
194    } else {
195        Err(link_invalid_error(visitor, identified))
196    }
197}
198
199/// In-memory [`SubjectRegistry`] for tests and single-process development.
200///
201/// Clones share the same records.
202#[derive(Debug, Clone)]
203pub struct InMemorySubjectRegistry {
204    records: Arc<tokio::sync::RwLock<HashMap<SubjectRef, SubjectRecord>>>,
205    clock: Arc<dyn Clock>,
206}
207
208impl Default for InMemorySubjectRegistry {
209    fn default() -> Self {
210        Self { records: Arc::default(), clock: Arc::new(SystemClock) }
211    }
212}
213
214impl InMemorySubjectRegistry {
215    /// Creates an empty registry.
216    pub fn new() -> Self {
217        Self::default()
218    }
219
220    /// Sets the clock that stamps registration and link times.
221    #[must_use]
222    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
223        self.clock = clock;
224        self
225    }
226}
227
228#[async_trait]
229impl SubjectRegistry for InMemorySubjectRegistry {
230    async fn get(&self, subject: &SubjectRef) -> Result<Option<SubjectRecord>> {
231        Ok(self.records.read().await.get(subject).cloned())
232    }
233
234    async fn ensure(&self, subject: &SubjectRef) -> Result<SubjectRecord> {
235        let now = self.clock.now();
236        let mut records = self.records.write().await;
237        Ok(records
238            .entry(subject.clone())
239            .or_insert_with(|| SubjectRecord::new(subject.clone(), now))
240            .clone())
241    }
242
243    async fn by_pseudonym(&self, pseudonym: &str) -> Result<Option<SubjectRef>> {
244        Ok(self
245            .records
246            .read()
247            .await
248            .values()
249            .find(|record| record.pseudonym == pseudonym)
250            .map(|record| record.subject.clone()))
251    }
252
253    async fn link(&self, visitor: &SubjectRef, identified: &SubjectRef) -> Result<SubjectRecord> {
254        validate_link(visitor, identified)?;
255        let now = self.clock.now();
256        let mut records = self.records.write().await;
257        for subject in [visitor, identified] {
258            if records.get(subject).is_some_and(|record| record.state == SubjectState::Erasing) {
259                return Err(erasing_error(subject));
260            }
261        }
262        if records.get(visitor).is_some_and(|record| record.linked_to.is_some()) {
263            return Err(link_consumed_error());
264        }
265        records
266            .entry(identified.clone())
267            .or_insert_with(|| SubjectRecord::new(identified.clone(), now));
268        let record = records
269            .entry(visitor.clone())
270            .or_insert_with(|| SubjectRecord::new(visitor.clone(), now));
271        record.linked_to = Some(identified.clone());
272        record.linked_at = Some(now);
273        Ok(record.clone())
274    }
275
276    async fn linked(&self, identified: &SubjectRef) -> Result<Vec<SubjectRef>> {
277        let mut linked: Vec<SubjectRef> = self
278            .records
279            .read()
280            .await
281            .values()
282            .filter(|record| record.linked_to.as_ref() == Some(identified))
283            .map(|record| record.subject.clone())
284            .collect();
285        linked.sort_by(|a, b| a.id.cmp(&b.id));
286        Ok(linked)
287    }
288
289    async fn set_state(&self, subject: &SubjectRef, state: SubjectState) -> Result<SubjectRecord> {
290        let now = self.clock.now();
291        let mut records = self.records.write().await;
292        let record = records
293            .entry(subject.clone())
294            .or_insert_with(|| SubjectRecord::new(subject.clone(), now));
295        record.state = state;
296        Ok(record.clone())
297    }
298
299    async fn remove(&self, subject: &SubjectRef) -> Result<bool> {
300        Ok(self.records.write().await.remove(subject).is_some())
301    }
302}