use std::collections::BTreeSet;
use std::fmt;
use std::future::{poll_fn, Future};
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, Waker};
use futures_core::Stream;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::{EventType, Machine};
use crate::input::{is_event, Chunk, Control, Input, Outcome};
use crate::journal::{ChunkEntry, HostedCheckpoint, JournalEntry, SnapshotEntry, StartEntry};
use crate::record::{Checkpoint, Fault, FaultCode, Record};
use crate::step::{Applied, Checkpoints, Options, Run, Stepper};
use crate::work::{Action, Invoke, Work, WorkId};
pub trait Clock {
fn now(&self) -> u64;
fn sleep_until(&self, at: u64) -> impl Future<Output = ()>;
}
pub trait Journal {
type Error: fmt::Display;
fn code(error: &Self::Error) -> FaultCode {
let _ = error;
FaultCode::WorkflowJournalFailed
}
fn keeps(&self) -> bool {
true
}
fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>>;
fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>>;
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MemoryJournal {
pub entries: Vec<JournalEntry>,
}
impl Journal for MemoryJournal {
type Error = std::convert::Infallible;
fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
std::future::ready(Ok(self.entries.clone()))
}
fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
self.entries.extend_from_slice(entries);
std::future::ready(Ok(()))
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoJournal;
impl Journal for NoJournal {
type Error = std::convert::Infallible;
fn keeps(&self) -> bool {
false
}
fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
std::future::ready(Ok(Vec::new()))
}
fn append(&mut self, _: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
std::future::ready(Ok(()))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HandlerContext {
pub id: String,
pub actor: String,
pub run: String,
}
pub trait Handlers {
fn invoke(&self, work: Invoke, context: HandlerContext) -> impl Future<Output = Result<Value, Value>>;
fn action(&self, work: Action, context: HandlerContext) -> impl Future<Output = Result<(), String>>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoHandlers;
impl Handlers for NoHandlers {
fn invoke(&self, _: Invoke, _: HandlerContext) -> impl Future<Output = Result<Value, Value>> {
std::future::pending()
}
fn action(&self, _: Action, _: HandlerContext) -> impl Future<Output = Result<(), String>> {
std::future::pending()
}
}
pub trait Sink {
fn record(&mut self, record: &Record);
fn fault(&mut self, fault: &Fault) {
let _ = fault;
}
}
impl<F: FnMut(&Record)> Sink for F {
fn record(&mut self, record: &Record) {
self(record);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
#[default]
ApplyFirst,
JournalFirst,
JournalSync,
}
#[derive(Debug, Clone, Default)]
pub struct HostOptions {
pub order: Order,
pub run: Option<String>,
pub version: Option<String>,
pub options: Options,
pub checkpoint: Option<Checkpoints>,
pub from: Option<HostedCheckpoint>,
pub breathe: Option<u64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Hosted {
pub seq: u64,
pub checkpoint: HostedCheckpoint,
}
const CHECKPOINT: u64 = 64;
const BREATHE: u64 = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
User,
Feedback,
}
enum Settled {
Work { id: String, outcome: Outcome, data: Option<Value> },
Failed { id: String, message: String },
}
const RETRY: u64 = 100;
const RETRY_MAX: u64 = 30_000;
fn journal_failed<J: Journal>(error: &J::Error, seq: u64) -> Fault {
Fault::new(J::code(error), format!("The journal failed: {error}"), seq)
}
async fn settle<H: Handlers>(handlers: &H, work: Work, run: String) -> Settled {
match work {
Work::Invoke(invoke) => {
let id = invoke.id.clone();
let context = HandlerContext { id: id.clone(), actor: invoke.actor.clone(), run };
match handlers.invoke(invoke, context).await {
Ok(output) => Settled::Work { id, outcome: Outcome::Resolved, data: Some(output) },
Err(error) => Settled::Work { id, outcome: Outcome::Rejected, data: Some(error) },
}
}
Work::Action(action) => {
let id = action.id.clone();
let context = HandlerContext { id: id.clone(), actor: action.actor.clone(), run };
match handlers.action(action, context).await {
Ok(()) => Settled::Work { id, outcome: Outcome::Done, data: None },
Err(message) => Settled::Failed { id, message },
}
}
}
}
fn to_start<C, E>(run: &Run<C, E>, started: &mut BTreeSet<String>) -> (BTreeSet<String>, Vec<Work>)
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let work = &run.last().work;
let waiting: BTreeSet<String> = work.iter().map(|w| w.id().to_owned()).collect();
started.retain(|id| waiting.contains(id));
let new = work.iter().cloned().map(Work::from).filter(|w| started.insert(w.id().to_owned())).collect();
(waiting, new)
}
fn now_or_never<F: Future>(future: F) -> Option<F::Output> {
let mut future = std::pin::pin!(future);
match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
Poll::Ready(output) => Some(output),
Poll::Pending => None,
}
}
pub async fn hosted<C, E, S, K, J, H, O>(
machine: Arc<Machine<C, E>>,
options: HostOptions,
inputs: S,
clock: &K,
journal: &mut J,
handlers: &H,
sink: &mut O,
) -> Result<Hosted, Fault>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
S: Stream<Item = Chunk<Value>>,
K: Clock,
J: Journal,
H: Handlers,
O: Sink,
{
let order = options.order;
let run_id = options.run.clone().unwrap_or_else(|| "root".to_owned());
let breathe = options.breathe.unwrap_or(BREATHE).max(1);
let fallback = if journal.keeps() { Checkpoints::Every(CHECKPOINT) } else { Checkpoints::Never };
let checkpoints = options.checkpoint.unwrap_or(fallback);
let entries = journal.read().await.map_err(|e| journal_failed::<J>(&e, 0))?;
if let Some(from) = &options.from {
check_start(&from.start, &run_id, options.version.as_deref(), FaultCode::WorkflowInvalidSnapshot)?;
if options.options.input.is_some() {
return Err(Fault::new(
FaultCode::WorkflowInvalidSnapshot,
"A checkpoint carries the input its run started of: give from or input, not both.",
from.seq,
));
}
if !entries.is_empty() {
sink.fault(&Fault::new(
FaultCode::WorkflowInvalidSnapshot,
"The journal holds the run: the checkpoint given as from is not read, and the run reopens of the journal.",
0,
));
}
}
let mut last_stamp = 0u64;
let mut stamp = |clock: &K| {
last_stamp = last_stamp.max(clock.now());
last_stamp
};
let (mut run, start, opening) = if entries.is_empty() {
let (start, run_options) = match &options.from {
None => {
let time = stamp(clock);
let o = &options.options;
let max_timers = o.max_timers.unwrap_or(xmachines_runtime::work::DEFAULT_MAX_TIMERS as u64);
let start = StartEntry {
run: run_id.clone(),
actor: o.actor.clone().unwrap_or_else(|| "root".to_owned()),
version: options.version.clone(),
input: o.input.clone(),
time: time as i64,
max_timers,
};
let run_options = Options {
actor: Some(start.actor.clone()),
time: Some(time as i64),
input: o.input.clone(),
checkpoint: Some(checkpoints),
max_timers: Some(max_timers),
max_steps: o.max_steps,
from: None,
};
(start, run_options)
}
Some(from) => {
let run_options = Options {
actor: Some(from.start.actor.clone()),
checkpoint: Some(checkpoints),
max_timers: Some(from.start.max_timers),
max_steps: options.options.max_steps,
from: Some(Checkpoint { seq: from.seq, snapshot: from.snapshot.clone() }),
..Options::default()
};
(from.start.clone(), run_options)
}
};
let (run, opening) = Run::open(machine, run_options)?;
let mut first = vec![JournalEntry::Start(start.clone())];
if let Some(from) = &options.from {
first.push(JournalEntry::Snapshot(SnapshotEntry {
epoch: None,
positions: None,
published: None,
seq: from.seq,
snapshot: from.snapshot.clone(),
}));
}
journal.append(&first).await.map_err(|e| journal_failed::<J>(&e, 0))?;
(run, start, opening)
} else {
let (run, start) = replay(machine, &entries, &run_id, options.version.as_deref(), checkpoints, &options)?;
let opening = vec![run.record()];
(run, start, opening)
};
for record in &opening {
sink.record(record);
}
let mut inputs = std::pin::pin!(inputs);
let mut started: BTreeSet<String> = BTreeSet::new();
let mut pending = Vec::new();
let mut retries = none_of(|| (String::new(), Box::pin(clock.sleep_until(0))));
let mut attempts: std::collections::BTreeMap<String, u32> = std::collections::BTreeMap::new();
let mut timer = None;
let mut stuck: Option<u64> = None;
let mut in_a_row = 0u64;
macro_rules! reconcile {
() => {{
let (waiting, new) = to_start(&run, &mut started);
pending.retain(|(id, _)| waiting.contains(id));
retries.retain(|(id, _)| waiting.contains(id));
attempts.retain(|id, _| waiting.contains(id));
for work in new {
let id = work.id().to_owned();
pending.push((id, Box::pin(settle(handlers, work, run_id.clone()))));
}
}};
}
reconcile!();
loop {
let deadline = run.last().deadline.filter(|d| Some(*d) != stuck);
if timer.as_ref().map(|(at, _)| *at) != deadline {
timer = deadline.map(|at| (at, Box::pin(clock.sleep_until(at))));
}
let next = poll_fn(|cx| {
for at in 0..pending.len() {
if let Poll::Ready(settled) = pending[at].1.as_mut().poll(cx) {
drop(pending.swap_remove(at));
return Poll::Ready(Some(Next::Settled(settled)));
}
}
for at in 0..retries.len() {
if retries[at].1.as_mut().poll(cx).is_ready() {
let (id, _) = retries.swap_remove(at);
return Poll::Ready(Some(Next::Retry(id)));
}
}
if let Some((_, sleep)) = timer.as_mut() {
if sleep.as_mut().poll(cx).is_ready() {
timer = None;
return Poll::Ready(Some(Next::Time));
}
}
match inputs.as_mut().poll_next(cx) {
Poll::Ready(Some(chunk)) => Poll::Ready(Some(Next::Chunk(chunk))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
})
.await;
let Some(next) = next else { break };
let fired = matches!(next, Next::Time).then(|| run.last().deadline).flatten();
let (inputs_of, origin) = match next {
Next::Chunk(chunk) => {
let batch = chunk.into_batch();
if !batch.iter().all(is_event) {
sink.fault(&Fault::new(
FaultCode::WorkflowInvalidInput,
"A caller writes events alone: time and work results are the host's.",
0,
));
continue;
}
(batch, Origin::User)
}
Next::Time => (Vec::new(), Origin::Feedback),
Next::Settled(Settled::Work { id, outcome, data }) => {
started.remove(&id);
attempts.remove(&id);
let control = Control::Work { id, outcome, data, extra: serde_json::Map::new() };
(vec![serde_json::to_value(control).unwrap_or_default()], Origin::Feedback)
}
Next::Settled(Settled::Failed { id, message }) => {
let attempt = attempts.entry(id.clone()).or_insert(0);
let wait = RETRY.saturating_mul(1 << (*attempt).min(16)).min(RETRY_MAX);
*attempt += 1;
retries.push((id.clone(), Box::pin(clock.sleep_until(clock.now().saturating_add(wait)))));
sink.fault(&Fault::new(
FaultCode::WorkflowHostActionFailed,
format!("The host action {id} failed, and is tried again in {wait} ms: {message}"),
0,
));
continue;
}
Next::Retry(id) => {
started.remove(&id);
reconcile!();
continue;
}
};
let now = stamp(clock);
let mut chunk = Vec::with_capacity(inputs_of.len() + 1);
chunk.push(serde_json::to_value(Control::<Value>::time(now as i64)).unwrap_or_default());
chunk.extend(inputs_of);
if stale(&run, &chunk, origin) {
continue;
}
if chunk.iter().any(is_event) {
let mut caught = None;
while let Some(deadline) = run.last().deadline {
if deadline > now || caught.is_some_and(|last| deadline <= last) {
break;
}
caught = Some(deadline);
let time = vec![chunk[0].clone()];
apply_one(&mut run, time, order, journal, sink).await?;
}
}
apply_one(&mut run, chunk, order, journal, sink).await?;
stuck = match (fired, run.last().deadline) {
(Some(was), Some(is)) if was == is => Some(is),
_ => None,
};
reconcile!();
in_a_row += 1;
if in_a_row.is_multiple_of(breathe) {
yield_now().await;
}
}
Ok(Hosted {
seq: run.seq(),
checkpoint: HostedCheckpoint { seq: run.seq(), snapshot: run.checkpoint().snapshot, start },
})
}
enum Next {
Chunk(Chunk<Value>),
Time,
Settled(Settled),
Retry(String),
}
async fn write<J: Journal>(journal: &mut J, entries: &[JournalEntry], sync: bool, seq: u64) -> Result<(), Fault> {
if sync {
return match now_or_never(journal.append(entries)) {
Some(appended) => appended.map_err(|e| journal_failed::<J>(&e, seq)),
None => Err(Fault::new(
FaultCode::WorkflowJournalFailed,
"The order journal-sync takes a journal that appends at once.",
seq,
)),
};
}
journal.append(entries).await.map_err(|e| journal_failed::<J>(&e, seq))
}
fn none_of<T>(_make: impl FnOnce() -> T) -> Vec<T> {
Vec::new()
}
fn check_start(start: &StartEntry, run: &str, version: Option<&str>, code: FaultCode) -> Result<(), Fault> {
if start.max_timers < 1 {
return Err(Fault::new(code, "The start has no bound of timers.", 0));
}
if start.time < 0 {
return Err(Fault::new(code, format!("The start is at {}: a time is 0 or more.", start.time), 0));
}
if start.version.as_deref() != version {
return Err(Fault::new(
code,
format!("The run is of version {:?} of the machine, not {version:?}.", start.version),
0,
));
}
if start.run != run {
return Err(Fault::new(code, format!("The run is {}, not {run}.", start.run), 0));
}
Ok(())
}
fn replay<C, E>(
machine: Arc<Machine<C, E>>,
entries: &[JournalEntry],
run_id: &str,
version: Option<&str>,
checkpoints: Checkpoints,
options: &HostOptions,
) -> Result<(Run<C, E>, StartEntry), Fault>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let invalid = |message: String, seq: u64| Fault::new(FaultCode::WorkflowInvalidJournal, message, seq);
let Some(JournalEntry::Start(start)) = entries.first() else {
return Err(invalid(
"The journal does not start with its start: a store that drops its oldest entries is no journal.".into(),
0,
));
};
check_start(start, run_id, version, FaultCode::WorkflowInvalidJournal)?;
let from = entries.iter().rev().find_map(|entry| match entry {
JournalEntry::Snapshot(snapshot) => Some(Checkpoint { seq: snapshot.seq, snapshot: snapshot.snapshot.clone() }),
_ => None,
});
let reopened = from.is_some();
let run_options = Options {
actor: Some(start.actor.clone()),
time: (!reopened).then_some(start.time),
input: if reopened { None } else { start.input.clone() },
checkpoint: Some(checkpoints),
max_timers: Some(start.max_timers),
max_steps: options.options.max_steps,
from,
};
let (mut run, _) = Run::open(machine, run_options)?;
let mut seen = BTreeSet::new();
for entry in entries {
let JournalEntry::Chunk(chunk) = entry else { continue };
if !seen.insert(chunk.seq) {
return Err(invalid(
format!("The journal holds chunk {} twice: two writers wrote the run.", chunk.seq),
chunk.seq,
));
}
if chunk.seq <= run.seq() {
continue;
}
if chunk.seq != run.seq() + 1 {
return Err(invalid(format!("The journal skips from chunk {} to {}.", run.seq(), chunk.seq), chunk.seq));
}
let batch = chunk.chunk.iter().map(|input| serde_json::to_value(input).unwrap_or_default()).collect();
match run.step(&Chunk::Batch(batch)) {
Ok(Applied::Applied { .. } | Applied::Rejected { .. }) => {}
Err(fault) if fault.code.is_recoverable() => {}
Err(fault) => return Err(fault),
}
}
Ok((run, start.clone()))
}
fn stale<C, E>(run: &Run<C, E>, chunk: &[Value], origin: Origin) -> bool
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
if origin != Origin::Feedback {
return false;
}
let last = run.last();
let work: Vec<&str> = chunk.iter().filter(|i| i["kind"] == "work").filter_map(|i| i["id"].as_str()).collect();
if work.is_empty() {
let now = chunk[0]["now"].as_u64().unwrap_or_default();
return last.deadline.is_none_or(|deadline| deadline > now);
}
work.len() == chunk.len() - 1 && work.iter().all(|id| !last.work.iter().any(|w| w.id() == *id))
}
async fn apply_one<C, E, J: Journal, O: Sink>(
run: &mut Run<C, E>,
chunk: Vec<Value>,
order: Order,
journal: &mut J,
sink: &mut O,
) -> Result<(), Fault>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let seq = run.seq() + 1;
let inputs = chunk
.iter()
.map(|input| Input::from_value(input.clone()))
.collect::<Result<_, _>>()
.map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {e}."), seq))?;
let entry = JournalEntry::Chunk(ChunkEntry { seq, chunk: inputs, source: None, epoch: None });
if order != Order::ApplyFirst {
write(journal, std::slice::from_ref(&entry), order == Order::JournalSync, seq).await?;
}
let mut records = Vec::new();
let applied = run.apply(Chunk::Batch(chunk), &mut records);
if order == Order::ApplyFirst {
records.iter().for_each(|record| sink.record(record));
write(journal, std::slice::from_ref(&entry), false, seq).await?;
}
if let Some(Record::Snapshot { seq, snapshot }) = records.last() {
if snapshot.state.is_some() {
let checkpoint = JournalEntry::Snapshot(SnapshotEntry {
epoch: None,
positions: None,
published: None,
seq: *seq,
snapshot: (**snapshot).clone(),
});
write(journal, std::slice::from_ref(&checkpoint), order == Order::JournalSync, *seq).await?;
}
}
if order != Order::ApplyFirst {
records.iter().for_each(|record| sink.record(record));
}
match applied {
Ok(_) => Ok(()),
Err(fault) if fault.code.is_recoverable() => {
sink.fault(&fault);
Ok(())
}
Err(fault) => Err(fault),
}
}
async fn yield_now() {
let mut yielded = false;
poll_fn(|cx| {
if yielded {
Poll::Ready(())
} else {
yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
})
.await;
}
#[derive(Debug, Clone, Default)]
pub struct ManualClock {
state: Arc<Mutex<ManualState>>,
}
#[derive(Debug, Default)]
struct ManualState {
now: u64,
next: u64,
waiting: std::collections::BTreeMap<u64, (u64, Waker)>,
}
impl ManualClock {
pub fn new(now: u64) -> Self {
Self { state: Arc::new(Mutex::new(ManualState { now, ..ManualState::default() })) }
}
pub fn set(&self, now: u64) {
let due: Vec<Waker> = {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
state.now = state.now.max(now);
let now = state.now;
let (due, waiting) = std::mem::take(&mut state.waiting).into_iter().partition(|(_, (at, _))| *at <= now);
state.waiting = waiting;
due.into_values().map(|(_, waker)| waker).collect()
};
due.into_iter().for_each(Waker::wake);
}
pub fn advance(&self, ms: u64) {
let now = self.now();
self.set(now + ms);
}
pub fn waiting(&self) -> usize {
self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.len()
}
}
impl Clock for ManualClock {
fn now(&self) -> u64 {
self.state.lock().unwrap_or_else(PoisonError::into_inner).now
}
fn sleep_until(&self, at: u64) -> impl Future<Output = ()> {
let id = {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
state.next += 1;
state.next
};
ManualSleep { state: Arc::clone(&self.state), at, id }
}
}
#[derive(Debug)]
struct ManualSleep {
state: Arc<Mutex<ManualState>>,
at: u64,
id: u64,
}
impl Future for ManualSleep {
type Output = ();
fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if state.now >= self.at {
state.waiting.remove(&self.id);
return Poll::Ready(());
}
match state.waiting.get_mut(&self.id) {
Some((_, waker)) => waker.clone_from(cx.waker()),
None => {
state.waiting.insert(self.id, (self.at, cx.waker().clone()));
}
}
Poll::Pending
}
}
impl Drop for ManualSleep {
fn drop(&mut self) {
self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.remove(&self.id);
}
}