1use 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum SessionStatus {
35 Open,
36 Closed,
37 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 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#[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 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 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 #[serde(default)]
142 pub created_after_ms: Option<i64>,
143 #[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 #[serde(default)]
156 pub from_event_id: Option<EventId>,
157 #[serde(default)]
159 pub to_event_id: Option<EventId>,
160 #[serde(default)]
164 pub limit: Option<usize>,
165}
166
167#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169pub struct EventPage {
170 pub events: Vec<StoredEvent>,
171 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#[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
231pub const MAX_READ_BATCH: usize = 1_000;
234
235#[derive(Default, Clone)]
239pub struct StoreHooks {
240 pub redaction: Option<SharedEventRedactor>,
243 pub event_signer: Option<SessionSigner>,
247 pub receipt_signer: Option<SessionSigner>,
251 pub retention: RetentionPolicy,
254 pub archive_sink: Option<SharedArchiveSink>,
259}
260
261#[async_trait]
262pub trait SessionStore: Send + Sync {
263 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 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#[async_trait]
361pub trait SessionImporter: SessionStore {
362 async fn import(&self, request: ImportSession) -> StoreResult<ImportResult>;
363}
364
365async 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 pub archived: usize,
402 pub tombstoned: usize,
405}
406
407pub type SharedSessionStore = Arc<dyn SessionStore>;