Skip to main content

adk_core/subject/
rights.rs

1//! Store adapters and the `SubjectRights` orchestrator.
2
3use std::collections::BTreeSet;
4use std::sync::Arc;
5use std::time::Duration;
6
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, json};
11
12use super::SubjectScope;
13use super::consent::{ConsentPurpose, ConsentRecord, ConsentStore};
14use super::registry::{SubjectRecord, SubjectRegistry, SubjectState, erasing_error};
15use crate::audit_log::{
16    AuditActor, AuditRecordDraft, AuditRecordKind, AuditRecordOutcome, AuditTrail,
17};
18use crate::principal::SubjectRef;
19use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
20
21/// The error code a [`SubjectDataStore`] returns from an operation it cannot perform.
22pub const SUBJECT_UNSUPPORTED_CODE: &str = "subject.unsupported";
23
24/// The error a [`SubjectDataStore`] returns from an operation it cannot perform, such as
25/// exporting from a store with no way to list a user's records.
26///
27/// # Example
28///
29/// ```rust
30/// use adk_core::subject::{SUBJECT_UNSUPPORTED_CODE, unsupported_error};
31///
32/// assert_eq!(unsupported_error("vertex-rag", "export").code, SUBJECT_UNSUPPORTED_CODE);
33/// ```
34pub fn unsupported_error(store: &str, operation: &str) -> AdkError {
35    AdkError::new(
36        ErrorComponent::Auth,
37        ErrorCategory::Unsupported,
38        SUBJECT_UNSUPPORTED_CODE,
39        format!("the '{store}' store cannot {operation} by subject"),
40    )
41}
42
43/// How a [`SubjectDataStore`] erases.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase", tag = "kind")]
46#[non_exhaustive]
47pub enum StoreSupport {
48    /// The data is gone when `erase` returns.
49    Hard,
50    /// `erase` starts a deletion that completes asynchronously, within `within`, such as
51    /// a managed service's long-running delete.
52    Eventual {
53        /// The longest the deletion takes.
54        #[serde(rename = "withinSecs", with = "duration_secs")]
55        within: Duration,
56    },
57    /// The store holds the subject's data but cannot find or delete it by subject.
58    Unsupported,
59    /// The data is held outside the deployment's reach, such as by a model provider or an
60    /// external telemetry collector; the report names the store so the deployment can act
61    /// there.
62    Unreachable,
63}
64
65mod duration_secs {
66    use std::time::Duration;
67
68    use serde::{Deserialize, Deserializer, Serializer};
69
70    pub fn serialize<S: Serializer>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
71        serializer.serialize_u64(value.as_secs())
72    }
73
74    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
75        u64::deserialize(deserializer).map(Duration::from_secs)
76    }
77}
78
79/// What one store's erasure did.
80///
81/// # Example
82///
83/// ```rust
84/// use adk_core::subject::StoreErasure;
85///
86/// assert_eq!(StoreErasure::deleted(3), StoreErasure { deleted: 3, retained: 0, completes_by: None });
87/// ```
88#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct StoreErasure {
91    /// Items deleted.
92    pub deleted: u64,
93    /// Items the store keeps by design after erasure, such as noncurrent object versions
94    /// under a retention policy. The report lists them; they are never silently counted
95    /// as deleted.
96    pub retained: u64,
97    /// When an asynchronous deletion completes.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub completes_by: Option<DateTime<Utc>>,
100}
101
102impl StoreErasure {
103    /// `count` items deleted, none retained, done.
104    pub fn deleted(count: u64) -> Self {
105        Self { deleted: count, retained: 0, completes_by: None }
106    }
107}
108
109/// One store family's adapter for subject rights: exports and erases what the store holds
110/// about a [`SubjectScope`].
111///
112/// A store keyed by `(app, user)` looks the subject up under every
113/// [user id](SubjectScope::user_ids) in every [application](SubjectScope::app_names) of the
114/// scope. Every adapter passes `adk_core::subject_data_store_conformance_tests!` (feature
115/// `conformance`): after a completed erasure no read path of the store returns the subject's
116/// data, other subjects' data is untouched, and a repeat deletes nothing.
117///
118/// # Example
119///
120/// ```rust
121/// use adk_core::subject::{StoreErasure, SubjectDataStore, SubjectScope};
122/// use adk_core::{Result, async_trait};
123/// use serde_json::{Value, json};
124///
125/// struct Newsletter;
126///
127/// #[async_trait]
128/// impl SubjectDataStore for Newsletter {
129///     fn name(&self) -> &str {
130///         "newsletter"
131///     }
132///
133///     async fn export(&self, scope: &SubjectScope) -> Result<Value> {
134///         Ok(json!({ "subscriptions": [] }))
135///     }
136///
137///     async fn erase(&self, scope: &SubjectScope) -> Result<StoreErasure> {
138///         Ok(StoreErasure::deleted(0))
139///     }
140/// }
141/// ```
142#[async_trait]
143pub trait SubjectDataStore: Send + Sync {
144    /// The store's name in reports, such as `sessions` or `memory`.
145    fn name(&self) -> &str;
146
147    /// How the store erases. [`StoreSupport::Hard`] by default.
148    fn support(&self) -> StoreSupport {
149        StoreSupport::Hard
150    }
151
152    /// Every item the store holds about the scope, as JSON. An empty array, an empty
153    /// object, or `null` means the store holds nothing.
154    ///
155    /// # Errors
156    ///
157    /// [`SUBJECT_UNSUPPORTED_CODE`] when the store cannot list by subject; any other error
158    /// when reading fails.
159    async fn export(&self, scope: &SubjectScope) -> Result<Value>;
160
161    /// Erases every item the store holds about the scope.
162    ///
163    /// Called only when [`support`](Self::support) is `Hard` or `Eventual`. A repeat
164    /// deletes nothing and succeeds.
165    ///
166    /// # Errors
167    ///
168    /// Returns an error when deleting fails; the subject stays
169    /// [`Erasing`](SubjectState::Erasing) so a repeat can finish.
170    async fn erase(&self, scope: &SubjectScope) -> Result<StoreErasure>;
171}
172
173/// What happened in one store during an erasure.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "camelCase", tag = "status")]
176#[non_exhaustive]
177pub enum StoreOutcome {
178    /// The data is gone.
179    #[serde(rename_all = "camelCase")]
180    Erased {
181        /// Items deleted.
182        deleted: u64,
183        /// Items kept by design.
184        retained: u64,
185    },
186    /// The deletion was accepted and completes by `completes_by`.
187    #[serde(rename_all = "camelCase")]
188    Scheduled {
189        /// Items whose deletion was accepted.
190        deleted: u64,
191        /// Items kept by design.
192        retained: u64,
193        /// When the deletion completes.
194        completes_by: DateTime<Utc>,
195    },
196    /// The store cannot erase by subject; its data remains.
197    Unsupported,
198    /// The data is outside the deployment's reach.
199    Unreachable,
200    /// Deleting failed; a repeat retries it.
201    #[serde(rename_all = "camelCase")]
202    Failed {
203        /// The error code.
204        code: String,
205        /// The error message.
206        message: String,
207    },
208}
209
210impl StoreOutcome {
211    /// Whether the store's part of the erasure is done or under way.
212    pub fn is_done(&self) -> bool {
213        match self {
214            Self::Erased { .. } | Self::Scheduled { .. } => true,
215            Self::Unsupported | Self::Unreachable | Self::Failed { .. } => false,
216        }
217    }
218}
219
220/// One store's line in an [`ErasureReport`].
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "camelCase")]
223pub struct StoreReport {
224    /// The store's name.
225    pub store: String,
226    /// What happened there.
227    #[serde(flatten)]
228    pub outcome: StoreOutcome,
229}
230
231/// Whether an erasure reached every store.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "camelCase")]
234#[non_exhaustive]
235pub enum ErasureStatus {
236    /// Every store erased the subject's data or accepted its deletion.
237    Completed,
238    /// At least one store is unsupported, unreachable, or failed; its data may remain.
239    Partial,
240}
241
242/// The result of [`SubjectRights::erase`]. Names no subject, so it may be kept or logged.
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244#[serde(rename_all = "camelCase")]
245pub struct ErasureReport {
246    /// Whether every store was reached.
247    pub status: ErasureStatus,
248    /// How many subject ids were erased: the subject and its linked visitor ids.
249    pub subjects: u64,
250    /// One line per store, the consent store last.
251    pub stores: Vec<StoreReport>,
252    /// The latest time an asynchronous deletion completes.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub completes_by: Option<DateTime<Utc>>,
255    /// When the erasure ran.
256    pub erased_at: DateTime<Utc>,
257}
258
259impl ErasureReport {
260    /// Whether a store failed, so a repeat can finish the erasure. The subject stays
261    /// [`Erasing`](SubjectState::Erasing) until one succeeds.
262    pub fn failed(&self) -> bool {
263        self.stores.iter().any(|line| matches!(line.outcome, StoreOutcome::Failed { .. }))
264    }
265}
266
267/// What one store returned for an export.
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase", tag = "status")]
270#[non_exhaustive]
271pub enum ExportOutcome {
272    /// The store's data about the subject.
273    Exported {
274        /// The data.
275        data: Value,
276    },
277    /// The store cannot list by subject.
278    Unsupported,
279    /// The data is outside the deployment's reach.
280    Unreachable,
281    /// Reading failed.
282    Failed {
283        /// The error code.
284        code: String,
285        /// The error message.
286        message: String,
287    },
288}
289
290/// One store's part of a [`SubjectExport`].
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292#[serde(rename_all = "camelCase")]
293pub struct StoreExport {
294    /// The store's name.
295    pub store: String,
296    /// What it returned.
297    #[serde(flatten)]
298    pub outcome: ExportOutcome,
299}
300
301/// The result of [`SubjectRights::export`]: everything the deployment's registered stores
302/// hold about a subject and its linked visitor ids.
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
304#[serde(rename_all = "camelCase")]
305pub struct SubjectExport {
306    /// The subject.
307    pub subject: SubjectRef,
308    /// Its linked visitor ids.
309    #[serde(default, skip_serializing_if = "Vec::is_empty")]
310    pub linked: Vec<SubjectRef>,
311    /// The registry's records of the subject and its linked ids.
312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
313    pub registry: Vec<SubjectRecord>,
314    /// Every consent record of the subject and its linked ids.
315    #[serde(default, skip_serializing_if = "Vec::is_empty")]
316    pub consent: Vec<ConsentRecord>,
317    /// One entry per store.
318    pub stores: Vec<StoreExport>,
319    /// When the export ran.
320    pub exported_at: DateTime<Utc>,
321}
322
323impl SubjectExport {
324    /// Whether every store returned its data.
325    pub fn is_complete(&self) -> bool {
326        self.stores.iter().all(|entry| matches!(entry.outcome, ExportOutcome::Exported { .. }))
327    }
328}
329
330/// The result of [`SubjectRights::revoke`].
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333pub struct Revocation {
334    /// The records revoked.
335    pub revoked: Vec<ConsentRecord>,
336    /// The erasure that followed, when a revoked purpose erases the subject.
337    #[serde(default, skip_serializing_if = "Option::is_none")]
338    pub erasure: Option<ErasureReport>,
339}
340
341/// Exports, erases, and links a subject's data across the registry, the consent store,
342/// and every registered [`SubjectDataStore`].
343///
344/// Build one per deployment with the applications whose `(app, user)`-keyed stores it
345/// covers. `link` trusts its arguments: the caller proves the visitor id (its token) and
346/// a fresh authentication of the identified subject in the same request before calling it.
347///
348/// # Example
349///
350/// ```rust
351/// use std::sync::Arc;
352/// use adk_core::principal::SubjectRef;
353/// use adk_core::subject::{InMemoryConsentStore, InMemorySubjectRegistry, SubjectRights, VisitorId};
354///
355/// # async fn demo() -> adk_core::Result<()> {
356/// let rights = SubjectRights::new(
357///     Arc::new(InMemorySubjectRegistry::new()),
358///     Arc::new(InMemoryConsentStore::new()),
359/// )
360/// .with_app("shop");
361///
362/// let visitor = VisitorId::generate().subject();
363/// let alice = SubjectRef::human("alice");
364/// rights.link(&visitor, &alice).await?;
365///
366/// // Export and erasure of alice cover the visitor id.
367/// assert_eq!(rights.export(&alice).await?.linked, vec![visitor]);
368/// # Ok(())
369/// # }
370/// ```
371#[derive(Clone)]
372pub struct SubjectRights {
373    registry: Arc<dyn SubjectRegistry>,
374    consent: Arc<dyn ConsentStore>,
375    stores: Vec<Arc<dyn SubjectDataStore>>,
376    app_names: Vec<String>,
377    erase_on_revoke: BTreeSet<ConsentPurpose>,
378    audit: Option<AuditTrail>,
379    clock: Arc<dyn Clock>,
380}
381
382impl std::fmt::Debug for SubjectRights {
383    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384        f.debug_struct("SubjectRights")
385            .field("stores", &self.stores.iter().map(|store| store.name()).collect::<Vec<_>>())
386            .field("app_names", &self.app_names)
387            .field("erase_on_revoke", &self.erase_on_revoke)
388            .finish_non_exhaustive()
389    }
390}
391
392impl SubjectRights {
393    /// Rights over `registry` and `consent`, with no stores and no applications yet.
394    pub fn new(registry: Arc<dyn SubjectRegistry>, consent: Arc<dyn ConsentStore>) -> Self {
395        Self {
396            registry,
397            consent,
398            stores: Vec::new(),
399            app_names: Vec::new(),
400            erase_on_revoke: BTreeSet::new(),
401            audit: None,
402            clock: Arc::new(SystemClock),
403        }
404    }
405
406    /// Adds an application whose `(app, user)`-keyed stores are covered.
407    #[must_use]
408    pub fn with_app(mut self, app_name: impl Into<String>) -> Self {
409        self.app_names.push(app_name.into());
410        self
411    }
412
413    /// Adds a store.
414    #[must_use]
415    pub fn with_store(mut self, store: Arc<dyn SubjectDataStore>) -> Self {
416        self.stores.push(store);
417        self
418    }
419
420    /// Erases the subject when it revokes consent for `purpose`. Without this, revoking
421    /// stops later writes and erases nothing.
422    #[must_use]
423    pub fn with_erase_on_revoke(mut self, purpose: ConsentPurpose) -> Self {
424        self.erase_on_revoke.insert(purpose);
425        self
426    }
427
428    /// Records links and erasures in `audit`, naming subjects by pseudonym.
429    #[must_use]
430    pub fn with_audit(mut self, audit: AuditTrail) -> Self {
431        self.audit = Some(audit);
432        self
433    }
434
435    /// Sets the clock that stamps revocations and reports.
436    #[must_use]
437    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
438        self.clock = clock;
439        self
440    }
441
442    /// The registry.
443    pub fn registry(&self) -> &Arc<dyn SubjectRegistry> {
444        &self.registry
445    }
446
447    /// The consent store.
448    pub fn consent(&self) -> &Arc<dyn ConsentStore> {
449        &self.consent
450    }
451
452    /// The scope of `subject`: it, its linked visitor ids, and the covered applications.
453    ///
454    /// # Errors
455    ///
456    /// Returns a registry error.
457    pub async fn scope(&self, subject: &SubjectRef) -> Result<SubjectScope> {
458        Ok(SubjectScope::new(self.app_names.iter().cloned(), subject.clone())
459            .with_linked(self.registry.linked(subject).await?))
460    }
461
462    /// Fails with [`SUBJECT_ERASING_CODE`](super::SUBJECT_ERASING_CODE) when `subject` is
463    /// being erased. Consent gates call it before a lasting write.
464    ///
465    /// # Errors
466    ///
467    /// `subject.erasing`, or a registry error.
468    pub async fn ensure_writable(&self, subject: &SubjectRef) -> Result<()> {
469        match self.registry.get(subject).await? {
470            Some(record) if record.state == SubjectState::Erasing => Err(erasing_error(subject)),
471            Some(_) | None => Ok(()),
472        }
473    }
474
475    /// Records a grant of consent.
476    ///
477    /// # Errors
478    ///
479    /// `subject.erasing` while the subject is being erased; `consent.conflict` when the
480    /// record's id is taken; or a store error.
481    pub async fn grant(&self, record: ConsentRecord) -> Result<()> {
482        self.ensure_writable(&record.subject).await?;
483        self.consent.grant(record).await
484    }
485
486    /// Revokes the subject's live consent for `purpose`, or for every purpose when `None`.
487    /// When a revoked purpose is one passed to
488    /// [`with_erase_on_revoke`](Self::with_erase_on_revoke), the subject is erased as well.
489    ///
490    /// # Errors
491    ///
492    /// Returns a store error.
493    pub async fn revoke(
494        &self,
495        subject: &SubjectRef,
496        purpose: Option<&ConsentPurpose>,
497    ) -> Result<Revocation> {
498        let revoked = self.consent.revoke_purpose(subject, purpose, self.clock.now()).await?;
499        let erase = revoked.iter().any(|record| self.erase_on_revoke.contains(&record.purpose));
500        let erasure = if erase { Some(self.erase(subject).await?) } else { None };
501        Ok(Revocation { revoked, erasure })
502    }
503
504    /// Links the visitor id `visitor` to the identified subject `identified`: export and
505    /// erasure of `identified` cover `visitor` from then on. Data stays where it is.
506    ///
507    /// The caller has proved both in one request — the visitor's token and a fresh
508    /// authentication of `identified` — and rotates the visitor's token afterwards.
509    ///
510    /// # Errors
511    ///
512    /// `subject.link.invalid`, `subject.link.consumed`, or `subject.erasing`, as
513    /// [`SubjectRegistry::link`].
514    pub async fn link(
515        &self,
516        visitor: &SubjectRef,
517        identified: &SubjectRef,
518    ) -> Result<SubjectRecord> {
519        let record = self.registry.link(visitor, identified).await?;
520        if let Some(trail) = &self.audit {
521            let identified = self.registry.ensure(identified).await?;
522            let draft = AuditRecordDraft::new(AuditRecordKind::Authentication, "subject.link")
523                .actor(AuditActor::subject(SubjectRef::new(
524                    identified.subject.kind,
525                    identified.pseudonym,
526                )))
527                .outcome(AuditRecordOutcome::Succeeded)
528                .ext("visitor", Value::String(record.pseudonym.clone()));
529            trail.record(draft).await?;
530        }
531        Ok(record)
532    }
533
534    /// Everything the registered stores hold about `subject` and its linked visitor ids.
535    ///
536    /// A store that cannot export is reported, never left out.
537    ///
538    /// # Errors
539    ///
540    /// Returns a registry or consent store error; store errors are reported per store.
541    pub async fn export(&self, subject: &SubjectRef) -> Result<SubjectExport> {
542        let scope = self.scope(subject).await?;
543        let mut registry = Vec::new();
544        let mut consent = Vec::new();
545        for each in scope.subjects() {
546            registry.extend(self.registry.get(each).await?);
547            consent.extend(self.consent.for_subject(each).await?);
548        }
549        let mut stores = Vec::with_capacity(self.stores.len());
550        for store in &self.stores {
551            let outcome = match store.support() {
552                StoreSupport::Unreachable => ExportOutcome::Unreachable,
553                StoreSupport::Hard | StoreSupport::Eventual { .. } | StoreSupport::Unsupported => {
554                    match store.export(&scope).await {
555                        Ok(data) => ExportOutcome::Exported { data },
556                        Err(error) if error.code == SUBJECT_UNSUPPORTED_CODE => {
557                            ExportOutcome::Unsupported
558                        }
559                        Err(error) => {
560                            tracing::warn!(subject.store = store.name(), error = %error, "subject export failed");
561                            ExportOutcome::Failed {
562                                code: error.code.to_string(),
563                                message: error.message,
564                            }
565                        }
566                    }
567                }
568            };
569            stores.push(StoreExport { store: store.name().to_owned(), outcome });
570        }
571        Ok(SubjectExport {
572            subject: scope.subject,
573            linked: scope.linked,
574            registry,
575            consent,
576            stores,
577            exported_at: self.clock.now(),
578        })
579    }
580
581    /// Erases everything the registered stores hold about `subject` and its linked visitor
582    /// ids, in the order the [module documentation](super) gives.
583    ///
584    /// A repeat is safe: a completed erasure leaves nothing to find, and one with a failed
585    /// store resumes where it stopped.
586    ///
587    /// # Errors
588    ///
589    /// Returns a registry error or a consent store error from revocation; errors of
590    /// individual stores are reported per store.
591    pub async fn erase(&self, subject: &SubjectRef) -> Result<ErasureReport> {
592        let now = self.clock.now();
593        let pseudonym = self.registry.set_state(subject, SubjectState::Erasing).await?.pseudonym;
594        let scope = self.scope(subject).await?;
595        for linked in &scope.linked {
596            self.registry.set_state(linked, SubjectState::Erasing).await?;
597        }
598        for each in scope.subjects() {
599            self.consent.revoke_purpose(each, None, now).await?;
600        }
601
602        let mut lines = Vec::with_capacity(self.stores.len() + 1);
603        for store in &self.stores {
604            let outcome = match store.support() {
605                StoreSupport::Unsupported => StoreOutcome::Unsupported,
606                StoreSupport::Unreachable => StoreOutcome::Unreachable,
607                support @ (StoreSupport::Hard | StoreSupport::Eventual { .. }) => {
608                    match store.erase(&scope).await {
609                        Ok(erasure) => {
610                            let eventual = match support {
611                                StoreSupport::Eventual { within } => {
612                                    chrono::Duration::from_std(within)
613                                        .ok()
614                                        .map(|within| now + within)
615                                }
616                                StoreSupport::Hard
617                                | StoreSupport::Unsupported
618                                | StoreSupport::Unreachable => None,
619                            };
620                            match erasure.completes_by.or(eventual) {
621                                Some(completes_by) => StoreOutcome::Scheduled {
622                                    deleted: erasure.deleted,
623                                    retained: erasure.retained,
624                                    completes_by,
625                                },
626                                None => StoreOutcome::Erased {
627                                    deleted: erasure.deleted,
628                                    retained: erasure.retained,
629                                },
630                            }
631                        }
632                        Err(error) => {
633                            tracing::error!(subject.store = store.name(), error = %error, "subject erasure failed in a store");
634                            StoreOutcome::Failed {
635                                code: error.code.to_string(),
636                                message: error.message,
637                            }
638                        }
639                    }
640                }
641            };
642            lines.push(StoreReport { store: store.name().to_owned(), outcome });
643        }
644
645        let mut consent_erased = Ok(0);
646        for each in scope.subjects() {
647            consent_erased = match (consent_erased, self.consent.erase(each).await) {
648                (Ok(total), Ok(count)) => Ok(total + count),
649                (Err(error), _) | (Ok(_), Err(error)) => Err(error),
650            };
651        }
652        lines.push(StoreReport {
653            store: "consent".to_owned(),
654            outcome: match consent_erased {
655                Ok(deleted) => StoreOutcome::Erased { deleted, retained: 0 },
656                Err(error) => {
657                    StoreOutcome::Failed { code: error.code.to_string(), message: error.message }
658                }
659            },
660        });
661
662        let report = ErasureReport {
663            status: if lines.iter().all(|line| line.outcome.is_done()) {
664                ErasureStatus::Completed
665            } else {
666                ErasureStatus::Partial
667            },
668            subjects: scope.subjects().count() as u64,
669            completes_by: lines
670                .iter()
671                .filter_map(|line| match line.outcome {
672                    StoreOutcome::Scheduled { completes_by, .. } => Some(completes_by),
673                    StoreOutcome::Erased { .. }
674                    | StoreOutcome::Unsupported
675                    | StoreOutcome::Unreachable
676                    | StoreOutcome::Failed { .. } => None,
677                })
678                .max(),
679            stores: lines,
680            erased_at: now,
681        };
682
683        if let Some(trail) = &self.audit {
684            let draft = AuditRecordDraft::new(AuditRecordKind::Erasure, "subject.erase")
685                .actor(AuditActor::subject(SubjectRef::new(subject.kind, pseudonym)))
686                .outcome(if report.failed() {
687                    AuditRecordOutcome::Failed
688                } else {
689                    AuditRecordOutcome::Succeeded
690                })
691                .ext("subjects", Value::from(report.subjects))
692                .ext("stores", erasure_audit_lines(&report.stores));
693            if let Err(error) = trail.record(draft).await {
694                tracing::warn!(error = %error, "subject erasure ran but its audit record was not written");
695            }
696        }
697
698        if !report.failed() {
699            for each in scope.subjects() {
700                self.registry.remove(each).await?;
701            }
702        }
703        Ok(report)
704    }
705}
706
707/// The report's store lines without error messages, which may name the subject.
708fn erasure_audit_lines(lines: &[StoreReport]) -> Value {
709    Value::Array(
710        lines
711            .iter()
712            .map(|line| {
713                let mut value = json!(line);
714                if let Some(fields) = value.as_object_mut() {
715                    fields.remove("message");
716                }
717                value
718            })
719            .collect(),
720    )
721}