use crate::{
Error, OwnedChange, Result,
config::AppConfig,
engine::{Runtime, checkpoint::State},
sink::TransactionSink,
};
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy, Debug)]
pub struct Event<'a> {
pub source_id: &'a str,
pub checkpoint: &'a State,
pub changes: &'a [OwnedChange],
}
pub trait EventHandler: Send + Sync {
fn handle(&self, event: Event<'_>) -> Result<()>;
}
impl<F> EventHandler for F
where
F: Fn(Event<'_>) -> Result<()> + Send + Sync,
{
fn handle(&self, event: Event<'_>) -> Result<()> {
self(event)
}
}
pub struct Replication {
config: AppConfig,
runtime: Runtime,
handlers: Vec<Box<dyn EventHandler>>,
}
impl Replication {
pub fn new(config: AppConfig) -> Result<Self> {
Self::with_runtime(config, Runtime::default())
}
pub fn with_runtime(config: AppConfig, runtime: Runtime) -> Result<Self> {
config.validate()?;
Ok(Self {
config,
runtime,
handlers: Vec::new(),
})
}
pub fn add_handle(&mut self, handler: impl EventHandler + 'static) -> &mut Self {
self.handlers.push(Box::new(handler));
self
}
pub fn check(&self) -> Result<()> {
self.runtime.check(&self.config)
}
pub fn initialize(self) -> Result<()> {
self.runtime.initialize(self.config)
}
pub fn run(self) -> Result<()> {
self.start(false)
}
pub fn run_once(self) -> Result<()> {
self.start(true)
}
fn start(self, once: bool) -> Result<()> {
if self.handlers.is_empty() {
return Err(Error::Sink("register at least one event handler".into()));
}
self.runtime.run(
self.config,
once,
Arc::new(Handlers {
handlers: self.handlers,
failed: Mutex::new(false),
}),
)
}
}
struct Handlers {
handlers: Vec<Box<dyn EventHandler>>,
failed: Mutex<bool>,
}
impl TransactionSink for Handlers {
fn commit(&self, source_id: &str, state: &State, changes: &[OwnedChange]) -> Result<()> {
let mut failed = self
.failed
.lock()
.map_err(|_| Error::Sink("event handler lock poisoned".into()))?;
if *failed {
return Err(Error::Sink("an event handler failed previously".into()));
}
let event = Event {
source_id,
checkpoint: state,
changes,
};
for handler in &self.handlers {
if let Err(error) = handler.handle(event) {
*failed = true;
return Err(error);
}
}
Ok(())
}
}