Skip to main content

harn_session_store/
store.rs

1//! `SessionStore` trait + the shared types every backend speaks.
2
3use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8
9use super::event::{AppendEvent, EventId, StoredEvent};
10use super::redaction::SharedEventRedactor;
11use super::retention::{RetentionPolicy, SharedArchiveSink, Tombstone};
12use super::signing::SessionSigner;
13
14pub type SessionId = String;
15
16/// Result of a fork operation.
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18pub struct ForkResult {
19    pub child_session_id: SessionId,
20    pub forked_from_event_id: EventId,
21    pub copied_event_count: usize,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub struct TruncateResult {
26    pub kept_event_count: usize,
27    pub removed_event_count: usize,
28    pub new_tip_event_id: Option<EventId>,
29}
30
31/// Per-session retention/lifecycle state.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum SessionStatus {
35    Open,
36    Closed,
37    /// Soft-deleted; will become `HardDeleted` once the grace window
38    /// elapses (enforced by retention sweeps; see [`crate::retention`]).
39    SoftDeleted,
40    HardDeleted,
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct SessionMeta {
45    pub id: SessionId,
46    pub tenant_id: Option<String>,
47    pub persona: Option<String>,
48    pub parent_session_id: Option<SessionId>,
49    pub created_at_ms: i64,
50    pub created_at: String,
51    /// Last `append`/`fork` timestamp; refreshed on every mutation.
52    pub updated_at_ms: i64,
53    pub updated_at: String,
54    pub status: SessionStatus,
55    pub event_count: usize,
56    pub last_event_id: Option<EventId>,
57    pub chain_root_hash: Option<String>,
58    pub closed_at_ms: Option<i64>,
59    pub closed_at: Option<String>,
60    pub soft_deleted_at_ms: Option<i64>,
61    pub ttl_seconds: Option<u64>,
62    pub tags: Vec<String>,
63    pub attributes: BTreeMap<String, serde_json::Value>,
64}
65
66#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
67pub struct CreateSession {
68    #[serde(default)]
69    pub id: Option<SessionId>,
70    #[serde(default)]
71    pub tenant_id: Option<String>,
72    #[serde(default)]
73    pub persona: Option<String>,
74    #[serde(default)]
75    pub parent_session_id: Option<SessionId>,
76    #[serde(default)]
77    pub ttl_seconds: Option<u64>,
78    #[serde(default)]
79    pub tags: Vec<String>,
80    #[serde(default)]
81    pub attributes: BTreeMap<String, serde_json::Value>,
82}
83
84/// One atomic, idempotent import into a new canonical session.
85///
86/// `source_id` names the external source independently of the target session;
87/// its receipt survives session deletion so retired sources cannot resurrect
88/// data. Reusing a source id with a different digest is a conflict.
89#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ImportSession {
91    pub source_id: String,
92    pub source_digest: String,
93    pub session: CreateSession,
94    #[serde(default)]
95    pub events: Vec<AppendEvent>,
96}
97
98impl ImportSession {
99    /// Validate the backend-independent import contract.
100    pub fn validate(&self) -> StoreResult<()> {
101        if self.source_id.trim().is_empty() || self.source_digest.trim().is_empty() {
102            return Err(StoreError::InvalidInput(
103                "import source_id and source_digest must be non-empty".to_string(),
104            ));
105        }
106        if self
107            .session
108            .id
109            .as_deref()
110            .is_none_or(|session_id| session_id.trim().is_empty())
111        {
112            return Err(StoreError::InvalidInput(
113                "import session id must be explicit and non-empty".to_string(),
114            ));
115        }
116        Ok(())
117    }
118}
119
120#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
121pub struct ImportResult {
122    pub source_id: String,
123    pub source_digest: String,
124    pub session_id: SessionId,
125    pub event_count: usize,
126    /// True only for the call that committed the import.
127    pub imported: bool,
128}
129
130#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
131pub struct ListFilter {
132    #[serde(default)]
133    pub tenant_id: Option<String>,
134    #[serde(default)]
135    pub persona: Option<String>,
136    #[serde(default)]
137    pub status: Option<SessionStatus>,
138    #[serde(default)]
139    pub tag: Option<String>,
140    /// Inclusive lower bound on `created_at_ms`.
141    #[serde(default)]
142    pub created_after_ms: Option<i64>,
143    /// Inclusive upper bound on `created_at_ms`.
144    #[serde(default)]
145    pub created_before_ms: Option<i64>,
146    #[serde(default)]
147    pub limit: Option<usize>,
148    #[serde(default)]
149    pub cursor: Option<String>,
150}
151
152#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
153pub struct ReadRange {
154    /// Inclusive lower bound; `None` means start from the genesis event.
155    #[serde(default)]
156    pub from_event_id: Option<EventId>,
157    /// Inclusive upper bound; `None` means up to the latest event.
158    #[serde(default)]
159    pub to_event_id: Option<EventId>,
160    /// Maximum number of events to return. Capped at
161    /// [`MAX_READ_BATCH`] by the store; callers iterate by advancing
162    /// `from_event_id` on the returned cursor.
163    #[serde(default)]
164    pub limit: Option<usize>,
165}
166
167/// Page of events plus the cursor needed to continue reading.
168#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169pub struct EventPage {
170    pub events: Vec<StoredEvent>,
171    /// Inclusive `from_event_id` to pass into the next read to resume.
172    /// `None` when the requested range was fully drained.
173    pub next_cursor: Option<EventId>,
174}
175
176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177pub struct SnapshotId(pub String);
178
179#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
180pub struct Snapshot {
181    pub id: SnapshotId,
182    pub session: SessionMeta,
183    pub events: Vec<StoredEvent>,
184    pub captured_at_ms: i64,
185    pub captured_at: String,
186}
187
188#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
189pub struct VerifyReport {
190    pub session_id: SessionId,
191    pub chain_root_hash: String,
192    pub event_count: usize,
193    pub signed_event_count: usize,
194    pub failures: Vec<VerifyFailure>,
195}
196
197#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
198pub struct VerifyFailure {
199    pub event_id: EventId,
200    pub reason: String,
201}
202
203/// Errors returned by every backend.
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub enum StoreError {
206    NotFound(String),
207    AlreadyExists(String),
208    Conflict(String),
209    InvalidInput(String),
210    Tenant(String),
211    Backend(String),
212}
213
214impl std::fmt::Display for StoreError {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        match self {
217            Self::NotFound(message) => write!(f, "not found: {message}"),
218            Self::AlreadyExists(message) => write!(f, "already exists: {message}"),
219            Self::Conflict(message) => write!(f, "conflict: {message}"),
220            Self::InvalidInput(message) => write!(f, "invalid input: {message}"),
221            Self::Tenant(message) => write!(f, "tenant: {message}"),
222            Self::Backend(message) => write!(f, "backend error: {message}"),
223        }
224    }
225}
226
227impl std::error::Error for StoreError {}
228
229pub type StoreResult<T> = Result<T, StoreError>;
230
231/// Soft cap on a single page of events to keep response sizes bounded.
232/// Memory + sqlite backends apply this; callers iterate via cursors.
233pub const MAX_READ_BATCH: usize = 1_000;
234
235/// Optional processors a host can plug in. Mutation hooks run inline before
236/// persistence; redaction is also reapplied to public retrieval projections
237/// as defense in depth for older stored data.
238#[derive(Default, Clone)]
239pub struct StoreHooks {
240    /// Applied to event payloads and headers before persistence and again
241    /// when events are read, snapshotted, or replayed.
242    pub redaction: Option<SharedEventRedactor>,
243    /// If set, every event is signed at append time. Without a signer
244    /// only the `Receipt` event minted by [`SessionStore::close`] is
245    /// signed (which is enough to verify the chain end-to-end).
246    pub event_signer: Option<SessionSigner>,
247    /// Required to mint receipts on `close`. Without this, `close`
248    /// still finalises the chain root hash but emits an unsigned
249    /// `Receipt` event.
250    pub receipt_signer: Option<SessionSigner>,
251    /// Default retention policy applied to new sessions when their
252    /// meta does not override it.
253    pub retention: RetentionPolicy,
254    /// Optional durable archive destination. The default
255    /// [`SessionStore::sweep_retention`] writes archived sessions and
256    /// tombstones here before the rows leave primary storage; see
257    /// [`super::retention::ArchiveSink`].
258    pub archive_sink: Option<SharedArchiveSink>,
259}
260
261#[async_trait]
262pub trait SessionStore: Send + Sync {
263    /// Plug-in processors configured for this store. The default
264    /// [`Self::sweep_retention`] reads `hooks.archive_sink` so the
265    /// retention loop can hand archived sessions to durable storage
266    /// without callers wiring the sink explicitly.
267    fn hooks(&self) -> &StoreHooks;
268
269    async fn create(&self, request: CreateSession) -> StoreResult<SessionMeta>;
270    async fn describe(&self, session_id: &str) -> StoreResult<SessionMeta>;
271    async fn list(&self, filter: ListFilter) -> StoreResult<Vec<SessionMeta>>;
272    async fn append(&self, session_id: &str, event: AppendEvent) -> StoreResult<StoredEvent>;
273    async fn read(&self, session_id: &str, range: ReadRange) -> StoreResult<EventPage>;
274    async fn fork(
275        &self,
276        session_id: &str,
277        at_event_id: EventId,
278        child_id: Option<SessionId>,
279    ) -> StoreResult<ForkResult>;
280    async fn truncate(&self, session_id: &str, at_event_id: EventId)
281        -> StoreResult<TruncateResult>;
282    async fn snapshot(&self, session_id: &str) -> StoreResult<Snapshot>;
283    async fn replay(&self, snapshot_id: &SnapshotId) -> StoreResult<Snapshot>;
284    async fn close(&self, session_id: &str) -> StoreResult<StoredEvent>;
285    async fn soft_delete(&self, session_id: &str) -> StoreResult<SessionMeta>;
286    async fn hard_delete(&self, session_id: &str) -> StoreResult<()>;
287    async fn verify(&self, session_id: &str) -> StoreResult<VerifyReport>;
288
289    /// Sweep retention. Backends with native scheduling can override
290    /// to skip the default loop; the default sweeps all sessions
291    /// against the configured [`RetentionPolicy`] and routes archived
292    /// sessions + tombstones through `hooks().archive_sink` when set.
293    async fn sweep_retention(
294        &self,
295        policy: &RetentionPolicy,
296        now_ms: i64,
297    ) -> StoreResult<SweepReport> {
298        use tracing::Instrument as _;
299        let span = tracing::info_span!(
300            "harn.session.sweep_retention",
301            harn.session.sweep.archive_sink_configured = self.hooks().archive_sink.is_some(),
302            harn.session.sweep.archived = tracing::field::Empty,
303            harn.session.sweep.soft_deleted = tracing::field::Empty,
304            harn.session.sweep.hard_deleted = tracing::field::Empty,
305        );
306        let span_for_record = span.clone();
307        let sink = self.hooks().archive_sink.clone();
308        let result = async move {
309            let mut report = SweepReport::default();
310            let sessions = self.list(ListFilter::default()).await?;
311            for session in sessions {
312                if policy.should_hard_delete(&session, now_ms) {
313                    if let Some(sink) = sink.as_ref() {
314                        let tombstone = Tombstone {
315                            session_id: session.id.clone(),
316                            tenant_id: session.tenant_id.clone(),
317                            deleted_at_ms: now_ms,
318                            deleted_at: super::event::ms_to_rfc3339(now_ms),
319                            final_chain_root_hash: session.chain_root_hash.clone(),
320                            final_event_id: session.last_event_id,
321                        };
322                        sink.tombstone(&tombstone).await?;
323                        report.tombstoned += 1;
324                    }
325                    self.hard_delete(&session.id).await?;
326                    report.hard_deleted += 1;
327                } else if policy.should_soft_delete(&session, now_ms) {
328                    if policy.should_archive(&session, now_ms) {
329                        if let Some(sink) = sink.as_ref() {
330                            let events = read_all_events(self, &session.id).await?;
331                            sink.archive(&session, &events).await?;
332                            report.archived += 1;
333                        }
334                    }
335                    self.soft_delete(&session.id).await?;
336                    report.soft_deleted += 1;
337                }
338            }
339            Ok::<_, StoreError>(report)
340        }
341        .instrument(span)
342        .await?;
343        span_for_record.record("harn.session.sweep.archived", result.archived as i64);
344        span_for_record.record(
345            "harn.session.sweep.soft_deleted",
346            result.soft_deleted as i64,
347        );
348        span_for_record.record(
349            "harn.session.sweep.hard_deleted",
350            result.hard_deleted as i64,
351        );
352        Ok(result)
353    }
354}
355
356/// Atomic, idempotent ingestion for stores that accept external session data.
357///
358/// This remains separate from [`SessionStore`] so downstream backends do not
359/// need to implement migration semantics unless they expose import support.
360#[async_trait]
361pub trait SessionImporter: SessionStore {
362    async fn import(&self, request: ImportSession) -> StoreResult<ImportResult>;
363}
364
365/// Drain every event for a session via repeated paginated reads. Used
366/// by [`SessionStore::sweep_retention`] when shipping a session to the
367/// [`super::retention::ArchiveSink`].
368async fn read_all_events<S: SessionStore + ?Sized>(
369    store: &S,
370    session_id: &str,
371) -> StoreResult<Vec<StoredEvent>> {
372    let mut all = Vec::new();
373    let mut cursor: Option<EventId> = None;
374    loop {
375        let page = store
376            .read(
377                session_id,
378                ReadRange {
379                    from_event_id: cursor,
380                    to_event_id: None,
381                    limit: Some(MAX_READ_BATCH),
382                },
383            )
384            .await?;
385        let next = page.next_cursor;
386        all.extend(page.events);
387        match next {
388            Some(next_cursor) => cursor = Some(next_cursor),
389            None => break,
390        }
391    }
392    Ok(all)
393}
394
395#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
396pub struct SweepReport {
397    pub soft_deleted: usize,
398    pub hard_deleted: usize,
399    /// Sessions handed to [`super::retention::ArchiveSink::archive`]
400    /// because they crossed `min_age_before_archive_seconds`.
401    pub archived: usize,
402    /// Hard-deleted sessions whose final state was emitted as a
403    /// [`super::retention::Tombstone`] to the archive sink.
404    pub tombstoned: usize,
405}
406
407/// Dyn-dispatch alias so adapters can keep one `Arc<dyn SessionStore>`
408/// in their state without naming the concrete backend everywhere.
409pub type SharedSessionStore = Arc<dyn SessionStore>;