use std::any::{Any, type_name};
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use crate::{
AnyInput, AnyListener, CloneFn, FreshFn, HookError, Point, PointKey, Refused, clone_value,
fresh_value,
};
pub type EncodeFn = fn(&(dyn Any + Send + Sync)) -> Option<String>;
pub type DecodeFn = fn(&str) -> Result<AnyInput, String>;
pub type EncodeValueFn = fn(&(dyn Any + Send)) -> Option<String>;
pub type DecodeValueFn = fn(&str, &mut (dyn Any + Send)) -> Result<(), String>;
pub trait Relayed: Point {
fn encode(input: &Self::Input) -> String;
fn decode(text: &str) -> Result<Self::Input, String>;
}
pub trait RelayedRequest: Relayed {
fn encode_value(value: &Self::Value) -> String;
fn decode_value(text: &str) -> Result<Self::Value, String>;
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Codec {
pub point: &'static str,
pub encode: EncodeFn,
pub decode: DecodeFn,
pub fresh: FreshFn,
pub encode_value: Option<EncodeValueFn>,
pub decode_value: Option<DecodeValueFn>,
pub clone_value: Option<CloneFn>,
}
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>,
encode_value: None,
decode_value: None,
clone_value: None,
}
}
pub const fn request<P: RelayedRequest>() -> Codec
where
P::Value: Default + Clone,
{
Codec {
point: P::ID,
encode: encode_erased::<P>,
decode: decode_erased::<P>,
fresh: fresh_value::<P::Value>,
encode_value: Some(encode_value_erased::<P>),
decode_value: Some(decode_value_erased::<P>),
clone_value: Some(clone_value::<P::Value>),
}
}
pub const fn answers(&self) -> bool {
self.encode_value.is_some() && self.decode_value.is_some() && self.clone_value.is_some()
}
}
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)
}
fn encode_value_erased<P: RelayedRequest>(value: &(dyn Any + Send)) -> Option<String> {
value.downcast_ref::<P::Value>().map(P::encode_value)
}
fn decode_value_erased<P: RelayedRequest>(
text: &str,
into: &mut (dyn Any + Send),
) -> Result<(), String> {
let Some(slot) = into.downcast_mut::<P::Value>() else {
return Err(format!("the value is not a `{}`", type_name::<P::Value>()));
};
*slot = P::decode_value(text)?;
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Origin {
pub process: String,
pub agent: Option<String>,
}
impl Origin {
pub fn process(name: impl Into<String>) -> Origin {
Origin {
process: name.into(),
agent: None,
}
}
pub fn agent(mut self, name: impl Into<String>) -> Origin {
self.agent = Some(name.into());
self
}
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.agent {
Some(agent) => write!(f, "{} (agent {agent})", self.process),
None => f.write_str(&self.process),
}
}
}
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 origin: Option<Origin>,
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,
origin: 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("origin", &self.origin)
.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 version: u32,
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,
version: 1,
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,
},
Refused {
kind: String,
reason: String,
},
Version {
kind: String,
sent: u32,
here: u32,
},
}
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")
}
IngestError::Refused { kind, reason } => {
write!(f, "relayed `{kind}`: refused: {reason}")
}
IngestError::Version { kind, sent, here } => write!(
f,
"relayed `{kind}`: sent at version {sent}, declared here at version {here}"
),
}
}
}
impl std::error::Error for IngestError {}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Crossing<'a> {
pub origin: &'a Origin,
pub kind: &'a str,
pub version: u32,
pub ask: bool,
}
impl<'a> Crossing<'a> {
pub fn new(origin: &'a Origin, kind: &'a str, version: u32, ask: bool) -> Crossing<'a> {
Crossing {
origin,
kind,
version,
ask,
}
}
}
pub type Authority = Arc<dyn Fn(&Crossing<'_>) -> Result<(), String> + Send + Sync>;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayedAsk {
pub run: u64,
pub id: u64,
pub kind: String,
pub version: u32,
pub deadline: Duration,
pub input: String,
pub value: String,
}
impl RelayedAsk {
pub fn new(
run: u64,
id: u64,
kind: impl Into<String>,
deadline: Duration,
input: impl Into<String>,
value: impl Into<String>,
) -> RelayedAsk {
RelayedAsk {
run,
id,
kind: kind.into(),
version: 1,
deadline,
input: input.into(),
value: value.into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Answer {
Done {
value: String,
},
Refused {
listener: Option<String>,
owner: Option<String>,
reason: String,
failed: bool,
},
}
impl Answer {
pub fn refused(reason: impl Into<String>) -> Answer {
Answer::Refused {
listener: None,
owner: None,
reason: reason.into(),
failed: false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayedAnswer {
pub run: u64,
pub id: u64,
pub answer: Answer,
}
impl RelayedAnswer {
pub fn to(ask: &RelayedAsk, answer: Answer) -> RelayedAnswer {
RelayedAnswer {
run: ask.run,
id: ask.id,
answer,
}
}
}
pub trait Relay: Send + Sync {
fn cursor(&self) -> Cursor;
fn resume(&self, from: Cursor, limit: usize) -> Resumed;
fn ingest(&self, origin: &Origin, entry: RelayedEntry) -> Result<u64, IngestError>;
fn answer(&self, origin: &Origin, ask: RelayedAsk) -> RelayedAnswer;
fn add_authority(&self, authority: Authority);
}
impl<'a> dyn Relay + 'a {
pub fn authorize(
&self,
authority: impl Fn(&Crossing<'_>) -> Result<(), String> + Send + Sync + 'static,
) {
self.add_authority(Arc::new(authority));
}
}
pub fn ask_run() -> u64 {
static RUN: OnceLock<u64> = OnceLock::new();
*RUN.get_or_init(|| {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
(nanos ^ (u64::from(std::process::id()) << 32)).max(1)
})
}
fn next_ask_id() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
pub fn far_listener(
codec: Codec,
deadline: Duration,
version: u32,
send: impl Fn(RelayedAsk) -> Option<RelayedAnswer> + Send + Sync + 'static,
) -> AnyListener {
Arc::new(move |input, value| {
let kind = codec.point;
let (Some(encode_value), Some(decode_value)) = (codec.encode_value, codec.decode_value)
else {
return Err(HookError::refuse(format!(
"`{kind}` has no request codec: it cannot cross"
)));
};
let Some(input) = (codec.encode)(input) else {
return Err(HookError::refuse(format!(
"`{kind}`: the input is not the point's"
)));
};
let Some(text) = encode_value(&*value) else {
return Err(HookError::refuse(format!(
"`{kind}`: the value is not the point's"
)));
};
let mut ask = RelayedAsk::new(ask_run(), next_ask_id(), kind, deadline, input, text);
ask.version = version;
let (run, id) = (ask.run, ask.id);
let sent = Instant::now();
let Some(answer) = send(ask) else {
return Err(HookError::refuse(format!(
"`{kind}`: no answer within {deadline:?}"
)));
};
if sent.elapsed() > deadline {
return Err(HookError::refuse(format!(
"`{kind}`: the answer came after {deadline:?}"
)));
}
if (answer.run, answer.id) != (run, id) {
return Err(HookError::refuse(format!(
"`{kind}`: the answer is to another ask"
)));
}
match answer.answer {
Answer::Done { value: text } => decode_value(&text, value).map_err(|reason| {
HookError::refuse(format!("`{kind}`: cannot read the answer: {reason}"))
}),
Answer::Refused {
listener, reason, ..
} => Err(HookError::refuse(match listener {
Some(l) => format!("refused on the far side by `{l}`: {reason}"),
None => format!("refused on the far side: {reason}"),
})),
}
})
}