Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 3
Scheduling
The order in which work runs, admission, and faults.
When a reducer emits several things, or an answer arrives while other work is queued, what runs first? In threaded code it depends on timing. In causet a few rules fix it, the same in every run, and this page states them. They are what you need to read a trace, to know what State a reducer will see, and to understand why a run repeats exactly.
In short: the Store takes one input at a time, and everything that input causes runs before the next. Inside, work runs in the order it was emitted, and an Action's consequences run before whatever was emitted after it. Every Action is checked just before it runs, against the State of that moment; a refused one is skipped, not an error. A panicAn exceptionAn exception stops the Store.
The sections below give the details: root inputs, the order within one, admission, time, the observer callbacks, Events, faults, and bug reports.
open Causet
open Causet_guide.ShopRoot inputs
Work enters a Store in two ways, each a root input:
- an Action dispatched by the application:
Store::dispatch_toStore.dispatch_tostore.dispatchTo; - an Event taken from the bus by
Store::drain_eventsStore.drain_eventsstore.drainEvents.
A root input runs to completion, everything it causes included, before the call returns. There is no implicit yielding and no asynchronous reducer. A reducer, an Effect handler, an Event adapter, an Output lowerer or an observer that returns a promise faults the Store.
One FIFO per execution, drained depth first
A reducer appends what it emits to its own private FIFO, in exactly the order it emits, never grouped by category. When the reducer returns, the Store drains that FIFO from the front:
- A queued Action is checked for admission against the State and time of that moment. If admitted, it runs, with everything it causes, before the next item.
- A refused Action is skipped. It gets no execution ID and no ordinal;
observers are told of it once (
action_refusedaction_refusedactionRefused), and later items still run. - An Effect runs its handler at its exact position.
- An Action an Effect handler dispatches runs at once, with everything it causes, before the handler resumes.
So if a reducer emits Action A, Effect B and Action C, what A causes
runs before B, and B's handler (with what it dispatches) before
C. Each message type derives its message with
[@@deriving message], which names each kind after its constructor
(A_child is steps.a_child). A message is a union tagged by its
kind, so each value names its kind where it is made: { kind: "steps.a_child" }:
type step = Start | A | A_child | C | From_effect
[@@deriving message ~name:"steps.action"]
type b = B [@@deriving message ~name:"steps.effect"]
let steps : (unit, unit, step, b, never) Component.t =
Component.make ~name:"steps" ~actions:step_message ~effects:b_message
~outputs:Message.never
~reduce:(fun ctx step _ ->
match step with
| Start ->
Ctx.emit_action ctx A;
Ctx.emit_effect ctx B;
Ctx.emit_action ctx C
| A -> Ctx.emit_action ctx A_child
| A_child | C | From_effect -> ())
~handle:(fun ctx B _ -> ignore (Effect_ctx.dispatch ctx From_effect))
()use causet::*;
use causet::observers::TraceLog;
#[derive(Debug, Action)]
#[causet(type = "steps.action")]
enum Step { Start, A, AChild, C, FromEffect }
#[derive(Debug, Effect)]
#[causet(type = "steps.effect", kind = "steps.b")]
struct B;
struct Steps;
impl Component for Steps {
type State = ();
type Service = ();
type Action = Step;
type Effect = B;
type Output = Never;
fn reduce(ctx: ComponentContext<'_, Self>, step: Step, _: &ActionMeta) {
let mut out = ctx.into_emitter();
match step {
Step::Start => {
out.emit_action(Step::A);
out.emit_effect(B);
out.emit_action(Step::C);
}
Step::A => out.emit_action(Step::AChild),
Step::AChild | Step::C | Step::FromEffect => {}
}
}
fn handle(mut ctx: EffectContext<'_, Self>, _: B, _: &EffectMeta) {
ctx.dispatch(Step::FromEffect);
}
}
let (mut store, _sink) = Store::start::<Steps>((), (), StoreOptions::default()).unwrap();
let steps = store.mount(&root::<Steps>()).unwrap();
store.add_observer(TraceLog::new());
store.dispatch_to(&steps, Step::Start).unwrap();
let trace = store.observer::<TraceLog>().unwrap().entries();
let kinds: Vec<_> = trace.iter().map(|e| e.kind).collect();
assert_eq!(kinds, ["steps.start", "steps.a", "steps.a_child", "steps.b", "steps.from_effect", "steps.c"]);
// Every execution has its own ID, strictly increasing...
assert!(trace.windows(2).all(|w| w[0].id < w[1].id));
// ...and names the execution that caused it.
assert_eq!(trace[2].causal, trace[1].id); // AChild was emitted by A
assert_eq!(trace[4].causal, trace[3].id); // FromEffect was dispatched by Blet () =
let store, _sink = Store.start_exn steps ~state:() ~services:() in
let mount = Store.mount_exn store (Path.root steps) in
let log = Observe.Trace_log.create () in
Store.add_observer store (Observe.Trace_log.observer log);
ignore (Store.dispatch_exn store mount Start);
let trace = Array.of_list (Observe.Trace_log.entries log) in
assert (
Array.to_list (Array.map (fun (e : Observe.Trace_entry.t) -> e.kind) trace)
= [ "steps.start"; "steps.a"; "steps.a_child"; "steps.b"; "steps.from_effect"; "steps.c" ]);
(* Every execution has its own ID, strictly increasing... *)
Array.iteri (fun i (e : Observe.Trace_entry.t) -> if i > 0 then assert (trace.(i - 1).id < e.id)) trace;
(* ...and names the execution that caused it. *)
assert (trace.(2).causal = trace.(1).id) (* A_child was emitted by A *);
assert (trace.(4).causal = trace.(3).id) (* From_effect was dispatched by B *)import assert from "node:assert/strict";
import { component, message, rootPath, Store } from "causet";
import { TraceLog } from "causet/observers";
type Step =
| { readonly kind: "steps.start" }
| { readonly kind: "steps.a" }
| { readonly kind: "steps.a_child" }
| { readonly kind: "steps.c" }
| { readonly kind: "steps.from_effect" };
const step = message<Step>("steps.action");
type B = { readonly kind: "steps.b" };
const b = message<B>("steps.effect");
const steps = component<undefined>()({
name: "steps",
actions: step,
effects: b,
reduce(ctx, action) {
switch (action.kind) {
case "steps.start":
ctx.emitAction({ kind: "steps.a" });
ctx.emitEffect({ kind: "steps.b" });
ctx.emitAction({ kind: "steps.c" });
break;
case "steps.a":
ctx.emitAction({ kind: "steps.a_child" });
break;
default:
break;
}
},
handle(ctx) {
ctx.dispatch({ kind: "steps.from_effect" });
},
});
const { store } = Store.startOrThrow(steps, { state: undefined, services: undefined });
const mount = store.mountOrThrow(rootPath(steps));
const log = new TraceLog();
store.addObserver(log);
store.dispatchOrThrow(mount, { kind: "steps.start" });
const trace = log.entries;
assert.deepEqual(
trace.map((e) => e.kind),
["steps.start", "steps.a", "steps.a_child", "steps.b", "steps.from_effect", "steps.c"],
);
// Every execution has its own ID, strictly increasing...
assert.ok(trace.every((e, i) => i === 0 || (trace[i - 1]?.id ?? 0) < e.id));
// ...and names the execution that caused it.
assert.equal(trace[2]?.causal, trace[1]?.id); // a_child was emitted by a
assert.equal(trace[4]?.causal, trace[3]?.id); // from_effect was dispatched by bAdmission
An Action runs only if every check admits it, against the same State and time, in this order:
- its destination's State is available (a fallibleoptionaloptional lens can make it absent; see addressing);
- the root guard on its mount, if the application set one (below);
- the parent's admission guard for the slot, if the slot has one;
- the component's own
is_enabledis_enabledisEnabled, which admits by default.
The first check that refuses is the one observers are told of. The same checks run on every route: dispatched from outside, queued, sent to a child, dispatched by an Effect handler, lowered from an Output, adapted from an Event, or called inline, except that a root guard does not run on an inline call made below the root. A refusal at the root is not an error:
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
// An empty cart cannot check out.
let outcome = shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
assert_eq!(outcome, DispatchOutcome::Disabled);
assert_eq!(shop.store.executions(), 0);let () =
let shop = open_ () in
(* An empty cart cannot check out. *)
assert (Store.dispatch_to shop.store shop.cart_mount Checkout = Ok Disabled);
assert (Store.executions shop.store = 0)import assert from "node:assert/strict";
import { open } from "causet/guide";
const shop = open();
// An empty cart cannot check out.
const outcome = shop.store.dispatchTo(shop.cart, { kind: "cart.checkout" });
assert.deepEqual(outcome, { ok: true, outcome: "disabled" });
assert.equal(shop.store.executions, 0);Queued Actions are checked when they reach the front of the FIFO, never when emitted, so they see everything that ran before them. Write the enabling check first: it is where ordering, timeouts and stale input are decided, so the reducer can assume its Action was admitted.
Root guards
A component's own check reads its own State, and a slot guard its parent's.
A condition on the rest of the application's State is a root guard: the
application sets it on any mount below the root, by its path, as a function
of the whole State, the mount's own State, the Action and the time
(Registry::admitRegistry.admitregistry.admit).
let mut registry = Registry::<NodeState, ()>::new();
registry.root::<Node>();
// Sync, two levels down, may ask only a peer the node is connected to.
registry.admit(
root::<Node>().child(CHAIN).child(SYNC),
|node, _sync, action, _now| match action {
SyncAction::Request { peer } => node.peers.contains(peer),
},
);
let protocol = registry.freeze().unwrap();
let state = NodeState { peers: vec![1, 2], ..NodeState::default() };
let (mut store, _sink) = Store::open(&protocol, state, (), StoreOptions::default());
let sync = store.mount(&root::<Node>().child(CHAIN).child(SYNC)).unwrap();
let asked = store.dispatch_to(&sync, SyncAction::Request { peer: 1 }).unwrap();
assert_eq!(asked, DispatchOutcome::Executed);
let refused = store.dispatch_to(&sync, SyncAction::Request { peer: 9 }).unwrap();
assert_eq!(refused, DispatchOutcome::Disabled);
assert_eq!(store.state().chain.sync.asked, [1]);let () =
let reg = Registry.create () in
Registry.root reg node;
let sync_path = Path.child (Path.child (Path.root node) chain_slot) sync_slot in
(* Sync, two levels down, may ask only a peer the node is connected to. *)
Registry.admit reg sync_path (fun node _sync (Request { peer }) _now ->
List.mem peer node.peers);
let protocol = match Registry.freeze reg with Ok p -> p | Error _ -> assert false in
let state = { empty_node with peers = [ 1; 2 ] } in
let store, _sink = Store.open_protocol protocol ~state ~services:() in
let sync = Store.mount_exn store sync_path in
assert (Store.dispatch_to store sync (Request { peer = 1 }) = Ok Executed);
assert (Store.dispatch_to store sync (Request { peer = 9 }) = Ok Disabled);
assert ((Store.state store).chain.sync.asked = [ 1 ])import assert from "node:assert/strict";
import { Registry, rootPath, Store } from "causet";
const registry = new Registry<NodeState, undefined>();
registry.root(nodeRoot);
// Sync, two levels down, may ask only a peer the node is connected to.
registry.admit(rootPath(nodeRoot).child(chainSlot).child(syncSlot), (node, _sync, action) => {
switch (action.kind) {
case "sync.request":
return node.peers.includes(action.peer);
}
});
const protocol = registry.freezeOrThrow();
const state: NodeState = { peers: [1, 2], chain: { sync: { asked: [] } } };
const { store } = Store.open(protocol, { state, services: undefined });
const syncMount = store.mountOrThrow(rootPath(nodeRoot).child(chainSlot).child(syncSlot));
const asked = store.dispatchTo(syncMount, { kind: "sync.request", peer: 1 });
assert.deepEqual(asked, { ok: true, outcome: "executed" });
const refused = store.dispatchTo(syncMount, { kind: "sync.request", peer: 9 });
assert.deepEqual(refused, { ok: true, outcome: "disabled" });
assert.deepEqual(store.state.chain.sync.asked, [1]);A root guard checks every Action that enters its mount: one the Store
admits there to start an execution, dispatched from outside, queued, adapted
from an Event, lowered from an Output or dispatched by an Effect handler. It
reads the State as it is when the Action runs. It also checks the root's own
inline calls, since the root holds the whole State. An inline call made
below the root does not enter the mount: the child runs inside its caller's
execution without the root guard, so the caller takes on what it checks.
Observers are told which inline calls skipped one:
InlineCall::root_guard_skippedthe inline call's root_guard_skippedthe inline call's rootGuardSkipped.
So a parent that forwards an Action to its child with
to_childCtx.to_childctx.toChild has it checked by the child's root guard as it
enters the child. A parent below the root that forwards it inline, to act on
the result at once, skips the child's root guard: the condition is then
checked where the Action entered, on the parent's own Action, by the
parent's root guard, which sees the wrapping Action. The two guards can
share one function of the whole State.
A panicexceptionexception in a root guard faults the Store, like one anywhere in a
root input; on an inline call it first unwindspropagatespropagates through
reduce_childCtx.reduce_childreduceChild to the caller, as any panicexceptionexception in an inline
call does.
Freezing the Registry reports a root guard whose path names no mount or
another component, one on the root itself, and a second one on the same
mount. A Store with root guards is opened from that Protocol with
Store::openStore.open_protocolStore.open
(assembling by hand).
Time
Every execution reads the Store's ClockCauset.ClockClock as
it starts. Its time is max(previous, now)max previous nowMath.max(now, previous),
so times never go back, whatever the clock does; executions in the same
instant share it. Its ID is apart from time: the Store numbers executions 1,
2, 3, ... as they start, so IDs order the run exactly. A root Action reads
the clock once, at dispatch, and is admitted at that time; a queued Action is
admitted at the time of the execution before it. Reducers read the time from
their metadata (meta.time), never from the system clock (see
determinism).
Lifecycle
Observers (ObserverCauset.Observe.tObserver, whose methods are all optional) are called at each
boundary:
Action start Effect start Event start
reducer handler adapter
inline child: inline action Effect finish Event finish
Action finish drain its FIFO
drain its FIFO Event settled
Action settled
Settled means everything the Action or Event caused has finished or been refused.
Two calls fall outside an execution's own boundaries. action_refusedaction_refusedactionRefused
tells of an Action refused at admission, wherever it was sent from (a root
dispatch, an Effect handler, a queue, or an inline call), with what refused
it and the execution that sent it. inline_actioninline_actioninlineAction tells of a child's Action
admitted inline (reduce_childCtx.reduce_childctx.reduceChild), just
before its reducer runs within its parent's execution, at its parent's
time: it has no action_startaction_startactionStart of its own. Both see the payload, and
neither makes an execution, so they change no ID, ordinal or time. A Store with no observers
skips them, as it skips every callback, and then reads no kind for them.
Events
Store::drain_eventsStore.drain_eventsstore.drainEvents takes up to a
given number of Events from the bus, each as its own root input: its adapter
runs, and the Actions it emits drain fully before the next Event. Events
sent from the Store's own thread (by Effect handlers) come before those sent
by worker threadsfrom the Store's own thread (by Effect handlers) come before those sent
by worker threadsduring an execution (by Effect handlers) come before those sent at any
other time (see running). Draining is the application's call, typically in its
driver loop:
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 500 }).unwrap();
// The gateway has answered; the answer waits on the bus until drained.
assert_eq!(shop.store.state().payments.pending.len(), 1);
assert_eq!(shop.store.drain_events(16).unwrap(), 1);
assert_eq!(shop.store.state().payments.declined, [500]);let () =
let shop = open_ () in
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 500 }));
(* The gateway has answered; the answer waits on the bus until drained. *)
assert (Pending.cardinal (Store.state shop.store).payments.pending = 1);
assert (Store.drain_events shop.store 16 = Ok 1);
assert ((Store.state shop.store).payments.declined = [ 500 ])import assert from "node:assert/strict";
import { open } from "causet/guide";
const shop = open();
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 500 });
// The gateway has answered; the answer waits on the bus until drained.
assert.equal(shop.store.state.payments.pending.size, 1);
assert.deepEqual(shop.store.drainEvents(16), { ok: true, delivered: 1 });
assert.deepEqual(shop.store.state.payments.declined, [500]);Faults
A panicAn exceptionAn exception anywhere in a root input's work (an
enabling check, a guard, a reducer, an Effect handler, an adapter, a
lowerer) is caught where the root input entered. It faults the Store: the
call returns DispatchError::FaultedError (Faulted message){ ok: false, error: { kind: "faulted", message } },
every later call returns it too, observers are told, and nothing is rolled
back. Nothing that was interrupted resumes.
An Effect handler can catch the paniccatch the exceptioncatch the exception
of an Action it dispatched synchronously, but that does not undo the fault.
The Store faults as the panicexceptionexception leaves the
dispatch: the fault is the first one, with its own message and place, the
bus closes, and observers are told once. The handler finds the Store
faulted: a later dispatch runs nothing and returns
DispatchOutcome::FaultedFaulted"faulted", and as the handler
returns, the rest of the root input is dropped. The call that started the
root input returns the fault.
type fragile = Fine | Break [@@deriving message ~name:"fragile.action"]
let glass : (int, unit, fragile, never, never) Component.t =
Component.make ~name:"glass" ~actions:fragile_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx action _ ->
Ctx.update ctx (( + ) 1);
match action with Break -> failwith "broke" | Fine -> ())
()use causet::*;
#[derive(Debug, Action)]
#[causet(type = "fragile.action")]
enum Fragile { Fine, Break }
struct Glass;
impl Component for Glass {
type State = u32;
type Action = Fragile;
type Output = Never;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, action: Fragile, _: &ActionMeta) {
*ctx.state_mut() += 1;
if let Fragile::Break = action {
panic!("broke");
}
}
}
let (mut store, _sink) = Store::start::<Glass>(0u32, (), StoreOptions::default()).unwrap();
let glass = store.mount(&root::<Glass>()).unwrap();
assert_eq!(store.dispatch_to(&glass, Fragile::Break), Err(DispatchError::Faulted("broke".into())));
assert_eq!(store.dispatch_to(&glass, Fragile::Fine), Err(DispatchError::Faulted("broke".into())));
assert_eq!(*store.state(), 1); // the reducer's change before the panic stays
assert_eq!(store.fault(), Some("broke"));let () =
let store, _sink = Store.start_exn glass ~state:0 ~services:() in
let mount = Store.mount_exn store (Path.root glass) in
assert (Store.dispatch_to store mount Break = Error (Faulted "broke"));
assert (Store.dispatch_to store mount Fine = Error (Faulted "broke"));
assert (Store.state store = 1) (* the reducer's change before the raise stays *);
assert (Store.fault store = Some "broke")import assert from "node:assert/strict";
import { component, message, rootPath, Store } from "causet";
type Fragile = { readonly kind: "fragile.fine" } | { readonly kind: "fragile.break" };
const fragile = message<Fragile>("fragile.action");
const glass = component<number>()({
name: "glass",
actions: fragile,
reduce(ctx, action) {
ctx.update((n) => n + 1);
if (action.kind === "fragile.break") throw new Error("broke");
},
});
const { store } = Store.startOrThrow(glass, { state: 0, services: undefined });
const mount = store.mountOrThrow(rootPath(glass));
const faulted = { ok: false, error: { kind: "faulted", message: "broke" } };
assert.deepEqual(store.dispatchTo(mount, { kind: "fragile.break" }), faulted);
assert.deepEqual(store.dispatchTo(mount, { kind: "fragile.fine" }), faulted);
assert.equal(store.state, 1); // the reducer's change before the throw stays
assert.equal(store.fault, "broke");Expected failures, such as a declined payment or an unreachable peer, are
not faults: Services report them as Events, and reducers handle them like
any other fact. Built with panic = "abort", a panic cannot be
caught: the process ends.
Bug reports
Between an expected failure and a fault sits the bug: a state the code
believes impossible, such as an index naming an item the list does not have.
PanickingRaisingThrowing would stop a production node for one bug;
ignoring it would hide it. bug_condition!Bug.conditionbugCondition
reports it and returns, and the caller carries on with a fallback it
chooses, the same in every build:
module String_map = Map.Make (String)
type shelf = {
titles : string array;
index : int String_map.t; (** Positions in [titles], by title. *)
}
(* A helper with no context: the report finds its Store by itself. *)
let take shelf title =
match String_map.find_opt title shelf.index with
| None -> (shelf, None)
| Some at ->
let shelf = { shelf with index = String_map.remove title shelf.index } in
if at >= Array.length shelf.titles then (
Bug.condition __POS__
~fields:[ ("title", title); ("at", string_of_int at) ]
"the index names a title the shelf does not have";
(shelf, None) (* the fallback: as if it were not there *))
else (shelf, Some shelf.titles.(at))
type shelf_action = Take of string [@@deriving message ~name:"shelf.action"]
let shelves : (shelf, unit, shelf_action, never, never) Component.t =
Component.make ~name:"shelves" ~actions:shelf_action_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx (Take title) _ -> Ctx.update ctx (fun s -> fst (take s title)))
()use causet::*;
use causet::observers::{BugLog, Phase};
#[derive(Default)]
struct Shelf {
titles: Vec<String>,
/// Positions in `titles`, by title.
index: std::collections::BTreeMap<String, usize>,
}
impl Shelf {
/// A helper with no context: the report finds its Store by itself.
fn take(&mut self, title: &str) -> Option<String> {
let at = self.index.remove(title)?;
let Some(found) = self.titles.get(at) else {
bug_condition!(title = title, at = at; "the index names a title the shelf does not have");
return None; // the fallback: as if it were not there
};
Some(found.clone())
}
}
#[derive(Debug, Action)]
#[causet(type = "shelf.action", kind = "shelf.take")]
struct Take(String);
struct Shelves;
impl Component for Shelves {
type State = Shelf;
type Action = Take;
type Output = Never;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, Take(title): Take, _: &ActionMeta) {
ctx.state_mut().take(&title);
}
}
let mut broken = Shelf::default();
broken.index.insert("Dune".into(), 3);
let (mut store, _sink) = Store::start::<Shelves>(broken, (), StoreOptions::default()).unwrap();
store.add_observer(BugLog::new());
let shelves = store.mount(&root::<Shelves>()).unwrap();
// The Store keeps running: the fallback ran.
assert_eq!(store.dispatch_to(&shelves, Take("Dune".into())), Ok(DispatchOutcome::Executed));
let [report] = store.observer::<BugLog>().unwrap().reports() else { panic!("one report") };
let place = report.place.as_ref().unwrap();
assert_eq!((place.phase, place.path.as_ref()), (Phase::Reducer, "/"));
assert_eq!(report.fields[1], ("at".into(), "3".into()));let () =
let broken = { titles = [||]; index = String_map.singleton "Dune" 3 } in
let store, _sink = Store.start_exn shelves ~state:broken ~services:() in
let mount = Store.mount_exn store (Path.root shelves) in
let log = Observe.Bug_log.create () in
Store.add_observer store (Observe.Bug_log.observer log);
(* The Store keeps running: the fallback ran. *)
assert (Store.dispatch_to store mount (Take "Dune") = Ok Executed);
match Observe.Bug_log.reports log with
| [ { place = Some { phase = Reducer; path = "/"; _ }; fields; _ } ] ->
assert (List.assoc "at" fields = "3")
| _ -> assert falseimport assert from "node:assert/strict";
import { bugCondition, component, message, rootPath, SortedMap, Store } from "causet";
import { BugLog } from "causet/observers";
interface Shelf {
readonly titles: readonly string[];
/** Positions in `titles`, by title. */
readonly index: SortedMap<string, number>;
}
/** A helper with no context: the report finds its Store by itself. */
function take(shelf: Shelf, title: string): readonly [Shelf, string | undefined] {
const at = shelf.index.get(title);
if (at === undefined) return [shelf, undefined];
const rest = { ...shelf, index: shelf.index.delete(title) };
const found = rest.titles[at];
if (found === undefined) {
bugCondition("the index names a title the shelf does not have", { title, at });
return [rest, undefined]; // the fallback: as if it were not there
}
return [rest, found];
}
type Take = { readonly kind: "shelf.take"; readonly title: string };
const takeAction = message<Take>("shelf.action");
const shelves = component<Shelf>()({
name: "shelves",
actions: takeAction,
reduce(ctx, { title }) {
ctx.update((shelf) => take(shelf, title)[0]);
},
});
const broken: Shelf = { titles: [], index: SortedMap.empty<string, number>().set("Dune", 3) };
const { store } = Store.startOrThrow(shelves, { state: broken, services: undefined });
const log = new BugLog();
store.addObserver(log);
const mount = store.mountOrThrow(rootPath(shelves));
// The Store keeps running: the fallback ran.
const outcome = store.dispatchTo(mount, { kind: "shelf.take", title: "Dune" });
assert.deepEqual(outcome, { ok: true, outcome: "executed" });
assert.equal(log.reports.length, 1);
const [report] = log.reports;
assert.equal(report?.place?.phase.kind, "reducer");
assert.equal(report?.place?.path, "/");
assert.deepEqual(report?.fields[1], ["at", "3"]);- A report has a place: the phase (admission, reducer, Effect
handler, adapter, observer), the execution it happened in (for an
admission, the execution that queued or dispatched the Action), the
component whose code made it, and its number in the run. Reports reach
observers (
Observer::bugbugbug) in the order they happened: a handler's report made before it dispatches an Action comes before that Action. - Nothing is cancelled. A report does not stop the reducer, roll back what it changed, or stop a parent that called the reporting child inline. The fallback is the safeguard, so choose it as carefully as the check; where you can, check before changing State, so a fallback finds nothing half done.
- Tests check reports after the run with
BugLog:assert_none()for ordinary tests,assert_messages(...)for tests of a recoveryCauset.Observe.Bug_log; aCauset_test.Nodefails on any report unless toldallow_bugsBugLog:assertNone()for ordinary tests,assertMessages([...])for tests of a recovery; aNodeofcauset/testfails on any report unless toldallowBugs(). The run itself never panicsraisesthrows on a report, so tests exercise the fallback production takes. A component tested alone keeps its reports in itsHarnessCauset.HarnessHarness(bugReports). - Outside a Store (a Service's thread, a plain unit test of a helper),
a report goes to the hook set by
set_bug_hookBug.set_hooksetBugHook, or to standard error. - Use an assertion instead when continuing would break State's integrity: a panican exceptionan exception faults the Store.