aion_store/store.rs
1//! Event-store traits and single-writer capability.
2
3use aion_core::{
4 Event, RunId, TimerId, WorkflowFilter, WorkflowId, WorkflowStatus, WorkflowSummary,
5};
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8
9use crate::{OutboxRow, StoreError, TimerEntry};
10
11mod write_capability {
12 /// Capability required to append workflow events.
13 ///
14 /// This token enforces Aion's single-writer durability invariant at the type level: only the
15 /// recorder append path may hold write authority for a workflow. `SequenceConflict` remains the
16 /// runtime defense-in-depth signal for any internal misuse or future bypass that attempts to
17 /// append with a stale head.
18 #[derive(Clone, Copy, Debug)]
19 pub struct WriteToken {
20 _private: (),
21 }
22
23 impl WriteToken {
24 /// Constructs a write token for Aion's recorder path.
25 #[must_use]
26 pub fn recorder() -> Self {
27 Self { _private: () }
28 }
29 }
30
31 pub(crate) fn conformance() -> WriteToken {
32 WriteToken { _private: () }
33 }
34}
35
36pub use write_capability::WriteToken;
37
38/// Summary of one concrete run in a workflow's continuation chain.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct RunSummary {
41 /// Concrete run identifier for this chain entry.
42 pub run_id: RunId,
43 /// Parent run that continued as this run, or `None` for the first run.
44 pub parent_run_id: Option<RunId>,
45 /// Status projected from this run's slice of lifecycle events.
46 pub status: WorkflowStatus,
47 /// Timestamp of this run's `WorkflowStarted` event.
48 pub started_at: DateTime<Utc>,
49 /// Timestamp of this run's terminal lifecycle event, when closed.
50 pub closed_at: Option<DateTime<Utc>>,
51}
52
53/// Read and durable-timer contract for Aion event stores.
54#[async_trait]
55pub trait ReadableEventStore: Send + Sync + 'static {
56 /// Reads the complete event history for `workflow_id` in ascending sequence order.
57 ///
58 /// A workflow with no recorded events is observed as an empty history. This includes unknown
59 /// workflow identifiers: because the first append with `expected_seq == 0` creates a workflow
60 /// implicitly, "unknown workflow" and "empty history" are the same observable state for reads.
61 /// This method must not return [`StoreError::NotFound`] for absent workflows.
62 async fn read_history(&self, workflow_id: &WorkflowId) -> Result<Vec<Event>, StoreError>;
63
64 /// Reads the event history for `workflow_id` restricted to events with sequence number
65 /// greater than or equal to `from_seq`, in ascending sequence order.
66 ///
67 /// This is the range-read primitive behind O(delta) WS resume: callers replaying from a
68 /// cursor must not pay for the full history. Semantics:
69 ///
70 /// - `from_seq <= 1` is equivalent to [`Self::read_history`]: sequence numbers start at 1,
71 /// so every recorded event satisfies the bound.
72 /// - `from_seq` beyond the current head returns an empty vector, never an error. Whether a
73 /// beyond-head cursor is *valid* is protocol judgment, not store judgment: the WS resume
74 /// protocol rejects `resume_from_seq > head + 1` as an invalid cursor
75 /// (`ResumeCursorAheadOfHistory`), but it makes that call by comparing the cursor against
76 /// the head it observes — the store only answers which events exist at or after the
77 /// requested sequence.
78 /// - Unknown workflows behave exactly like [`Self::read_history`] for unknown workflows:
79 /// empty history, never [`StoreError::NotFound`], because "unknown workflow" and "empty
80 /// history" are the same observable state for reads.
81 ///
82 /// There is deliberately no default implementation: a read-all-then-filter fallback would
83 /// silently reintroduce O(history) behavior. Every backend must implement this as a real
84 /// range read (for SQL backends, an indexed `seq >= ?` range scan).
85 async fn read_history_from(
86 &self,
87 workflow_id: &WorkflowId,
88 from_seq: u64,
89 ) -> Result<Vec<Event>, StoreError>;
90
91 /// Reads the concrete run chain for `workflow_id` in continuation order.
92 async fn read_run_chain(&self, workflow_id: &WorkflowId)
93 -> Result<Vec<RunSummary>, StoreError>;
94
95 /// Lists every workflow identifier that has at least one event in history.
96 ///
97 /// Unlike [`Self::list_active`], this includes terminal workflows and exists to let projection
98 /// repair jobs reconcile derived indexes against the authoritative event history.
99 async fn list_workflow_ids(&self) -> Result<Vec<WorkflowId>, StoreError>;
100
101 /// Lists workflow identifiers whose projected status is non-terminal.
102 async fn list_active(&self) -> Result<Vec<WorkflowId>, StoreError>;
103
104 /// Lists workflow identifiers whose projected status is exactly
105 /// [`WorkflowStatus::Paused`](aion_core::WorkflowStatus::Paused).
106 ///
107 /// Mirrors [`Self::list_active`] with a `== Paused` exact-equality filter: it
108 /// is the durable source the dispatch-hold set is rebuilt from at startup and
109 /// at shard adoption, so a run paused before a `kill -9` keeps its outbox rows
110 /// held after restart. A paused run is excluded from [`Self::list_active`]
111 /// (which filters `== Running`), so nothing else would repopulate the hold.
112 async fn list_paused(&self) -> Result<Vec<WorkflowId>, StoreError>;
113
114 /// Returns workflow summaries matching `filter`.
115 async fn query(&self, filter: &WorkflowFilter) -> Result<Vec<WorkflowSummary>, StoreError>;
116
117 /// Persists a durable timer for `workflow_id` that is due at `fire_at`.
118 ///
119 /// Timer scheduling remains on the public store surface because timers are not workflow-history
120 /// appends and are used by the timer subsystem after the recorder has written `TimerStarted`.
121 async fn schedule_timer(
122 &self,
123 workflow_id: &WorkflowId,
124 timer_id: &TimerId,
125 fire_at: DateTime<Utc>,
126 ) -> Result<(), StoreError>;
127
128 /// Returns durable timers whose `fire_at` is less than or equal to `as_of`.
129 async fn expired_timers(&self, as_of: DateTime<Utc>) -> Result<Vec<TimerEntry>, StoreError>;
130
131 /// Restrict every per-workflow enumeration (active workflows, timers, outbox
132 /// rows) to the named set of distribution shards this node owns, or restore
133 /// the own-all-shards default when `shards` is `None`.
134 ///
135 /// This is the engine-lifecycle hook behind a multi-shard deployment: the
136 /// boot path tells the store which shards this node serves so recovery and
137 /// enumeration see only that node's slice of the cluster's state. The
138 /// default implementation is a deliberate no-op — single-shard backends
139 /// (in-memory, libSQL) own everything unconditionally, so a `None` or any
140 /// shard set leaves their behaviour byte-identical. Only a sharded backend
141 /// (haematite) overrides this to scope its enumeration. Decorators that wrap
142 /// another store must forward this call to their inner store.
143 fn set_owned_shards(&self, shards: Option<&[usize]>) {
144 let _ = shards;
145 }
146
147 /// Acquire-and-serve ownership of each named distribution shard BEFORE the
148 /// boot path recovers or enumerates over them, so the node is the fenced
149 /// owner and its replicated state is union-merged locally first.
150 ///
151 /// This is the SS-2 election hook the engine boot path calls right after
152 /// [`Self::set_owned_shards`] and BEFORE startup recovery: a distributed
153 /// backend wins the per-shard election and becomes the live owner, so the
154 /// subsequent recovery reads see the full committed history for its shards.
155 ///
156 /// The default implementation is a deliberate no-op returning `Ok(())` —
157 /// single-shard / non-distributed backends (in-memory, libSQL, and the
158 /// single-node haematite mode) own everything unconditionally and elect
159 /// nothing, so boot stays byte-identical. Only a DISTRIBUTED sharded backend
160 /// overrides this to run the election. Decorators that wrap another store
161 /// must forward this call to their inner store.
162 ///
163 /// # Errors
164 ///
165 /// Returns [`StoreError::Backend`] when a distributed backend cannot win the
166 /// election or become the live owner of one of `shards`; the node must not
167 /// serve those shards in that case (fail-closed).
168 fn acquire_owned_shards(&self, shards: &[usize]) -> Result<(), StoreError> {
169 let _ = shards;
170 Ok(())
171 }
172
173 /// Acquire-and-serve ownership of a SINGLE distribution `shard` — the
174 /// per-shard primitive [`Self::acquire_owned_shards`] is a loop over, exposed
175 /// so the failover path can drive a per-shard abort seam: a clean election
176 /// loss on one shard ([`StoreError::NotOwner`]) drops only that shard rather
177 /// than failing the whole adoption batch (ADR-021 clean-partial).
178 ///
179 /// The default implementation is a deliberate no-op returning `Ok(())` —
180 /// single-shard / non-distributed backends own everything unconditionally and
181 /// elect nothing. Only a DISTRIBUTED sharded backend (haematite) overrides it.
182 /// Decorators that wrap another store must forward this call.
183 ///
184 /// # Errors
185 ///
186 /// Returns [`StoreError::NotOwner`] when a strictly higher ballot deposed this
187 /// candidate (a clean, droppable election loss), and [`StoreError::Backend`]
188 /// for a quorum-unavailable election or any transport fault (retryable).
189 fn acquire_owned_shard(&self, shard: usize) -> Result<(), StoreError> {
190 let _ = shard;
191 Ok(())
192 }
193
194 /// Whether this node currently holds LIVE serve-authority for `shard` — it won
195 /// the per-shard election THIS process lifetime and has not been deposed
196 /// in-process.
197 ///
198 /// This is the residual-window re-assertion the failover path uses to exclude
199 /// a survivor that lost its epoch between winning acquire+publish and widening
200 /// its enumeration scope (ADR-021 clean-partial). It is a POINT-IN-TIME
201 /// ADVISORY, not a durable lock — the authoritative gate remains the per-write
202 /// CAS fence.
203 ///
204 /// The default implementation returns `true` — single-shard / non-distributed
205 /// backends own everything unconditionally, so the failover path's
206 /// re-assertion is a no-op there and behaviour stays byte-identical. Only a
207 /// DISTRIBUTED sharded backend (haematite) overrides it. Decorators that wrap
208 /// another store must forward this call.
209 fn is_current_owner(&self, shard: usize) -> bool {
210 let _ = shard;
211 true
212 }
213
214 /// Add `shards` to this node's owned-enumeration scope, UNIONING them with
215 /// the shards it already owns rather than replacing the set.
216 ///
217 /// This is the SS-5 failover hook: when a live node absorbs a dead peer's
218 /// shards it must KEEP serving its own shards while ALSO enumerating the
219 /// adopted ones. [`Self::set_owned_shards`] replaces the scope (the boot
220 /// path's one-shot assignment); this widens it in place. The boot path uses
221 /// `set_owned_shards`; the failover path uses this.
222 ///
223 /// The default implementation is a deliberate no-op — single-shard backends
224 /// own everything unconditionally, so widening their scope is meaningless and
225 /// leaves their behaviour byte-identical. Only a sharded backend (haematite)
226 /// overrides this. Decorators that wrap another store must forward this call.
227 ///
228 /// When the store currently owns ALL shards (the `None` / single-node
229 /// default), it already enumerates `shards`, so a sharded backend leaves the
230 /// own-all scope untouched.
231 fn extend_owned_shards(&self, shards: &[usize]) {
232 let _ = shards;
233 }
234
235 /// Publish THIS node as the current owner of `shard` in the cluster's
236 /// shard-owner directory, so other nodes' request-routing edges resolve
237 /// `shard` to this node (SS-3).
238 ///
239 /// This is the failover-publish hook the engine calls from `adopt_shards`
240 /// right after it has won `shard`'s election: it records, durably and
241 /// cluster-visibly, that this node has adopted `shard`, so a request reaching
242 /// a DIFFERENT survivor routes to this adopter rather than mis-resolving to
243 /// the dead declared owner (gap #2).
244 ///
245 /// The default implementation is a deliberate no-op returning `Ok(())` —
246 /// single-shard / non-distributed backends own everything unconditionally and
247 /// have no peers to coordinate, so boot and adoption stay byte-identical. Only
248 /// a DISTRIBUTED sharded backend overrides this. Decorators that wrap another
249 /// store must forward this call.
250 ///
251 /// # Errors
252 ///
253 /// Returns [`StoreError::NotOwner`] when a distributed backend's fenced
254 /// directory write is out-voted (this node is not actually the owner), and
255 /// [`StoreError::Backend`] for any other replication/transport failure.
256 fn publish_shard_owner(&self, shard: usize) -> Result<(), StoreError> {
257 let _ = shard;
258 Ok(())
259 }
260}
261
262/// Write authority for appending workflow-history events.
263///
264/// `append` requires a [`WriteToken`], so having an `Arc<dyn EventStore>` or
265/// `Arc<dyn ReadableEventStore>` is not sufficient to write events.
266#[async_trait]
267pub trait WritableEventStore: Send + Sync + 'static {
268 /// Atomically appends `events` to `workflow_id` when the stored history head equals
269 /// `expected_seq`.
270 ///
271 /// Implementations must apply every event in `events` or none of them. If the current stored
272 /// head for `workflow_id` differs from `expected_seq`, this method must return
273 /// [`StoreError::SequenceConflict`] and leave history unchanged. A first append with
274 /// `expected_seq == 0` creates the workflow history implicitly.
275 async fn append(
276 &self,
277 token: WriteToken,
278 workflow_id: &WorkflowId,
279 events: &[Event],
280 expected_seq: u64,
281 ) -> Result<(), StoreError>;
282
283 /// Atomically appends `events` and the durable-outbox `outbox_rows` for `workflow_id` in a
284 /// single transaction, under the same expected-head sequence guard as [`Self::append`].
285 ///
286 /// This is the durable fan-out write: the `ActivityScheduled`/`ActivityStarted` scheduling
287 /// events and their matching outbox rows commit together or not at all. Atomicity is
288 /// load-bearing — a committed fan-out batch always carries both, or neither — so the out-of-band
289 /// dispatcher can never observe an outbox row whose scheduling events were rolled back, and a
290 /// re-issued append cannot leave events without their dispatch rows.
291 ///
292 /// # Default implementation (safe for outbox-unaware backends)
293 ///
294 /// The default delegates to [`Self::append`] when `outbox_rows` is empty (byte-for-byte
295 /// equivalent to an event-only append), and otherwise returns [`StoreError::Backend`] **rather
296 /// than silently dropping the outbox rows**. Dropping them would be the dangerous failure mode:
297 /// the events would commit, the workflow would believe its fan-out is durably staged, and the
298 /// rows would never be dispatched. A hard error forces a backend to opt in to durable-outbox
299 /// support by overriding this method (as the libSQL store does) before any caller can route a
300 /// fan-out batch through it.
301 ///
302 /// # Errors
303 ///
304 /// Returns [`StoreError::SequenceConflict`] when the stored head differs from `expected_seq`,
305 /// [`StoreError::Serialization`] when an event or outbox payload cannot be serialized, and
306 /// [`StoreError::Backend`] for backend boundary failures or when an outbox-unaware backend is
307 /// asked to persist a non-empty `outbox_rows` slice.
308 async fn append_with_outbox(
309 &self,
310 token: WriteToken,
311 workflow_id: &WorkflowId,
312 events: &[Event],
313 expected_seq: u64,
314 outbox_rows: &[OutboxRow],
315 ) -> Result<(), StoreError> {
316 if outbox_rows.is_empty() {
317 return self.append(token, workflow_id, events, expected_seq).await;
318 }
319 Err(StoreError::Backend(String::from(
320 "this event store does not support durable-outbox appends; \
321 refusing to drop outbox rows (override WritableEventStore::append_with_outbox)",
322 )))
323 }
324
325 /// Returns the outbox rows for `rows`' `dispatch_key`s to `Pending`, re-staging them for the
326 /// out-of-band dispatcher.
327 ///
328 /// This is the crash-recovery re-arm: on first arrival after a restart, an activity whose
329 /// `ActivityScheduled` is recorded but which has no terminal event lost its in-flight dispatch
330 /// when the previous engine process died. Under the durable-outbox model the recovering workflow
331 /// re-stages the dispatch by flipping its outbox row back to claimable `Pending` (an UPSERT — a
332 /// brand-new `dispatch_key` with no prior row is inserted as `Pending`) instead of driving an
333 /// in-process completion task. Redelivery is safe: the completion dedup
334 /// (`record_fan_out_completion`) ignores a terminal for an already-resolved ordinal, so re-arm is
335 /// at-least-once.
336 ///
337 /// The dispatch retry budget is preserved across re-arm: a backend must NOT reset an existing
338 /// row's `attempt` to zero, so a workflow that reliably crashes the server still eventually
339 /// dead-letters rather than re-dispatching forever.
340 ///
341 /// # Default implementation (safe for outbox-unaware backends)
342 ///
343 /// An empty `rows` slice is `Ok(())`. A non-empty slice returns [`StoreError::Backend`] **rather
344 /// than silently no-op'ing the re-arm**: a store without durable-outbox support cannot re-stage a
345 /// dispatch, and silently dropping the request would strand the recovered activity. A hard error
346 /// forces a backend to opt in (as the libSQL store does) before any caller can route a re-arm
347 /// through it.
348 ///
349 /// # Errors
350 ///
351 /// Returns [`StoreError::Serialization`] when an outbox payload cannot be serialized, and
352 /// [`StoreError::Backend`] for backend boundary failures or when an outbox-unaware backend is
353 /// asked to re-arm a non-empty `rows` slice.
354 async fn rearm_outbox_pending(&self, rows: &[OutboxRow]) -> Result<(), StoreError> {
355 if rows.is_empty() {
356 return Ok(());
357 }
358 Err(StoreError::Backend(String::from(
359 "this event store does not support durable-outbox re-arm; \
360 refusing to drop a non-empty re-arm (override WritableEventStore::rearm_outbox_pending)",
361 )))
362 }
363
364 /// Idempotently settles one outbox row to cancelled when this writer is backed by an outbox.
365 ///
366 /// Outbox-aware backends override this and delegate to [`crate::OutboxStore`]. The default is a
367 /// no-op so non-outbox test stores and legacy backends can still record `ActivityCancelled`
368 /// history without requiring an outbox table.
369 ///
370 /// # Errors
371 ///
372 /// Outbox-aware overrides return [`StoreError::Backend`] for backend boundary failures.
373 async fn settle_outbox_row_cancelled(&self, dispatch_key: &str) -> Result<(), StoreError> {
374 let _ = dispatch_key;
375 Ok(())
376 }
377
378 /// Idempotently settles EVERY live ([`crate::OutboxStatus::Pending`] or
379 /// [`crate::OutboxStatus::Claimed`]) outbox row of `workflow_id` to
380 /// [`crate::OutboxStatus::Cancelled`], returning the settled `dispatch_key`s (#253).
381 ///
382 /// This is the workflow-terminal settle the Recorder runs after durably recording a workflow
383 /// terminal (`WorkflowCompleted`/`WorkflowFailed`/`WorkflowCancelled`): a terminal workflow's
384 /// staged dispatches must never be redelivered, so its live rows are retired to the terminal
385 /// `Cancelled` disposition that re-arm and claim contractually never touch. Rows already in
386 /// `Done`/`Failed`/`Cancelled` are left untouched, so the settle is idempotent. Reopen still
387 /// supersedes it: [`Self::rearm_outbox_pending`] forcibly returns any existing row — including a
388 /// `Cancelled` one — to `Pending`, so a reopened workflow's re-dispatches deliver again.
389 ///
390 /// The default is a no-op returning no settled keys, mirroring
391 /// [`Self::settle_outbox_row_cancelled`], so non-outbox test stores and legacy backends record
392 /// workflow terminals without requiring an outbox table. Outbox-aware backends override it and
393 /// share the implementation with [`crate::OutboxStore::cancel_outbox_rows_for_workflow`].
394 ///
395 /// # Errors
396 ///
397 /// Outbox-aware overrides return [`StoreError::Backend`] for backend boundary failures and
398 /// [`StoreError::Serialization`] when a stored row cannot be decoded.
399 async fn settle_workflow_outbox_rows_cancelled(
400 &self,
401 workflow_id: &WorkflowId,
402 ) -> Result<Vec<String>, StoreError> {
403 let _ = workflow_id;
404 Ok(Vec::new())
405 }
406}
407
408/// Convenience trait for concrete stores that support reads/timers, recorder
409/// writes, and deployed-package persistence.
410///
411/// [`crate::PackageStore`] is part of the contract, not an optional add-on:
412/// runtime-deployed packages share the durability promise of event history
413/// (a recovered run is pinned to a recorded package version, and a backend
414/// that dropped the archive would strand it).
415pub trait EventStore: ReadableEventStore + WritableEventStore + crate::PackageStore {}
416
417impl<T> EventStore for T where
418 T: ReadableEventStore + WritableEventStore + crate::PackageStore + ?Sized
419{
420}
421
422pub(crate) fn conformance_write_token() -> WriteToken {
423 write_capability::conformance()
424}
425
426#[cfg(test)]
427mod tests {
428 use std::sync::Arc;
429
430 use super::{EventStore, ReadableEventStore, WritableEventStore};
431
432 #[test]
433 fn event_store_traits_are_object_safe() {
434 let _: Option<Arc<dyn ReadableEventStore>> = None;
435 let _: Option<Arc<dyn WritableEventStore>> = None;
436 let _: Option<Arc<dyn EventStore>> = None;
437 }
438}