use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard},
};
use super::{CursorPosition, ProjectionCursor, ProjectionError, ProjectionId, ProjectionResult};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProjectionGeneration(u64);
impl ProjectionGeneration {
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
#[must_use]
pub const fn as_u64(self) -> u64 {
self.0
}
}
#[async_trait::async_trait]
pub trait ProjectionOffsetStore: Send + Sync {
fn validate_exactly_once(&self) -> ProjectionResult<()> {
Err(ProjectionError::invalid_config(
"delivery_semantics",
"exactly-once requires a transactional projection offset store",
))
}
async fn claim(&self, projection_id: &ProjectionId) -> ProjectionResult<ProjectionGeneration>;
async fn load(
&self,
projection_id: &ProjectionId,
) -> ProjectionResult<Option<ProjectionCursor>>;
async fn save(
&self,
projection_id: &ProjectionId,
generation: ProjectionGeneration,
expected_position: Option<&CursorPosition>,
cursor: ProjectionCursor,
) -> ProjectionResult<()>;
async fn clear(
&self,
projection_id: &ProjectionId,
generation: ProjectionGeneration,
) -> ProjectionResult<()>;
async fn load_paused(&self, projection_id: &ProjectionId) -> ProjectionResult<bool>;
async fn set_paused(&self, projection_id: &ProjectionId, paused: bool) -> ProjectionResult<()>;
#[cfg(feature = "postgres")]
#[doc(hidden)]
fn postgres_store(&self) -> Option<&super::PostgresProjectionOffsetStore> {
None
}
}
#[derive(Debug, Default)]
struct MemoryOffsetEntry {
generation: ProjectionGeneration,
cursor: Option<ProjectionCursor>,
}
#[derive(Debug, Default)]
struct MemoryOffsetState {
offsets: HashMap<ProjectionId, MemoryOffsetEntry>,
management: HashMap<ProjectionId, bool>,
}
#[derive(Debug, Clone, Default)]
pub struct MemoryProjectionOffsetStore {
state: Arc<Mutex<MemoryOffsetState>>,
}
impl MemoryProjectionOffsetStore {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
#[async_trait::async_trait]
impl ProjectionOffsetStore for MemoryProjectionOffsetStore {
async fn claim(&self, projection_id: &ProjectionId) -> ProjectionResult<ProjectionGeneration> {
projection_id.validate()?;
let mut state = lock(&self.state)?;
let entry = state.offsets.entry(projection_id.clone()).or_default();
let next = entry.generation.as_u64().checked_add(1).ok_or_else(|| {
ProjectionError::GenerationExhausted {
projection_id: projection_id.clone(),
}
})?;
entry.generation = ProjectionGeneration::new(next);
Ok(entry.generation)
}
async fn load(
&self,
projection_id: &ProjectionId,
) -> ProjectionResult<Option<ProjectionCursor>> {
projection_id.validate()?;
let state = lock(&self.state)?;
Ok(state
.offsets
.get(projection_id)
.and_then(|entry| entry.cursor.clone()))
}
async fn save(
&self,
projection_id: &ProjectionId,
generation: ProjectionGeneration,
expected_position: Option<&CursorPosition>,
cursor: ProjectionCursor,
) -> ProjectionResult<()> {
projection_id.validate()?;
let mut state = lock(&self.state)?;
let entry = state.offsets.get_mut(projection_id);
validate_generation(projection_id, generation, entry.as_deref())?;
let entry = entry.expect("validated claimed generation has an entry");
let actual_position = entry.cursor.as_ref().map(ProjectionCursor::position);
if actual_position != expected_position {
return Err(ProjectionError::UnexpectedPosition {
projection_id: projection_id.clone(),
expected: expected_position.map(ToString::to_string),
actual: actual_position.map(ToString::to_string),
});
}
entry.cursor = Some(cursor);
Ok(())
}
async fn clear(
&self,
projection_id: &ProjectionId,
generation: ProjectionGeneration,
) -> ProjectionResult<()> {
projection_id.validate()?;
let mut state = lock(&self.state)?;
let entry = state.offsets.get_mut(projection_id);
validate_generation(projection_id, generation, entry.as_deref())?;
entry
.expect("validated claimed generation has an entry")
.cursor = None;
Ok(())
}
async fn load_paused(&self, projection_id: &ProjectionId) -> ProjectionResult<bool> {
projection_id.validate()?;
let state = lock(&self.state)?;
Ok(state
.management
.get(projection_id)
.copied()
.unwrap_or(false))
}
async fn set_paused(&self, projection_id: &ProjectionId, paused: bool) -> ProjectionResult<()> {
projection_id.validate()?;
let mut state = lock(&self.state)?;
state.management.insert(projection_id.clone(), paused);
Ok(())
}
}
fn validate_generation(
projection_id: &ProjectionId,
attempted: ProjectionGeneration,
entry: Option<&MemoryOffsetEntry>,
) -> ProjectionResult<()> {
let current = entry.map_or(ProjectionGeneration::default(), |entry| entry.generation);
if attempted != current || attempted == ProjectionGeneration::default() {
return Err(ProjectionError::Fenced {
projection_id: projection_id.clone(),
attempted_generation: attempted.as_u64(),
current_generation: current.as_u64(),
});
}
Ok(())
}
fn lock(state: &Mutex<MemoryOffsetState>) -> ProjectionResult<MutexGuard<'_, MemoryOffsetState>> {
state
.lock()
.map_err(|_| ProjectionError::OffsetStore("in-memory offset-store lock poisoned".into()))
}