use std::pin::Pin;
use futures_core::Stream;
use crate::{
AppendOutcome, PersistenceError, PersistenceId, PersistenceResult, SequenceNr,
SerializedPayload, Tag,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredEvent {
pub persistence_id: PersistenceId,
pub sequence_nr: SequenceNr,
pub adapter_manifest: String,
pub writer_uuid: String,
pub timestamp_ms: i64,
pub metadata: Option<SerializedPayload>,
pub payload: SerializedPayload,
pub tags: Vec<Tag>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AtomicWrite {
events: Vec<StoredEvent>,
}
impl AtomicWrite {
pub fn new(events: Vec<StoredEvent>) -> PersistenceResult<Self> {
let Some(first) = events.first() else {
return Err(PersistenceError::InvalidAtomicWrite(
"at least one event is required".to_owned(),
));
};
if let Some(event) = events
.iter()
.find(|event| event.persistence_id != first.persistence_id)
{
return Err(PersistenceError::InvalidAtomicWrite(format!(
"event for persistence id {} does not match {}",
event.persistence_id, first.persistence_id
)));
}
for pair in events.windows(2) {
let current = pair[0].sequence_nr.as_u64();
let expected = current.checked_add(1).ok_or_else(|| {
PersistenceError::InvalidAtomicWrite(format!(
"sequence number {current} cannot have a successor"
))
})?;
let actual = pair[1].sequence_nr.as_u64();
if actual != expected {
return Err(PersistenceError::InvalidAtomicWrite(format!(
"expected sequence number {expected} after {current}, got {actual}"
)));
}
}
Ok(Self { events })
}
#[must_use]
pub fn persistence_id(&self) -> &PersistenceId {
&self.events[0].persistence_id
}
#[must_use]
pub fn events(&self) -> &[StoredEvent] {
&self.events
}
#[must_use]
pub fn into_events(self) -> Vec<StoredEvent> {
self.events
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplayRange {
pub persistence_id: PersistenceId,
pub from: SequenceNr,
pub to: SequenceNr,
pub max: u64,
}
pub type EventStream = Pin<Box<dyn Stream<Item = PersistenceResult<StoredEvent>> + Send + 'static>>;
#[async_trait::async_trait]
pub trait Journal: Send + Sync {
async fn append(&self, writes: Vec<AtomicWrite>) -> PersistenceResult<Vec<AppendOutcome>>;
async fn append_one(&self, write: AtomicWrite) -> PersistenceResult<AppendOutcome> {
let outcomes = self.append(vec![write]).await?;
let mut outcomes = outcomes.into_iter();
let outcome = outcomes.next().ok_or_else(|| {
PersistenceError::Failure("journal returned no outcome for one atomic write".into())
})?;
if outcomes.next().is_some() {
return Err(PersistenceError::Failure(
"journal returned more than one outcome for one atomic write".into(),
));
}
Ok(outcome)
}
async fn highest_sequence_nr(
&self,
persistence_id: &PersistenceId,
from_hint: SequenceNr,
) -> PersistenceResult<SequenceNr>;
async fn replay(&self, range: ReplayRange) -> PersistenceResult<EventStream>;
async fn delete_to(
&self,
persistence_id: &PersistenceId,
inclusive: SequenceNr,
) -> PersistenceResult<()>;
}