use std::any::{Any, type_name};
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use crate::{AnyInput, FreshFn, Point, PointKey, Refused, fresh_value};
pub type EncodeFn = fn(&(dyn Any + Send + Sync)) -> Option<String>;
pub type DecodeFn = fn(&str) -> Result<AnyInput, String>;
pub trait Relayed: Point {
fn encode(input: &Self::Input) -> String;
fn decode(text: &str) -> Result<Self::Input, String>;
}
#[derive(Clone, Copy, Debug)]
pub struct Codec {
pub point: &'static str,
pub encode: EncodeFn,
pub decode: DecodeFn,
pub fresh: FreshFn,
}
impl Codec {
pub const fn of<P: Relayed>() -> Codec
where
P::Value: Default,
{
Codec {
point: P::ID,
encode: encode_erased::<P>,
decode: decode_erased::<P>,
fresh: fresh_value::<P::Value>,
}
}
}
impl PartialEq for Codec {
fn eq(&self, other: &Codec) -> bool {
self.point == other.point
}
}
impl Eq for Codec {}
fn encode_erased<P: Relayed>(input: &(dyn Any + Send + Sync)) -> Option<String> {
input.downcast_ref::<P::Input>().map(P::encode)
}
fn decode_erased<P: Relayed>(text: &str) -> Result<AnyInput, String> {
P::decode(text).map(|input| Arc::new(input) as AnyInput)
}
pub fn kind_matches(pattern: &str, kind: &str) -> bool {
if pattern == "*" || pattern == kind {
return true;
}
match pattern.strip_suffix(".*") {
Some(prefix) => kind
.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('.')),
None => false,
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct JournalEntry {
pub seq: u64,
pub kind: String,
pub cause: Option<u64>,
pub source: Option<String>,
pub input: Option<AnyInput>,
pub text: Option<String>,
}
impl JournalEntry {
pub fn new(seq: u64, kind: impl Into<String>) -> JournalEntry {
JournalEntry {
seq,
kind: kind.into(),
cause: None,
source: None,
input: None,
text: None,
}
}
pub fn read<P: Point>(&self) -> Option<&P::Input> {
if self.kind != P::ID {
return None;
}
self.input.as_deref()?.downcast_ref::<P::Input>()
}
}
impl fmt::Debug for JournalEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JournalEntry")
.field("seq", &self.seq)
.field("kind", &self.kind)
.field("cause", &self.cause)
.field("source", &self.source)
.field("input", &self.input.as_ref().map(|_| ".."))
.field("text", &self.text)
.finish()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Since {
pub entries: Vec<JournalEntry>,
pub gap: bool,
pub last_seq: u64,
}
impl Since {
pub fn new(entries: Vec<JournalEntry>, last_seq: u64) -> Since {
Since {
entries,
gap: false,
last_seq,
}
}
}
pub trait Journal: Send + Sync {
fn last_seq(&self) -> u64;
fn since(&self, seq: u64, limit: usize) -> Since;
fn wait(&self, patterns: &[&str], seq: u64, timeout: Duration) -> Option<JournalEntry>;
fn publish_any(
&self,
point: PointKey,
input: AnyInput,
fresh: FreshFn,
cause: Option<u64>,
) -> Result<u64, Refused>;
fn flush(&self, timeout: Duration) -> bool;
}
impl<'a> dyn Journal + 'a {
pub fn publish<P: Point>(&self, input: P::Input) -> Result<u64, Refused>
where
P::Value: Default,
{
self.publish_any(
PointKey::of::<P>(),
Arc::new(input),
fresh_value::<P::Value>,
None,
)
}
pub fn publish_caused<P: Point>(&self, input: P::Input, cause: u64) -> Result<u64, Refused>
where
P::Value: Default,
{
self.publish_any(
PointKey::of::<P>(),
Arc::new(input),
fresh_value::<P::Value>,
Some(cause),
)
}
pub fn wait_for<P: Point>(&self, seq: u64, timeout: Duration) -> Option<(u64, P::Input)>
where
P::Input: Clone,
{
let entry = self.wait(&[P::ID], seq, timeout)?;
let input = entry.read::<P>().cloned().unwrap_or_else(|| {
panic!(
"the journal returned a `{}` entry with no `{}` input",
P::ID,
type_name::<P::Input>()
)
});
Some((entry.seq, input))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Cursor {
pub run: u64,
pub seq: u64,
}
impl Cursor {
pub const START: Cursor = Cursor { run: 0, seq: 0 };
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayedEntry {
pub seq: u64,
pub kind: String,
pub cause: Option<u64>,
pub text: String,
}
impl RelayedEntry {
pub fn new(seq: u64, kind: impl Into<String>, text: impl Into<String>) -> RelayedEntry {
RelayedEntry {
seq,
kind: kind.into(),
cause: None,
text: text.into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Lost {
Gap,
Restarted,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Resumed {
pub entries: Vec<RelayedEntry>,
pub lost: Option<Lost>,
pub next: Cursor,
}
impl Resumed {
pub fn new(entries: Vec<RelayedEntry>, next: Cursor) -> Resumed {
Resumed {
entries,
lost: None,
next,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum IngestError {
Decode {
kind: String,
reason: String,
},
NotRelayable {
kind: String,
},
}
impl fmt::Display for IngestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IngestError::Decode { kind, reason } => {
write!(f, "relayed `{kind}`: cannot read its input: {reason}")
}
IngestError::NotRelayable { kind } => {
write!(f, "relayed `{kind}`: the point is not relayable here")
}
}
}
}
impl std::error::Error for IngestError {}
pub trait Relay: Send + Sync {
fn cursor(&self) -> Cursor;
fn resume(&self, from: Cursor, limit: usize) -> Resumed;
fn ingest(&self, source: &str, entry: RelayedEntry) -> Result<u64, IngestError>;
}