Skip to main content

Actor

Struct Actor 

Source
pub struct Actor<C, E> { /* private fields */ }
Expand description

A running machine and its invoked children: an actor System whose root is machine, with conveniences for the root.

The actor never reads a clock. The host passes the current time in milliseconds; Actor::next_deadline says when timers are due.

Effects are handled as a live XState actor would: the root’s emitted events and logs are collected (Actor::take_emitted, Actor::take_logs), and every actor’s emitted events once observed (Actor::observe_system_emitted); custom actions with a Rust implementation run immediately; async work (@xstate.effect) stays pending until the host resolves it with Actor::resolve_effect.

Errors are handled as a live XState actor handles them, where the pure System fails the call: an execution error (a step that throws, an action that fails) is recovered from through an active state’s onError (xstate.error.execution); a child that fails stops its own children and reports xstate.error.actor to its parent, and the call goes on; the root’s failure fails the call, the root keeping its snapshot in the error status.

Implementations§

Source§

impl<C, E> Actor<C, E>
where C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, E: EventType + Send + Sync,

Source

pub fn start( machine: Arc<Machine<C, E>>, now_ms: u64, ) -> Result<Self, SystemError>

Starts an actor at time now_ms.

Source

pub fn start_with( machine: Arc<Machine<C, E>>, options: InitOptions, ) -> Result<Self, SystemError>

Starts an actor with explicit system options (input, root id, registry key, execution id, time, step bound), observing every actor’s emitted events from the start when InitOptions::observe_system_emitted is set, so what actors emit while the system starts is collected too.

Source

pub fn restore( machine: Arc<Machine<C, E>>, data: &Value, ) -> Result<Self, SystemError>

Restores an actor from Actor::persist data. Runs no actions.

Source

pub fn restore_with( machine: Arc<Machine<C, E>>, data: &Value, options: RestoreOptions, ) -> Result<Self, SystemError>

Actor::restore with what a snapshot does not keep.

Source

pub fn send(&mut self, event: E, now_ms: u64) -> Result<(), SystemError>

Sends event to the root at now_ms (see Actor::send_json).

Source

pub fn send_json( &mut self, event: Value, now_ms: u64, ) -> Result<(), SystemError>

Sends a JSON event to the root at now_ms. When time has moved forward, timers due by now_ms fire first; a timer scheduled at the current time (a zero delay) fires on the next Actor::advance, as with XState’s SimulatedClock.

A lifecycle notification (xstate.done.actor, xstate.error.actor, xstate.snapshot.actor, xstate.done.state, xstate.error.execution) is not delivered: only the runtime sends those, and XState’s live actor takes one from the application as a dead letter.

Source

pub fn send_to( &mut self, address: &str, event: Value, now_ms: u64, ) -> Result<(), SystemError>

Sends a JSON event to any actor in the system by address (the root’s is its id; an invoked child’s is <parent>/<invoke id>), as Actor::send_json does for the root.

Source

pub fn advance(&mut self, now_ms: u64) -> Result<(), SystemError>

Fires every timer due at or before now_ms, chronologically. Each timer is its own step, as with a live XState actor: when a later timer fails, the effects of the earlier ones have already run.

Source

pub fn resolve_effect( &mut self, effect_id: &str, event: Option<Value>, ) -> Result<(), SystemError>

Delivers the result of pending async work (an @xstate.effect), such as { "type": "xstate.async.resolve", "data": ... }.

Source

pub fn pending_effects(&self) -> Vec<ExternalEffect>

External work waiting for the host.

Source

pub fn work(&self) -> Vec<Work>

The work the actor waits for, in the order it started: invoked work (@xstate.effect), which Input::Work settles resolved or rejected, and host actions (see crate::HostActions), which it settles done.

A host action stays listed until it is done, also when the actor that took it has stopped since, even in the very step that took it, so the host still does it: XState’s pure system API would cancel it.

Source

pub fn settle( &mut self, id: &str, outcome: Outcome, data: Option<Value>, ) -> Result<(), ApplyError>

Settles work the actor waits for (see Actor::work) at its current time: invoked work resolved or rejected, with data its output or error, or a host action done. A result of work the actor no longer waits for, as of work it cancelled, is a late result: it changes nothing. An outcome of the other kind of work is WORKFLOW_INVALID_WORK_RESULT, and changes nothing either. A failure of the machine as it takes the result is a rejection of the root’s error, the root left in error; Actor::apply ends the run in error of it instead, as it does of a result that puts the root in error with no failure of a step.

Source

pub fn max_timers(&self) -> usize

How many timers a time input of Actor::apply fires at most in a chunk of control inputs alone (DEFAULT_MAX_TIMERS until Actor::set_max_timers).

