Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 2
Authority
What each kind of code may read, change and start.
Many bugs in asynchronous code come from code doing more than its job: a callback that changes State another part thought it owned, a timer that starts I/O nobody tracks. Causet gives each kind of code exactly one job. A reducer decides and changes State; an Effect handler starts I/O; an adapter translates a Service's answer; a lowerer translates a child's report. Each gets a context that can do its job and nothing else, so most overstepping is a compile errortype errortype error rather than a race found in production, and the order inside a reducer is checked as it runs, and the order inside a reducer is checked as it runs.
This page goes through each kind of code: what it may read, what it may change, and what it may start.
The components talk only through four kinds of message, each with one producer and one handler:
| Message | Meaning | Produced by | Handled by |
|---|---|---|---|
| Action | A request to examine and maybe change State. | The Store's caller, reducers, Effect handlers, Event adapters, Output lowerers. | The component's enabling check, then its reducer. Only reducers change State. |
| Effect | A command for a Service. | Reducers only. | The component's Effect handler. |
| Event | A fact from outside: a Service's answer, a network message. | Services, through the Event bus. | The component's adapter, which turns it into Actions. |
| Output | A fact a child reports to its parent. | Reducers. | The parent's lowerer, which turns it into parent Actions. |
Action -> reducer -> Effect -> Service (any thread) -> Event bus
-> drain_events -> adapter -> Action -> reducer
child reducer -> Output -> parent's lowerer -> parent Action
The examples on these pages use
causet::guide::shopCauset_guide.Shopcauset/guide: a cart, a payment
component and a gateway Service.
open Causet
open Causet_guide.ShopReducers: change State first, then emit
A reducer receives a ComponentContext. It can change its component's
State, make request IDs and call children inline. Then it trades the
context for a ComponentEmitter, which emits Actions, Effects, Outputs and
queued child sends. No API hands out both at once, so nothing a reducer
emits can depend on State it changes afterwards.
A reducer receives a Causet.Ctx.t. It can change its component's State,
make request IDs and call children inline; then it emits Actions, Effects,
Outputs and queued child sends. Once it has emitted, its State is
read-only: a change after an emission raises, and faults the Store. So
nothing a reducer emits can depend on State it changes afterwards.
A reducer receives a Ctx. It can read ctx.state and set a new one
(set, update; State is immutable, and a child's is written back
through its lens), make request IDs and call children inline; then it
emits Actions, Effects, Outputs and queued child sends. Once it has
emitted, its State is read-only: a change after an emission throws, and
faults the Store. So nothing a reducer emits can depend on State it
changes afterwards.
A reducer can be run on its own with a HarnessCauset.HarnessHarness:
no Store, no Services, its emissions returned in order.
Harness::dispatchHarness.dispatchharness.dispatch runs the enabling
check first, as a Store does, and returns
Err(Disabled)Error `Disabled{ ok: false, error: "disabled" } for a refusal;
atHarness.atharness.at sets the time, and
with_sessionHarness.create ~sessionnew Harness({ session }) the session, to
start from a fixture's.
use causet::guide::shop::*;
use causet::{Emission, Harness};
let mut harness = Harness::<Payments>::new();
let mut state = PaymentsState::default();
let emissions = harness.reduce(&mut state, PaymentsAction::Charge { amount: 30 });
// It remembered the request, then emitted the Effect that carries it.
let (request, amount) = state.pending.iter().next().unwrap();
assert_eq!(*amount, 30);
assert!(matches!(
emissions.as_slice(),
[Emission::Effect(PaymentsEffect::Charge { request: r, amount: 30 })] if *r == request
));let () =
let harness = Harness.create () in
let state = { pending = Pending.empty; paid = []; declined = [] } in
let state, emissions = Harness.reduce harness payments state (Charge { amount = 30 }) in
(* It remembered the request, then emitted the Effect that carries it. *)
match (Pending.bindings state.pending, emissions) with
| [ (request, 30) ], [ Emit_effect (Charge_effect { request = r; amount = 30 }) ] ->
assert (Request_id.equal r request)
| _ -> assert falseimport assert from "node:assert/strict";
import { Harness } from "causet";
import { empty, payments } from "causet/guide";
const harness = new Harness();
const { state, emissions } = harness.reduce(payments, empty.payments, {
kind: "payments.charge",
amount: 30,
});
// It remembered the request, then emitted the Effect that carries it.
const [entry] = state.pending.entries();
assert.ok(entry !== undefined);
const [request, amount] = entry;
assert.equal(amount, 30);
assert.deepEqual(emissions, [
{ kind: "effect", effect: { kind: "payments.charge", request, amount: 30 } },
]);Once the emitter existsit has emittedit has emitted, State is out of reach:
use causet::guide::shop::*;
fn reduce(mut ctx: ComponentContext<'_, Cart>) {
let mut out = ctx.into_emitter();
ctx.state_mut().total = 0; // `ctx` was consumed by `into_emitter`
out.emit_output(CartOutput::CheckedOut { total: 0 });
}# let late =
Component.make ~name:"late" ~actions:cart_action_message ~effects:Message.never
~outputs:cart_output_message
~reduce:(fun ctx _ _ ->
Ctx.emit_output ctx (Checked_out { total = 0 });
Ctx.set_state ctx { items = []; total = 0 })
()
in
Harness.reduce (Harness.create ()) late { items = []; total = 0 } Checkout;;
Exception:
Invalid_argument "causet: set_state after the reducer started emitting".import assert from "node:assert/strict";
import { component, Harness } from "causet";
import { type CartState, cartAction, cartOutput, empty } from "causet/guide";
const late = component<CartState>()({
name: "late",
actions: cartAction,
outputs: cartOutput,
reduce(ctx) {
ctx.emitOutput({ kind: "cart.checked_out", total: 0 });
ctx.set({ items: [], total: 0 });
},
});
const reduce = () => new Harness().reduce(late, empty.cart, { kind: "cart.checkout" });
assert.throws(reduce, { message: "causet: set after the reducer started emitting" });A component emits only its own messages:
emit_actionCtx.emit_actionctx.emitAction takes its own Action type,
and to_childCtx.to_childctx.toChild reaches only the children it
declared (see addressing).
# let wrong =
Component.make ~name:"wrong" ~actions:cart_action_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx _ _ -> Ctx.emit_action ctx (Charge { amount = 1 }))
()
in
ignore wrong;;
Line 4, characters 52-58:
Error: This variant expression is expected to have type cart_action
There is no constructor Charge within type cart_actionimport { component } from "causet";
import { type CartState, cartAction } from "causet/guide";
export const wrong = component<CartState>()({
name: "wrong",
actions: cartAction,
// error: Type '"payments.charge"' is not assignable to type '"cart.add" | "cart.checkout"'.
reduce: (ctx) => ctx.emitAction({ kind: "payments.charge", amount: 1 }),
});Enabling checks and guards: read only
Component::is_enabledA component's is_enabledA component's isEnabled, a
slot's admission guard and a root guard are plain functions of State, the
Action and the time. They get no context: they cannot change State, call a Service or
emit. They decide whether an Action runs at all (see
scheduling).
use causet::guide::shop::*;
use causet::Harness;
let mut harness = Harness::<Cart>::new();
let empty = CartState::default();
assert!(!harness.is_enabled(&empty, &CartAction::Checkout));let () = assert (not (Harness.is_enabled (Harness.create ()) cart { items = []; total = 0 } Checkout))import assert from "node:assert/strict";
import { Harness } from "causet";
import { cart, empty } from "causet/guide";
assert.ok(!new Harness().isEnabled(cart, empty.cart, { kind: "cart.checkout" }));Effect handlers: Services, not State
An Effect handler gets an
EffectContextCauset.Effect_ctx.tEffectCtx: its component's
State to read (an OptionoptionS | undefined, since it may be gone by
then), its Service to use, and
dispatchEffect_ctx.dispatchctx.dispatch for an Action that must
run right now, before the handler goes on. It cannot change State and
cannot emit Effects: a reducer decides every Effect.
use causet::guide::shop::*;
fn handle(mut ctx: EffectContext<'_, Payments>) {
ctx.state_mut(); // handlers read State; only reducers change it
}# fun ctx -> Effect_ctx.set_state ctx empty;;
Line 1, characters 12-32:
Error: Unbound value Effect_ctx.set_stateimport type { EffectCtx } from "causet";
import {
empty,
type Gateway,
type PaymentsAction,
type PaymentsEffect,
type PaymentsState,
} from "causet/guide";
type Context = EffectCtx<PaymentsState, Gateway, PaymentsAction, PaymentsEffect, never>;
export function handle(ctx: Context): void {
// error: Property 'set' does not exist: handlers read State; only reducers change it
ctx.set(empty.payments);
}A Service is the only place for I/O: storage, network, threads. It never
touches State. It answers by publishing Events through a
ReplyCauset.Reply.tReply the handler gave it, from any
thread, from any thread, at once or later, from a promise or an I/O callback.
Adapters and lowerers: Actions only
An Event adapter(Adapts::adapt) and an Output lowerer get
an ActionPorta Causet.Port.ta Port, which emits Actions and
nothing else. If an Event needs more I/O, the Action it becomes emits an
Effect in the usual way.
use causet::guide::shop::*;
fn adapt(event: Charged, port: &mut ActionPort<'_, Payments>) {
port.emit_effect(PaymentsEffect::Charge { request: event.request, amount: 1 });
}# fun port (_ : charged) -> Port.emit_effect port (Charge_effect { request = Obj.magic 0; amount = 1 });;
Line 1, characters 27-43:
Error: Unbound value Port.emit_effectimport type { Port } from "causet";
import type { Charged, PaymentsAction } from "causet/guide";
export function adapt(event: Charged, port: Port<PaymentsAction>): void {
// error: Property 'emitEffect' does not exist on type 'Port<PaymentsAction>'
port.emitEffect({ kind: "payments.charge", request: event.request, amount: 1 });
}From outside the Store
The application's own code can do two things: dispatch an Action to a mount, and send an Event to a mount through the bus. Nothing outside a reducer can start an Effect.
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
let outcome = shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 7 }).unwrap();
assert_eq!(outcome, DispatchOutcome::Executed);let () =
let shop = open_ () in
assert (Store.dispatch_to shop.store shop.payments_mount (Charge { amount = 7 }) = Ok Executed)import assert from "node:assert/strict";
import { open } from "causet/guide";
const shop = open();
const result = shop.store.dispatchTo(shop.payments, { kind: "payments.charge", amount: 7 });
assert.deepEqual(result, { ok: true, outcome: "executed" });