Skip to main content

xmachines_workflow/
host.rs

1//! A run, hosted: [`hosted`] stamps each chunk with the time, journals it,
2//! applies it, and gives its records to a [`Sink`], with a clock that writes
3//! the time when a timer is due and a worker that does the work the machine
4//! waits for, in one of three writer orders ([`Order`]). Everything it needs
5//! is passed in: the [`Clock`], the [`Journal`] and the [`Handlers`]. It
6//! reads no clock of its own, spawns no task, and needs no executor's
7//! features: one future, one loop, no queue, no deadlock.
8//!
9//! The journal's entries are the JSON of xmachines-js's hosts
10//! ([`JournalEntry`]): a journal one host wrote reopens on the other.
11
12use std::collections::BTreeSet;
13use std::fmt;
14use std::future::{poll_fn, Future};
15use std::sync::{Arc, Mutex, PoisonError};
16use std::task::{Context, Poll, Waker};
17
18use futures_core::Stream;
19use serde::de::DeserializeOwned;
20use serde::Serialize;
21use serde_json::Value;
22use xmachines_runtime::{EventType, Machine};
23
24use crate::input::{is_event, Chunk, Control, Input, Outcome};
25use crate::journal::{ChunkEntry, HostedCheckpoint, JournalEntry, SnapshotEntry, StartEntry};
26use crate::record::{Checkpoint, Fault, FaultCode, Record};
27use crate::step::{Applied, Checkpoints, Options, Run, Stepper};
28use crate::work::{Action, Invoke, Work, WorkId};
29
30/// The wall's time, and a wait until a time of it: what stamps each chunk
31/// and arms the timers of a hosted run. One trait, since a wait means
32/// nothing without the clock it is measured on.
33pub trait Clock {
34    /// The wall's time now, in whole milliseconds since the epoch.
35    fn now(&self) -> u64;
36    /// A future that is ready once [`Clock::now`] has reached `at`. A host
37    /// drops it to cancel the wait.
38    fn sleep_until(&self, at: u64) -> impl Future<Output = ()>;
39}
40
41/// An append-only log of a run's entries, as little of one as a host needs:
42/// a durable stream, a table, a file, or memory. `append` stores the entries
43/// given together, all or none, once its future is ready.
44pub trait Journal {
45    /// Why an append or a read failed.
46    type Error: fmt::Display;
47    /// The code of the fault an error stops the host with:
48    /// `WORKFLOW_JOURNAL_FAILED` by default; `WORKFLOW_JOURNAL_FENCED` of a
49    /// journal that refused a writer behind another, as a holder whose lease
50    /// was lost.
51    fn code(error: &Self::Error) -> FaultCode {
52        let _ = error;
53        FaultCode::WorkflowJournalFailed
54    }
55    /// Whether the journal keeps what it is given: a host takes no
56    /// checkpoint of one that keeps nothing ([`NoJournal`]).
57    fn keeps(&self) -> bool {
58        true
59    }
60    /// What the journal holds, in order: none of a new run.
61    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>>;
62    /// Stores `entries`, all or none.
63    fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>>;
64}
65
66/// A journal in memory, which stores each append at once: what a test, a
67/// demo or a page that keeps nothing hosts a run on, and a journal the order
68/// [`Order::JournalSync`] takes.
69#[derive(Debug, Clone, Default, PartialEq)]
70pub struct MemoryJournal {
71    /// The entries, in order.
72    pub entries: Vec<JournalEntry>,
73}
74
75impl Journal for MemoryJournal {
76    type Error = std::convert::Infallible;
77
78    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
79        std::future::ready(Ok(self.entries.clone()))
80    }
81
82    fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
83        self.entries.extend_from_slice(entries);
84        std::future::ready(Ok(()))
85    }
86}
87
88/// No journal: a run that keeps nothing, as a local view.
89#[derive(Debug, Clone, Copy, Default)]
90pub struct NoJournal;
91
92impl Journal for NoJournal {
93    type Error = std::convert::Infallible;
94
95    fn keeps(&self) -> bool {
96        false
97    }
98
99    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
100        std::future::ready(Ok(Vec::new()))
101    }
102
103    fn append(&mut self, _: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
104        std::future::ready(Ok(()))
105    }
106}
107
108/// What a handler of work is told beside the work: its id, its actor, and
109/// the run it is of. A host action is done at least once: a handler that
110/// must do it once dedupes by the run and the id.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct HandlerContext {
113    /// The work's id.
114    pub id: String,
115    /// The address of the actor whose work it is.
116    pub actor: String,
117    /// The run's id.
118    pub run: String,
119}
120
121/// The work a host does for its runs: invoked work, which gives an output
122/// or fails with an error, and host actions, which are done or fail. Each
123/// handler closes over what it needs; a future dropped is the work aborted.
124pub trait Handlers {
125    /// Does invoked work: `Ok` of its output, settled `resolved`, or `Err` of
126    /// its error, settled `rejected`.
127    fn invoke(&self, work: Invoke, context: HandlerContext) -> impl Future<Output = Result<Value, Value>>;
128    /// Does a host action: `Ok` once it is done, settled `done`, or `Err` of
129    /// why it failed, which the host reports as `WORKFLOW_HOST_ACTION_FAILED`
130    /// and tries again after a wait, while the run still lists the action:
131    /// 100 ms the first time, doubling each time after, to 30 s.
132    fn action(&self, work: Action, context: HandlerContext) -> impl Future<Output = Result<(), String>>;
133}
134
135/// No handlers: work stays pending until something else settles it.
136#[derive(Debug, Clone, Copy, Default)]
137pub struct NoHandlers;
138
139impl Handlers for NoHandlers {
140    fn invoke(&self, _: Invoke, _: HandlerContext) -> impl Future<Output = Result<Value, Value>> {
141        std::future::pending()
142    }
143
144    fn action(&self, _: Action, _: HandlerContext) -> impl Future<Output = Result<(), String>> {
145        std::future::pending()
146    }
147}
148
149/// Where a hosted run's records and faults go.
150pub trait Sink {
151    /// A record of the run, in order.
152    fn record(&mut self, record: &Record);
153    /// A fault the run went on after: a chunk that is no input, a result of
154    /// the other kind of work, a host action that failed.
155    fn fault(&mut self, fault: &Fault) {
156        let _ = fault;
157    }
158}
159
160impl<F: FnMut(&Record)> Sink for F {
161    fn record(&mut self, record: &Record) {
162        self(record);
163    }
164}
165
166/// The order a host writes a run in. Each gives the same journal and the
167/// same records.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub enum Order {
170    /// A chunk applies at once, its records go to the sink, and the journal
171    /// follows. For a local UI: the sink may be ahead of the journal, and a
172    /// crash loses what was not in it yet, which nothing but the sink saw.
173    #[default]
174    ApplyFirst,
175    /// A chunk applies once it is in the journal. For a server of an async
176    /// log: the sink is never ahead, and nothing acknowledged is lost.
177    JournalFirst,
178    /// A chunk is appended to a synchronous log, then applies, at once. A
179    /// journal whose append is not ready at once is `WORKFLOW_JOURNAL_FAILED`.
180    JournalSync,
181}
182
183/// The options of [`hosted`].
184#[derive(Debug, Clone, Default)]
185pub struct HostOptions {
186    /// The order the host writes the run in.
187    pub order: Order,
188    /// The run's id, which its journal's start holds: `root` by default.
189    pub run: Option<String>,
190    /// The machine's version: a journal or a checkpoint of another is
191    /// refused.
192    pub version: Option<String>,
193    /// The root actor's id, its input, its bound of timers and of steps, as
194    /// [`Options`] has them. Its `time` is the clock's, its `from` is
195    /// [`HostOptions::from`], and its `checkpoint` is
196    /// [`HostOptions::checkpoint`]'s.
197    pub options: Options,
198    /// How often the journal takes a checkpoint, by `seq`: every 64 chunks
199    /// by default, of a journal that keeps them, and never of one that keeps
200    /// nothing, as a local view.
201    pub checkpoint: Option<Checkpoints>,
202    /// The checkpoint to reopen the run of, when the journal holds nothing,
203    /// as [`Hosted::checkpoint`] gave it: the run starts as its start says.
204    /// One of another run or version is `WORKFLOW_INVALID_SNAPSHOT` either
205    /// way; of a journal that holds the run, the run reopens of the journal,
206    /// and the sink is told the checkpoint was not read.
207    pub from: Option<HostedCheckpoint>,
208    /// The loop yields to its executor once each this many chunks, so a run
209    /// that feeds itself can't starve the executor: 128 by default.
210    pub breathe: Option<u64>,
211}
212
213/// What a hosted run left when its source ended: its last `seq`, and a
214/// checkpoint of it, with its start, which reopens it.
215#[derive(Debug, Clone, PartialEq)]
216pub struct Hosted {
217    /// The number of the last chunk read.
218    pub seq: u64,
219    /// The run as a checkpoint now, with how it started.
220    pub checkpoint: HostedCheckpoint,
221}
222
223/// How often a journal takes a checkpoint, of no `checkpoint`.
224const CHECKPOINT: u64 = 64;
225/// How often the loop yields, of no `breathe`.
226const BREATHE: u64 = 128;
227
228/// Where a chunk came from: the caller's source, or the host's own clock
229/// and worker, whose chunks are dropped when they change nothing.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum Origin {
232    User,
233    Feedback,
234}
235
236/// The result of a handler, as the host reads it.
237enum Settled {
238    Work { id: String, outcome: Outcome, data: Option<Value> },
239    Failed { id: String, message: String },
240}
241
242/// How long a host action that failed waits before it is tried again, the
243/// first time: it doubles each time after, to [`RETRY_MAX`].
244const RETRY: u64 = 100;
245/// The longest wait before a host action that failed is tried again.
246const RETRY_MAX: u64 = 30_000;
247
248/// A journal's error as the host's fault, of the journal's code.
249fn journal_failed<J: Journal>(error: &J::Error, seq: u64) -> Fault {
250    Fault::new(J::code(error), format!("The journal failed: {error}"), seq)
251}
252
253/// Does `work` by `handlers`, for run `run`: what the loop holds of each
254/// piece of work in flight. One concrete future, no box of a trait object, so
255/// the host's future is `Send` when the handlers' are.
256async fn settle<H: Handlers>(handlers: &H, work: Work, run: String) -> Settled {
257    match work {
258        Work::Invoke(invoke) => {
259            let id = invoke.id.clone();
260            let context = HandlerContext { id: id.clone(), actor: invoke.actor.clone(), run };
261            match handlers.invoke(invoke, context).await {
262                Ok(output) => Settled::Work { id, outcome: Outcome::Resolved, data: Some(output) },
263                Err(error) => Settled::Work { id, outcome: Outcome::Rejected, data: Some(error) },
264            }
265        }
266        Work::Action(action) => {
267            let id = action.id.clone();
268            let context = HandlerContext { id: id.clone(), actor: action.actor.clone(), run };
269            match handlers.action(action, context).await {
270                Ok(()) => Settled::Work { id, outcome: Outcome::Done, data: None },
271                Err(message) => Settled::Failed { id, message },
272            }
273        }
274    }
275}
276
277/// The work the run waits for that has no handler running yet, each marked
278/// started; and the ids it no longer waits for are dropped from `started`.
279fn to_start<C, E>(run: &Run<C, E>, started: &mut BTreeSet<String>) -> (BTreeSet<String>, Vec<Work>)
280where
281    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
282    E: EventType + Send + Sync,
283{
284    let work = &run.last().work;
285    let waiting: BTreeSet<String> = work.iter().map(|w| w.id().to_owned()).collect();
286    started.retain(|id| waiting.contains(id));
287    let new = work.iter().cloned().map(Work::from).filter(|w| started.insert(w.id().to_owned())).collect();
288    (waiting, new)
289}
290
291/// Polls `future` once, as the order [`Order::JournalSync`] reads an append:
292/// ready at once, or a journal that is not synchronous.
293fn now_or_never<F: Future>(future: F) -> Option<F::Output> {
294    let mut future = std::pin::pin!(future);
295    match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
296        Poll::Ready(output) => Some(output),
297        Poll::Pending => None,
298    }
299}
300
301/// Hosts a run of `machine`: stamps each chunk `inputs` gives with the time
302/// of `clock`, journals it in `journal`, applies it, and gives its records to
303/// `sink`, in the order of `options`. The clock writes the time when a timer
304/// is due, and the worker does the work the machine waits for by `handlers`
305/// and writes back its result, each stamped too. Gives the run as it was
306/// when `inputs` ended, or the fault it could not go on from.
307///
308/// - One way in: the order of entry is the order of the run. A caller writes
309///   events alone: a chunk of the caller's with a control input is a fault of
310///   no chunk, `WORKFLOW_INVALID_INPUT`, and is dropped. Time is the host's
311///   to stamp, and never goes back.
312/// - A run behind its deadlines, as one reopened after a day, is caught up
313///   with chunks of time alone, each firing at most `maxTimers` timers,
314///   before an event applies.
315/// - A time or a work result of the host's own that changes nothing, a race
316///   lost, takes no `seq` and is dropped. A late result of work aborted is
317///   dropped, not a fault.
318/// - The journal's first entry is the run's start; then each chunk that took
319///   a `seq`, faulted ones too; and every `checkpoint` chunks a checkpoint.
320///   A journal that holds entries reopens the run: its last checkpoint, then
321///   the chunks after it, applied with nothing given to the sink and no work
322///   started; then the work pending starts, once, by the ids it had. One
323///   that does not start with its start, skips a chunk, holds one twice, or
324///   is of another run or version is `WORKFLOW_INVALID_JOURNAL`.
325/// - A journal that fails stops the host, `WORKFLOW_JOURNAL_FAILED`: what it
326///   applied may not be in the journal.
327///
328/// When `inputs` ends the host stops at once: the timer and the work in
329/// flight are dropped. Drop the future to stop it sooner.
330pub async fn hosted<C, E, S, K, J, H, O>(
331    machine: Arc<Machine<C, E>>,
332    options: HostOptions,
333    inputs: S,
334    clock: &K,
335    journal: &mut J,
336    handlers: &H,
337    sink: &mut O,
338) -> Result<Hosted, Fault>
339where
340    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
341    E: EventType + Send + Sync,
342    S: Stream<Item = Chunk<Value>>,
343    K: Clock,
344    J: Journal,
345    H: Handlers,
346    O: Sink,
347{
348    let order = options.order;
349    let run_id = options.run.clone().unwrap_or_else(|| "root".to_owned());
350    let breathe = options.breathe.unwrap_or(BREATHE).max(1);
351    let fallback = if journal.keeps() { Checkpoints::Every(CHECKPOINT) } else { Checkpoints::Never };
352    let checkpoints = options.checkpoint.unwrap_or(fallback);
353    let entries = journal.read().await.map_err(|e| journal_failed::<J>(&e, 0))?;
354    if let Some(from) = &options.from {
355        // A checkpoint is of this run and this version, whether the journal reads it or not.
356        check_start(&from.start, &run_id, options.version.as_deref(), FaultCode::WorkflowInvalidSnapshot)?;
357        if options.options.input.is_some() {
358            return Err(Fault::new(
359                FaultCode::WorkflowInvalidSnapshot,
360                "A checkpoint carries the input its run started of: give from or input, not both.",
361                from.seq,
362            ));
363        }
364        if !entries.is_empty() {
365            sink.fault(&Fault::new(
366                FaultCode::WorkflowInvalidSnapshot,
367                "The journal holds the run: the checkpoint given as from is not read, and the run reopens of the journal.",
368                0,
369            ));
370        }
371    }
372    let mut last_stamp = 0u64;
373    let mut stamp = |clock: &K| {
374        last_stamp = last_stamp.max(clock.now());
375        last_stamp
376    };
377
378    // The run: reopened of its journal, or new, or of a checkpoint.
379    let (mut run, start, opening) = if entries.is_empty() {
380        let (start, run_options) = match &options.from {
381            None => {
382                let time = stamp(clock);
383                let o = &options.options;
384                let max_timers = o.max_timers.unwrap_or(xmachines_runtime::work::DEFAULT_MAX_TIMERS as u64);
385                let start = StartEntry {
386                    run: run_id.clone(),
387                    actor: o.actor.clone().unwrap_or_else(|| "root".to_owned()),
388                    version: options.version.clone(),
389                    input: o.input.clone(),
390                    time: time as i64,
391                    max_timers,
392                };
393                let run_options = Options {
394                    actor: Some(start.actor.clone()),
395                    time: Some(time as i64),
396                    input: o.input.clone(),
397                    checkpoint: Some(checkpoints),
398                    max_timers: Some(max_timers),
399                    max_steps: o.max_steps,
400                    from: None,
401                };
402                (start, run_options)
403            }
404            Some(from) => {
405                let run_options = Options {
406                    actor: Some(from.start.actor.clone()),
407                    checkpoint: Some(checkpoints),
408                    max_timers: Some(from.start.max_timers),
409                    max_steps: options.options.max_steps,
410                    from: Some(Checkpoint { seq: from.seq, snapshot: from.snapshot.clone() }),
411                    ..Options::default()
412                };
413                (from.start.clone(), run_options)
414            }
415        };
416        let (run, opening) = Run::open(machine, run_options)?;
417        let mut first = vec![JournalEntry::Start(start.clone())];
418        if let Some(from) = &options.from {
419            first.push(JournalEntry::Snapshot(SnapshotEntry {
420                epoch: None,
421                positions: None,
422                published: None,
423                seq: from.seq,
424                snapshot: from.snapshot.clone(),
425            }));
426        }
427        journal.append(&first).await.map_err(|e| journal_failed::<J>(&e, 0))?;
428        (run, start, opening)
429    } else {
430        let (run, start) = replay(machine, &entries, &run_id, options.version.as_deref(), checkpoints, &options)?;
431        let opening = vec![run.record()];
432        (run, start, opening)
433    };
434    for record in &opening {
435        sink.record(record);
436    }
437
438    let mut inputs = std::pin::pin!(inputs);
439    let mut started: BTreeSet<String> = BTreeSet::new();
440    // Each container's element type is the one concrete future of its kind, so the host's future
441    // is `Send` when the clock's and the handlers' futures are.
442    let mut pending = Vec::new();
443    // The retries' one concrete future, the clock's wait.
444    let mut retries = none_of(|| (String::new(), Box::pin(clock.sleep_until(0))));
445    let mut attempts: std::collections::BTreeMap<String, u32> = std::collections::BTreeMap::new();
446    let mut timer = None;
447    // A deadline a chunk of time did not move: a timer that never fires, which waits for a change.
448    let mut stuck: Option<u64> = None;
449    let mut in_a_row = 0u64;
450    // Starts the work the run waits for that has no handler, and drops the handlers, and the retries,
451    // of work it no longer waits for: their work is aborted.
452    macro_rules! reconcile {
453        () => {{
454            let (waiting, new) = to_start(&run, &mut started);
455            pending.retain(|(id, _)| waiting.contains(id));
456            retries.retain(|(id, _)| waiting.contains(id));
457            attempts.retain(|id, _| waiting.contains(id));
458            for work in new {
459                let id = work.id().to_owned();
460                pending.push((id, Box::pin(settle(handlers, work, run_id.clone()))));
461            }
462        }};
463    }
464    reconcile!();
465
466    loop {
467        // The timer of the next deadline, armed again when it moves; never of a stuck one.
468        let deadline = run.last().deadline.filter(|d| Some(*d) != stuck);
469        if timer.as_ref().map(|(at, _)| *at) != deadline {
470            timer = deadline.map(|at| (at, Box::pin(clock.sleep_until(at))));
471        }
472        let next = poll_fn(|cx| {
473            // Work that settled, then the retries of host actions, then the timer, then the caller.
474            for at in 0..pending.len() {
475                if let Poll::Ready(settled) = pending[at].1.as_mut().poll(cx) {
476                    drop(pending.swap_remove(at));
477                    return Poll::Ready(Some(Next::Settled(settled)));
478                }
479            }
480            for at in 0..retries.len() {
481                if retries[at].1.as_mut().poll(cx).is_ready() {
482                    let (id, _) = retries.swap_remove(at);
483                    return Poll::Ready(Some(Next::Retry(id)));
484                }
485            }
486            if let Some((_, sleep)) = timer.as_mut() {
487                if sleep.as_mut().poll(cx).is_ready() {
488                    timer = None;
489                    return Poll::Ready(Some(Next::Time));
490                }
491            }
492            match inputs.as_mut().poll_next(cx) {
493                Poll::Ready(Some(chunk)) => Poll::Ready(Some(Next::Chunk(chunk))),
494                Poll::Ready(None) => Poll::Ready(None),
495                Poll::Pending => Poll::Pending,
496            }
497        })
498        .await;
499        let Some(next) = next else { break };
500        let fired = matches!(next, Next::Time).then(|| run.last().deadline).flatten();
501        let (inputs_of, origin) = match next {
502            Next::Chunk(chunk) => {
503                let batch = chunk.into_batch();
504                if !batch.iter().all(is_event) {
505                    sink.fault(&Fault::new(
506                        FaultCode::WorkflowInvalidInput,
507                        "A caller writes events alone: time and work results are the host's.",
508                        0,
509                    ));
510                    continue;
511                }
512                (batch, Origin::User)
513            }
514            Next::Time => (Vec::new(), Origin::Feedback),
515            Next::Settled(Settled::Work { id, outcome, data }) => {
516                started.remove(&id);
517                attempts.remove(&id);
518                let control = Control::Work { id, outcome, data, extra: serde_json::Map::new() };
519                (vec![serde_json::to_value(control).unwrap_or_default()], Origin::Feedback)
520            }
521            Next::Settled(Settled::Failed { id, message }) => {
522                // Tried again after a wait that doubles each time, while the run still lists it. A fault
523                // of no chunk: the chunk that took the action had its outcome.
524                let attempt = attempts.entry(id.clone()).or_insert(0);
525                let wait = RETRY.saturating_mul(1 << (*attempt).min(16)).min(RETRY_MAX);
526                *attempt += 1;
527                retries.push((id.clone(), Box::pin(clock.sleep_until(clock.now().saturating_add(wait)))));
528                sink.fault(&Fault::new(
529                    FaultCode::WorkflowHostActionFailed,
530                    format!("The host action {id} failed, and is tried again in {wait} ms: {message}"),
531                    0,
532                ));
533                continue;
534            }
535            Next::Retry(id) => {
536                started.remove(&id);
537                reconcile!();
538                continue;
539            }
540        };
541        let now = stamp(clock);
542        let mut chunk = Vec::with_capacity(inputs_of.len() + 1);
543        chunk.push(serde_json::to_value(Control::<Value>::time(now as i64)).unwrap_or_default());
544        chunk.extend(inputs_of);
545        if stale(&run, &chunk, origin) {
546            continue;
547        }
548        // A run behind its deadlines catches up with chunks of time alone before an event applies.
549        if chunk.iter().any(is_event) {
550            let mut caught = None;
551            while let Some(deadline) = run.last().deadline {
552                if deadline > now || caught.is_some_and(|last| deadline <= last) {
553                    break;
554                }
555                caught = Some(deadline);
556                let time = vec![chunk[0].clone()];
557                apply_one(&mut run, time, order, journal, sink).await?;
558            }
559        }
560        apply_one(&mut run, chunk, order, journal, sink).await?;
561        // A timer whose chunk of time left its deadline where it was never fires: it waits for a change.
562        stuck = match (fired, run.last().deadline) {
563            (Some(was), Some(is)) if was == is => Some(is),
564            _ => None,
565        };
566        reconcile!();
567        in_a_row += 1;
568        if in_a_row.is_multiple_of(breathe) {
569            yield_now().await;
570        }
571    }
572    Ok(Hosted {
573        seq: run.seq(),
574        checkpoint: HostedCheckpoint { seq: run.seq(), snapshot: run.checkpoint().snapshot, start },
575    })
576}
577
578/// What the loop takes next.
579enum Next {
580    Chunk(Chunk<Value>),
581    Time,
582    Settled(Settled),
583    /// The wait of a host action that failed is over.
584    Retry(String),
585}
586
587/// Appends `entries` to `journal`, at once of the order `journal-sync`: a
588/// journal that does not append at once is `WORKFLOW_JOURNAL_FAILED` then.
589async fn write<J: Journal>(journal: &mut J, entries: &[JournalEntry], sync: bool, seq: u64) -> Result<(), Fault> {
590    if sync {
591        return match now_or_never(journal.append(entries)) {
592            Some(appended) => appended.map_err(|e| journal_failed::<J>(&e, seq)),
593            None => Err(Fault::new(
594                FaultCode::WorkflowJournalFailed,
595                "The order journal-sync takes a journal that appends at once.",
596                seq,
597            )),
598        };
599    }
600    journal.append(entries).await.map_err(|e| journal_failed::<J>(&e, seq))
601}
602
603/// An empty list of what `make` gives, which is never called: it names the
604/// type of an element that has no name, as a clock's wait.
605fn none_of<T>(_make: impl FnOnce() -> T) -> Vec<T> {
606    Vec::new()
607}
608
609/// Refuses a start of another run or version, or one that is no start of a
610/// run, with `code`.
611fn check_start(start: &StartEntry, run: &str, version: Option<&str>, code: FaultCode) -> Result<(), Fault> {
612    if start.max_timers < 1 {
613        return Err(Fault::new(code, "The start has no bound of timers.", 0));
614    }
615    if start.time < 0 {
616        return Err(Fault::new(code, format!("The start is at {}: a time is 0 or more.", start.time), 0));
617    }
618    if start.version.as_deref() != version {
619        return Err(Fault::new(
620            code,
621            format!("The run is of version {:?} of the machine, not {version:?}.", start.version),
622            0,
623        ));
624    }
625    if start.run != run {
626        return Err(Fault::new(code, format!("The run is {}, not {run}.", start.run), 0));
627    }
628    Ok(())
629}
630
631/// Reopens a run of its journal's `entries`: its start, then its last
632/// checkpoint, then each chunk after it, applied in order, with nothing
633/// given out and no work started.
634fn replay<C, E>(
635    machine: Arc<Machine<C, E>>,
636    entries: &[JournalEntry],
637    run_id: &str,
638    version: Option<&str>,
639    checkpoints: Checkpoints,
640    options: &HostOptions,
641) -> Result<(Run<C, E>, StartEntry), Fault>
642where
643    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
644    E: EventType + Send + Sync,
645{
646    let invalid = |message: String, seq: u64| Fault::new(FaultCode::WorkflowInvalidJournal, message, seq);
647    let Some(JournalEntry::Start(start)) = entries.first() else {
648        return Err(invalid(
649            "The journal does not start with its start: a store that drops its oldest entries is no journal.".into(),
650            0,
651        ));
652    };
653    check_start(start, run_id, version, FaultCode::WorkflowInvalidJournal)?;
654    let from = entries.iter().rev().find_map(|entry| match entry {
655        JournalEntry::Snapshot(snapshot) => Some(Checkpoint { seq: snapshot.seq, snapshot: snapshot.snapshot.clone() }),
656        _ => None,
657    });
658    let reopened = from.is_some();
659    let run_options = Options {
660        actor: Some(start.actor.clone()),
661        time: (!reopened).then_some(start.time),
662        input: if reopened { None } else { start.input.clone() },
663        checkpoint: Some(checkpoints),
664        max_timers: Some(start.max_timers),
665        max_steps: options.options.max_steps,
666        from,
667    };
668    let (mut run, _) = Run::open(machine, run_options)?;
669    let mut seen = BTreeSet::new();
670    for entry in entries {
671        let JournalEntry::Chunk(chunk) = entry else { continue };
672        // Two chunks of one seq are two writers of one run: the journal is no run's.
673        if !seen.insert(chunk.seq) {
674            return Err(invalid(
675                format!("The journal holds chunk {} twice: two writers wrote the run.", chunk.seq),
676                chunk.seq,
677            ));
678        }
679        if chunk.seq <= run.seq() {
680            continue;
681        }
682        if chunk.seq != run.seq() + 1 {
683            return Err(invalid(format!("The journal skips from chunk {} to {}.", run.seq(), chunk.seq), chunk.seq));
684        }
685        let batch = chunk.chunk.iter().map(|input| serde_json::to_value(input).unwrap_or_default()).collect();
686        match run.step(&Chunk::Batch(batch)) {
687            Ok(Applied::Applied { .. } | Applied::Rejected { .. }) => {}
688            Err(fault) if fault.code.is_recoverable() => {}
689            Err(fault) => return Err(fault),
690        }
691    }
692    Ok((run, start.clone()))
693}
694
695/// Whether a chunk of the host's own clock or worker changes nothing, read
696/// against the run as it is: time alone, of a run whose deadline is not due
697/// by it, or the result of work the run no longer waits for. A race lost: it
698/// takes no `seq`, as in `@xmachines/run`'s host.
699fn stale<C, E>(run: &Run<C, E>, chunk: &[Value], origin: Origin) -> bool
700where
701    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
702    E: EventType + Send + Sync,
703{
704    if origin != Origin::Feedback {
705        return false;
706    }
707    let last = run.last();
708    let work: Vec<&str> = chunk.iter().filter(|i| i["kind"] == "work").filter_map(|i| i["id"].as_str()).collect();
709    if work.is_empty() {
710        let now = chunk[0]["now"].as_u64().unwrap_or_default();
711        return last.deadline.is_none_or(|deadline| deadline > now);
712    }
713    work.len() == chunk.len() - 1 && work.iter().all(|id| !last.work.iter().any(|w| w.id() == *id))
714}
715
716/// Applies one stamped chunk under the run's next `seq`, journaled in
717/// `order`, its records given to `sink`, and its checkpoint journaled when
718/// its snapshot holds the state. A fault the run goes on after goes to the
719/// sink; any other is the host's.
720async fn apply_one<C, E, J: Journal, O: Sink>(
721    run: &mut Run<C, E>,
722    chunk: Vec<Value>,
723    order: Order,
724    journal: &mut J,
725    sink: &mut O,
726) -> Result<(), Fault>
727where
728    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
729    E: EventType + Send + Sync,
730{
731    let seq = run.seq() + 1;
732    let inputs = chunk
733        .iter()
734        .map(|input| Input::from_value(input.clone()))
735        .collect::<Result<_, _>>()
736        .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {e}."), seq))?;
737    let entry = JournalEntry::Chunk(ChunkEntry { seq, chunk: inputs, source: None, epoch: None });
738    if order != Order::ApplyFirst {
739        write(journal, std::slice::from_ref(&entry), order == Order::JournalSync, seq).await?;
740    }
741    let mut records = Vec::new();
742    let applied = run.apply(Chunk::Batch(chunk), &mut records);
743    if order == Order::ApplyFirst {
744        records.iter().for_each(|record| sink.record(record));
745        write(journal, std::slice::from_ref(&entry), false, seq).await?;
746    }
747    if let Some(Record::Snapshot { seq, snapshot }) = records.last() {
748        if snapshot.state.is_some() {
749            let checkpoint = JournalEntry::Snapshot(SnapshotEntry {
750                epoch: None,
751                positions: None,
752                published: None,
753                seq: *seq,
754                snapshot: (**snapshot).clone(),
755            });
756            write(journal, std::slice::from_ref(&checkpoint), order == Order::JournalSync, *seq).await?;
757        }
758    }
759    if order != Order::ApplyFirst {
760        records.iter().for_each(|record| sink.record(record));
761    }
762    match applied {
763        Ok(_) => Ok(()),
764        Err(fault) if fault.code.is_recoverable() => {
765            sink.fault(&fault);
766            Ok(())
767        }
768        Err(fault) => Err(fault),
769    }
770}
771
772/// A future that is pending once, then ready: the loop yields to its
773/// executor, so a run that feeds itself can't starve it.
774async fn yield_now() {
775    let mut yielded = false;
776    poll_fn(|cx| {
777        if yielded {
778            Poll::Ready(())
779        } else {
780            yielded = true;
781            cx.waker().wake_by_ref();
782            Poll::Pending
783        }
784    })
785    .await;
786}
787
788/// A clock a test moves by hand: the twin of a fake timer. Its time moves
789/// only by [`ManualClock::set`] and [`ManualClock::advance`], which wake the
790/// waits due by then. Clones share one clock.
791#[derive(Debug, Clone, Default)]
792pub struct ManualClock {
793    state: Arc<Mutex<ManualState>>,
794}
795
796#[derive(Debug, Default)]
797struct ManualState {
798    now: u64,
799    /// The next wait's id.
800    next: u64,
801    /// Each armed wait not yet due, by its id: when it is due, and its waker.
802    waiting: std::collections::BTreeMap<u64, (u64, Waker)>,
803}
804
805impl ManualClock {
806    /// A clock at `now`.
807    pub fn new(now: u64) -> Self {
808        Self { state: Arc::new(Mutex::new(ManualState { now, ..ManualState::default() })) }
809    }
810
811    /// Moves the clock to `now`, if it is ahead, and wakes each wait due by
812    /// then.
813    pub fn set(&self, now: u64) {
814        let due: Vec<Waker> = {
815            let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
816            state.now = state.now.max(now);
817            let now = state.now;
818            let (due, waiting) = std::mem::take(&mut state.waiting).into_iter().partition(|(_, (at, _))| *at <= now);
819            state.waiting = waiting;
820            due.into_values().map(|(_, waker)| waker).collect()
821        };
822        due.into_iter().for_each(Waker::wake);
823    }
824
825    /// Moves the clock on by `ms`.
826    pub fn advance(&self, ms: u64) {
827        let now = self.now();
828        self.set(now + ms);
829    }
830
831    /// How many waits are armed and not yet due: one for each wait polled
832    /// and not yet done, woken or dropped.
833    pub fn waiting(&self) -> usize {
834        self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.len()
835    }
836}
837
838impl Clock for ManualClock {
839    fn now(&self) -> u64 {
840        self.state.lock().unwrap_or_else(PoisonError::into_inner).now
841    }
842
843    fn sleep_until(&self, at: u64) -> impl Future<Output = ()> {
844        let id = {
845            let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
846            state.next += 1;
847            state.next
848        };
849        ManualSleep { state: Arc::clone(&self.state), at, id }
850    }
851}
852
853/// A wait of a [`ManualClock`]: one entry of its clock while it is armed,
854/// its waker replaced when it is polled again, and gone once it is due,
855/// woken or dropped.
856#[derive(Debug)]
857struct ManualSleep {
858    state: Arc<Mutex<ManualState>>,
859    at: u64,
860    id: u64,
861}
862
863impl Future for ManualSleep {
864    type Output = ();
865
866    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
867        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
868        if state.now >= self.at {
869            state.waiting.remove(&self.id);
870            return Poll::Ready(());
871        }
872        match state.waiting.get_mut(&self.id) {
873            Some((_, waker)) => waker.clone_from(cx.waker()),
874            None => {
875                state.waiting.insert(self.id, (self.at, cx.waker().clone()));
876            }
877        }
878        Poll::Pending
879    }
880}
881
882impl Drop for ManualSleep {
883    fn drop(&mut self) {
884        self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.remove(&self.id);
885    }
886}