Source

pub fn set_max_timers(&mut self, max_timers: usize)

Sets how many timers a time input of Actor::apply fires at most in a chunk of control inputs alone, at least one, so a run far behind catches up in steps, each step’s time the last moment it reached. A run’s records depend on it, and a snapshot does not keep it: a host sets it on each actor it starts or restores, the same for the whole run, as the workflow contract’s maxTimers.

Source

pub fn apply(&mut self, batch: &[Value]) -> Result<Step, ApplyError>

Applies one chunk of inputs, in order, as the workflow contract’s engine does, and gives the step: the events the root emitted in the chunk (taken, as Actor::take_emitted takes them), the root, the time, the next deadline and the work the actor waits for.

  • An event is sent at the actor’s current time. An event that fails, the root failing on it, refuses the whole chunk as a rejection of the root’s error, { "message", "data"? }, and the actor is as it was before the chunk. So does an event to a run that is done, in error or stopped, which takes none (The run is done., The run is in error., The run is stopped.), and an event of a type that starts with xstate., which only XState itself sends.
  • A time or work input that fails, or that puts the root in error with no failure of a step (as invoked work rejected that no onError handles), is a fact, which is never refused: the run ends in error, the root’s status, with the root’s error, or the failure’s, as { "message", "data"? }. What the inputs before it gave stands, nothing of the failed input does, not even what it emitted, and no input after it applies; the step’s time is the time the run had reached before the failed input. The ended run keeps no timer and no invoked work, only the host actions still to do, and it persists and restores in error.
  • A run in error skips time, rejects events and still lets a host action go by done.
  • A time input moves the clock to now, a moment at a time, the timers due at one moment firing together; a now behind the clock leaves it where it is. In a chunk of control inputs alone it stops before a moment once it has fired Actor::max_timers timers, its time the last moment it reached; in a chunk with an event it fires every timer due, so no event applies at a time that lags.
  • A work input settles work of Actor::work (see Actor::settle): a late result changes nothing, and an outcome of the other kind of work refuses the chunk, WORKFLOW_INVALID_WORK_RESULT.

An input that is no input of the contract refuses the chunk before anything is applied (WORKFLOW_INVALID_INPUT), and an empty chunk gives the step as it is. The undo is a copy of the system as it was (System::try_clone), with the machine shared, taken once before the chunk and once before each time or work input after the first; an undo that cannot restore the system is WORKFLOW_ENGINE_FAILED. The run can’t go on after it: the actor is broken, and refuses every chunk after it with WORKFLOW_ENGINE_FAILED too.

use std::sync::Arc;
use serde_json::{json, Value};
use xmachines_runtime::{Actor, Machine, Registry};

let machine = Arc::new(Machine::<Value, Value>::from_json(
    &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
    &Registry::new(),
).unwrap());
let mut actor = Actor::start(machine, 0).unwrap();
let step = actor.apply(&[json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]).unwrap();
assert_eq!(step.root.value, json!("b"));
assert_eq!(step.time, 5);
assert!(actor.apply(&[json!({ "type": "go" }), json!({ "kind": "time", "now": 1.5 })]).is_err());
Source

pub fn is_broken(&self) -> bool

Whether a chunk failed with WORKFLOW_ENGINE_FAILED, so that Actor::apply refuses every chunk after it.

Source

pub fn stop(&mut self) -> Result<(), SystemError>

Stops the root and its children, as XState’s actor.stop().

Source

pub fn next_deadline(&self) -> Option<u64>

When the next timer is due, if any.

Source

pub fn status(&self) -> Status

Source

pub fn context(&self) -> Option<&C>

The root’s context; None when its start threw, as XState’s live actor then has none.

Source

pub fn output(&self) -> Option<&Value>

The actor’s output, once it is done.

Source

pub fn error(&self) -> Option<&Value>

The error of an actor in the error status.

Source

pub fn now(&self) -> u64

The system’s virtual time.

Source

pub fn value(&self) -> Option<Value>

XState’s nested state value, such as {"b": "b1"}; None when the root’s start threw, as XState’s live actor then has none.

Source

pub fn matches(&self, state: &str) -> bool

Whether a state is active: #id by state id, or a .-separated path of state keys from the root, such as "checkout.payment".

Source

pub fn check(&self, event: &E) -> Result<TransitionCheck, SystemError>

What the root would do with event, without taking it, as XState’s snapshot.check(event) (see TransitionCheck): accepted, unhandled, rejected with the reasons of each transition that rejects it, or partial. Guards and transition functions run as they would when the event is sent; no action runs, no timer fires and the actor is left as it is. A guard or a transition function that throws fails the check.

Source

pub fn check_json(&self, event: &Value) -> Result<TransitionCheck, SystemError>

Actor::check of a JSON event.

Source

pub fn can(&self, event: &E) -> Result<bool, SystemError>

Whether the root would take event now, as kit-workflow’s can: XState’s !isUnhandled(transition(...)). An active root selects a transition of it, any transition, also one with nothing to do ({}, a description alone) or one that rejects the event, which Actor::check calls unhandled or rejected. A guard that does not pass selects nothing. A transition of JSON selects by its guard alone: what it does, its context, actions and input, is not run, so one that would throw as it is taken is still taken; a transition function runs, as it decides. An event of a type that starts with xstate., which Actor::apply rejects, is never taken. Changes nothing.

Source

pub fn can_json(&self, event: &Value) -> Result<bool, SystemError>

Actor::can of a JSON event.

Source

pub fn has_tag(&self, tag: &str) -> bool

Whether any active state has this tag.

Source

pub fn configuration(&self) -> Vec<&str>

Ids of the active states, in configuration order.

Source

pub fn active_leaf_ids(&self) -> Vec<&str>

Ids of the active atomic and final states, in configuration order.

Source

pub fn children(&self) -> Vec<(&str, &str)>

The root’s invoked children: id and actor address.

Source

pub fn take_emitted(&mut self) -> Vec<Value>

Takes the events the root emitted since the last call.

Source

pub fn observe_system_emitted(&mut self)

Collects the events every actor in the system emits from now on, root and children alike, as XState’s system.onEmitted; read them with Actor::take_system_emitted. Off by default, so emissions are not copied when nobody reads them.

Source

pub fn unobserve_system_emitted(&mut self)

Stops collecting what Actor::observe_system_emitted started, as unsubscribing from XState’s system.onEmitted, and drops the events not taken yet.

Source

pub fn take_system_emitted(&mut self) -> Vec<(ActorRef, Value)>

Takes the events every actor emitted since the last call, in order, with the actor that emitted each. Empty unless observing, by Actor::observe_system_emitted or InitOptions::observe_system_emitted.

Source

pub fn take_logs(&mut self) -> Vec<Vec<Value>>

Takes the argument lists of the root’s @xstate.log actions.

Source

pub fn persist(&self) -> Value

The whole system snapshot (XState’s SystemSnapshot shape).

Source

pub fn persist_view(&self) -> SystemView<'_>

Actor::persist as a view that serializes to the same data without building it: write it straight into an encoding with serde.

Source

pub fn persist_compact(&self) -> SystemView<'_>

A smaller snapshot that Actor::restore restores to the same actor (see System::compact_view); not meant for XState’s own restore.

Source

pub fn machine(&self) -> &Arc<Machine<C, E>> ⓘ

Source

pub fn system(&self) -> &System

The underlying system, for access to children.

Source

pub fn system_logic(&self) -> &SystemLogic

The system’s definitions.

Trait Implementations§

Source§

impl<C, E> Debug for Actor<C, E>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<C, E> !RefUnwindSafe for Actor<C, E>

§

impl<C, E> !Sync for Actor<C, E>

§

impl<C, E> !UnwindSafe for Actor<C, E>

§

impl<C, E> Forget for Actor<C, E>

§

impl<C, E> Freeze for Actor<C, E>

§

impl<C, E> Move for Actor<C, E>

§

impl<C, E> Send for Actor<C, E>
where Arc<Machine<C, E>>: Send, Arc<dyn Logic>: Send, RawVecInner: Send, Arc<Vec<(String, Arc<dyn Logic>)>>: Send, &'static str: Send, String: Send, Arc<str>: Send, BoxRaw<str>: Send, BoxRaw<Value>: Send, BoxRaw<dyn AnySnapshot>: Send, RawTable<usize>: Send, Arc<dyn Fn() -> Result<(), String> + Send + Sync>: Send, BoxRaw<SystemError>: Send, BoxRaw<Scratch>: Send, BoxRaw<Vec<(ActorRef, Value)>>: Send,

§

impl<C, E> Unpin for Actor<C, E>
where Arc<Machine<C, E>>: Unpin, Arc<dyn Logic>: Unpin, *const u8 is !null: Unpin, Arc<Vec<(String, Arc<dyn Logic>)>>: Unpin, &'static str: Unpin, String: Unpin, Arc<str>: Unpin, Box<str>: Unpin, Box<Value>: Unpin, Box<dyn AnySnapshot>: Unpin, Arc<dyn Fn() -> Result<(), String> + Send + Sync>: Unpin, Box<SystemError>: Unpin, Box<Scratch>: Unpin, Box<Vec<(ActorRef, Value)>>: Unpin,

§

impl<C, E> UnsafeUnpin for Actor<C, E>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.