Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 4
Addressing
Mounts, paths, child slots, Outputs and replies, and where context and Effects belong.
As an application grows, you want to write a component once and use it in several places: a counter under two parents, a P2P component inside a node. And you want each copy kept apart, with its own State, its own requests and its own answers. This page explains how components nest and how messages find their way: how a parent calls a child, how a child reports back without knowing its parent, how a Service's answer returns to the copy that asked, and where an Effect should live.
Components form a tree. A component is written once and mounted wherever a parent declares a slot for it; each mount has its own State (projected from its parent's by a lens), its own Service (likewise) and its own identity. Messages travel only along the tree: a parent calls its declared children, a child reports to its parent with Outputs, and Services answer the mount that asked.
Paths and instance identity
The root is mounted at /. A slot named cart under it is /cart; a
component mounted at two slots is two mounts with two paths. Each mount's
InstanceIdinstance IDInstanceId, a bigint, is the 64-bit xxh3 hash (seed 0)
of its path: the same in every run and every build, and the same in all three ports, so it can be logged, stored and carried in messages. Two paths that
hash alike are refused when the Registry is frozen.
From outside the Store, a mount is reached through a typed path built from
slots, resolved once into a MountCauset.mountMount: by the Store,
store.mount(&path)Store.mount store pathstore.mount(path), or by the Protocol it runs, as here:
use causet::guide::shop::*;
use causet::root;
let protocol = protocol();
let cart: Mount<Cart> = protocol.resolve(&root::<ShopRoot>().child(CART)).unwrap();
assert_eq!(protocol.path_of(&cart), "/cart");
// A Mount<Cart> accepts only CartActions: the type comes from the slot.open Causet
open Causet_guide.Shop
let () =
let protocol = protocol () in
let cart : (cart_state, unit, cart_action, never, cart_output) mount =
Protocol.resolve_exn protocol (Path.child (Path.root shop_root) cart_slot)
in
assert (Protocol.path_of protocol cart = "/cart")
(* A cart mount accepts only cart actions: the type comes from the slot. *)import assert from "node:assert/strict";
import { type Mount, rootPath } from "causet";
import { type cart, cartSlot, protocol, shopRoot } from "causet/guide";
const proto = protocol();
const cartMount: Mount<typeof cart> = proto.resolveOrThrow(rootPath(shopRoot).child(cartSlot));
assert.equal(proto.pathOf(cartMount), "/cart");
// A Mount<typeof cart> accepts only cart Actions: the type comes from the slot.A mount belongs to the Protocol that resolved it. Any Store built from that Protocol accepts it, and every other Store refuses it:
use causet::guide::shop::*;
use causet::{DispatchError, root};
let mut shop = Shop::open(StoreOptions::default());
let elsewhere = protocol(); // frozen separately: another Protocol
let foreign = elsewhere.resolve(&root::<ShopRoot>().child(CART)).unwrap();
let refused = shop.store.dispatch_to(&foreign, CartAction::Checkout);
assert_eq!(refused, Err(DispatchError::ForeignMount));let () =
let shop = open_ () in
let elsewhere = protocol () (* frozen separately: another Protocol *) in
let foreign = Protocol.resolve_exn elsewhere (Path.child (Path.root shop_root) cart_slot) in
assert (Store.dispatch_to shop.store foreign Checkout = Error Foreign_mount)import assert from "node:assert/strict";
import { rootPath } from "causet";
import { cartSlot, open, protocol, shopRoot } from "causet/guide";
const shop = open();
const elsewhere = protocol(); // frozen separately: another Protocol
const foreign = elsewhere.resolveOrThrow(rootPath(shopRoot).child(cartSlot));
const refused = shop.store.dispatchTo(foreign, { kind: "cart.checkout" });
assert.deepEqual(refused, { ok: false, error: { kind: "foreignMount" } });Child slots: inline and queued calls
A component declares each child as a slot,
a typed constant Child<Parent, Child>a value made by Child.makea Child<P, C> made by child<P>()(name, component),
and binds it in its own register: the State lens, the Service
lensprojectionprojection if the child has Effects, an optional
admission guard, and an Output lowerer if the child has Outputs. The slot's
type names its parent, so only the declaring component can use it.
In TypeScript the slot's type names its parent's State: another component
of the same State type also accepts it, and using it where it is not bound
throws, which faults the Store.
A reducer then calls a child in one of two ways:
- Queued,
out.to_child(SLOT, action), from the emitterCtx.to_child ctx slot action, an emissionctx.toChild(slot, action), an emission: the ordinary way. The Action joins the FIFO and runs as its own execution when its turn comes, admitted by every check on its way in. - Inline,
ctx.reduce_child(SLOT, action)Ctx.reduce_child ctx slot actionctx.reduceChild(slot, action), for a parent that must act on the result in the same execution, while it still changes State. The child's checks and reducer run right there, inside the parent's execution, and the call reports whether the child ran. The parent carries on afterwards, knowing the result. The child's slot guard and own check run as on any route; a root guard runs only when the root itself is the caller (see admission), so a parent below the root that calls inline takes on what the child's root guard checks.
use causet::*;
#[derive(Debug, Action)]
#[causet(type = "counter.action", kind = "counter.inc")]
struct Inc;
/// A reusable leaf, mounted twice below.
struct Counter;
impl Component for Counter {
type State = u32;
type Action = Inc;
type Output = Never;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, _: Inc, _: &ActionMeta) {
*ctx.state_mut() += 1;
}
}
struct Pair;
const LEFT: Child<Pair, Counter> = Child::new("left");
const RIGHT: Child<Pair, Counter> = Child::new("right");
#[derive(Default)]
struct PairState {
open: bool,
left: u32,
/// Absent until created: a fallible lens, `right?`.
right: Option<u32>,
left_refused: u32,
}
#[derive(Debug, Action)]
#[causet(type = "pair.action")]
enum PairAction { Open, AddRight, Bump }
/// The parent's guard on LEFT: whatever the route, nothing reaches the left
/// counter while the pair is closed.
fn only_when_open(parent: &PairState, _: &Inc, _now: Timestamp) -> bool {
parent.open
}
impl Component for Pair {
type State = PairState;
type Action = PairAction;
type Output = Never;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, action: PairAction, _: &ActionMeta) {
match action {
PairAction::Open => ctx.state_mut().open = true,
PairAction::AddRight => ctx.state_mut().right = Some(0),
PairAction::Bump => {
// Inline: runs now, and the parent learns the outcome.
if ctx.reduce_child(LEFT, Inc) == ChildOutcome::Refused {
ctx.state_mut().left_refused += 1;
}
// Queued: runs after this reducer, as its own execution.
ctx.into_emitter().to_child(RIGHT, Inc);
}
}
}
fn register(r: &mut ComponentRegistry<'_, Self>) {
r.child(LEFT, lens!(PairState => left)).admit(only_when_open).bind();
r.child(RIGHT, lens!(PairState => right?)).bind();
}
}
let (mut store, _sink) = Store::start::<Pair>(PairState::default(), (), StoreOptions::default()).unwrap();
let pair = store.mount(&root::<Pair>()).unwrap();
let left = store.mount(&root::<Pair>().child(LEFT)).unwrap();
let right = store.mount(&root::<Pair>().child(RIGHT)).unwrap();
// Closed, and no right counter yet: both calls are refused.
store.dispatch_to(&pair, PairAction::Bump).unwrap();
assert_eq!((store.state().left, store.state().right, store.state().left_refused), (0, None, 1));
// The guard holds on every route, not only through the parent's reducer.
assert_eq!(store.dispatch_to(&left, Inc), Ok(DispatchOutcome::Disabled));
store.dispatch_to(&pair, PairAction::Open).unwrap();
store.dispatch_to(&pair, PairAction::AddRight).unwrap();
store.dispatch_to(&pair, PairAction::Bump).unwrap();
store.dispatch_to(&right, Inc).unwrap();
assert_eq!((store.state().left, store.state().right), (1, Some(2)));
// One component, two mounts, two identities.
assert_eq!(store.protocol().path_of(&left), "/left");
assert_ne!(store.protocol().instance_of(&left), store.protocol().instance_of(&right));type inc = Inc [@@deriving message ~name:"counter.action"]
(* A reusable leaf, mounted twice below. *)
let counter : (int, unit, inc, never, never) Component.t =
Component.make ~name:"counter" ~actions:inc_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx Inc _ -> Ctx.update ctx (( + ) 1))
()
let left = Child.make "left" counter
let right = Child.make "right" counter
type pair_state = {
opened : bool;
left : int;
right : int option; (** Absent until created: an optional lens. *)
left_refused : int;
}
type pair_action = Open | Add_right | Bump [@@deriving message ~name:"pair.action"]
(* The parent's guard on [left]: whatever the route, nothing reaches the left
counter while the pair is closed. *)
let only_when_open parent Inc _now = parent.opened
let pair : (pair_state, unit, pair_action, never, never) Component.t =
Component.make ~name:"pair" ~actions:pair_action_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx action _ ->
match action with
| Open -> Ctx.update ctx (fun s -> { s with opened = true })
| Add_right -> Ctx.update ctx (fun s -> { s with right = Some 0 })
| Bump ->
(* Inline: runs now, and the parent learns the outcome. *)
if Ctx.reduce_child ctx left Inc = Refused then
Ctx.update ctx (fun s -> { s with left_refused = s.left_refused + 1 });
(* Queued: runs after this reducer, as its own execution. *)
Ctx.to_child ctx right Inc)
~register:(fun r ->
Registrar.child r left
~lens:(Lens.field ~get:(fun s -> s.left) ~set:(fun s left -> { s with left }))
~guard:only_when_open ();
Registrar.child r right
~lens:
(Lens.opt ~get:(fun s -> s.right) ~set:(fun s n -> { s with right = Some n }))
())
()import assert from "node:assert/strict";
import { child, component, field, message, optionalLens, rootPath, Store } from "causet";
type Inc = { readonly kind: "counter.inc" };
const inc = message<Inc>("counter.action");
/** A reusable leaf, mounted twice below. */
const counter = component<number>()({
name: "counter",
actions: inc,
reduce(ctx) {
ctx.update((n) => n + 1);
},
});
interface PairState {
readonly open: boolean;
readonly left: number;
/** Absent until created: an optional lens. */
readonly right: number | undefined;
readonly leftRefused: number;
}
const left = child<PairState>()("left", counter);
const right = child<PairState>()("right", counter);
type PairAction =
| { readonly kind: "pair.open" }
| { readonly kind: "pair.add_right" }
| { readonly kind: "pair.bump" };
const pairAction = message<PairAction>("pair.action");
/**
* The parent's guard on `left`: whatever the route, nothing reaches the left
* counter while the pair is closed.
*/
const onlyWhenOpen = (parent: PairState): boolean => parent.open;
const pair = component<PairState>()({
name: "pair",
actions: pairAction,
reduce(ctx, action) {
switch (action.kind) {
case "pair.open":
ctx.update((s) => ({ ...s, open: true }));
break;
case "pair.add_right":
ctx.update((s) => ({ ...s, right: 0 }));
break;
case "pair.bump":
// Inline: runs now, and the parent learns the outcome.
if (ctx.reduceChild(left, { kind: "counter.inc" }) === "refused") {
ctx.update((s) => ({ ...s, leftRefused: s.leftRefused + 1 }));
}
// Queued: runs after this reducer, as its own execution.
ctx.toChild(right, { kind: "counter.inc" });
break;
}
},
register(r) {
r.child(left, { lens: field("left"), guard: onlyWhenOpen });
r.child(right, {
lens: optionalLens(
(s) => s.right,
(s, n) => ({ ...s, right: n }),
),
});
},
});
const state: PairState = { open: false, left: 0, right: undefined, leftRefused: 0 };
const { store } = Store.startOrThrow(pair, { state, services: undefined });
const pairMount = store.mountOrThrow(rootPath(pair));
const leftMount = store.mountOrThrow(rootPath(pair).child(left));
const rightMount = store.mountOrThrow(rootPath(pair).child(right));
// Closed, and no right counter yet: both calls are refused.
store.dispatchOrThrow(pairMount, { kind: "pair.bump" });
const s = store.state;
assert.deepEqual([s.left, s.right, s.leftRefused], [0, undefined, 1]);
// The guard holds on every route, not only through the parent's reducer.
assert.deepEqual(store.dispatchTo(leftMount, { kind: "counter.inc" }), {
ok: true,
outcome: "disabled",
});
for (const kind of ["pair.open", "pair.add_right", "pair.bump"] as const) {
store.dispatchOrThrow(pairMount, { kind });
}
store.dispatchOrThrow(rightMount, { kind: "counter.inc" });
assert.deepEqual([store.state.left, store.state.right], [1, 2]);
// One component, two mounts, two identities.
assert.equal(store.protocol.pathOf(leftMount), "/left");
assert.notEqual(store.protocol.instanceOf(leftMount), store.protocol.instanceOf(rightMount));let () =
let state = { opened = false; left = 0; right = None; left_refused = 0 } in
let store, _sink = Store.start_exn pair ~state ~services:() in
let pair_m = Store.mount_exn store (Path.root pair) in
let left_m = Store.mount_exn store (Path.child (Path.root pair) left) in
let right_m = Store.mount_exn store (Path.child (Path.root pair) right) in
(* Closed, and no right counter yet: both calls are refused. *)
ignore (Store.dispatch_exn store pair_m Bump);
let s = Store.state store in
assert ((s.left, s.right, s.left_refused) = (0, None, 1));
(* The guard holds on every route, not only through the parent's reducer. *)
assert (Store.dispatch_to store left_m Inc = Ok Disabled);
List.iter (fun a -> ignore (Store.dispatch_exn store pair_m a)) [ Open; Add_right; Bump ];
ignore (Store.dispatch_exn store right_m Inc);
let s = Store.state store in
assert ((s.left, s.right) = (1, Some 2));
(* One component, two mounts, two identities. *)
assert (Protocol.path_of (Store.protocol store) left_m = "/left");
assert (Protocol.instance_of left_m <> Protocol.instance_of right_m)Slots name immediate children only: a component cannot reach its siblings, its parent or its grandchildren. A grandparent that must gate a grandchild does it through the child's guard on its own slot. The application can also gate any mount on its whole State, with a root guard (see admission).
Outputs: children report, parents decide
A child that must tell its parent something emits an Output, a fact such as
CheckedOut { total }Checked_out { total }{ kind: "cart.checked_out", total }. The
parent's lowerer for that slot turns it into parent Actions, in place: a
child never names its parent's Actions, so it can be mounted under any
parent. In the shop, the cart's CheckedOutChecked_outcart.checked_out
becomes the root's Pay:
Child emits: Action A, Output O, Effect E
Parent lowers O: Action P, Action Q
FIFO: A, P, Q, E
A lowerer is a plain function with an ActionPorta Port.ta Port
for the parent: no State, no Service. Ignoring an Output must be an
explicit match armcasecase in the lowerer, which a slot whose child has
Outputs must bind. There is no broadcast: siblings
coordinate through their parent.
Replies: a Service answers the mount that asked
An Effect handler gives its Service a Reply<Ev>Reply.tReply<Ev>.
The Service can keep it, move it to a worker threadmove it to a worker threadhand it to a callback and send through it
later; the Event goes to the adapter of the mount whose Effect made the
reply, even when several mounts share one Service. A reply can only be made
for an Event the component adapts:
this is checked at compile time.Effect_ctx.reply raises otherwise.ctx.reply throws otherwise.
To recognise its answer, a reducer makes a request ID
(a RequestIdCtx.new_requestctx.newRequest()) while it changes State,
stores it, and puts it in the Effect; the Service returns it in the Event.
An answer whose request is no longer pending is stale, and the reducer
ignores it. That is also how a timeout cancels a request: forget it. The
Timer Service delivers a TimerFireda fired Eventa TimerFired
for a request after a delay, the same way.
Pending keeps those requests in State: for each, what the reducer needs
to handle its answer, and an optional deadline. The first of the answer and
the timer pinned to the request takes it
(Pending::takePending.takepending.take); the second finds nothing
and is stale. A component that keeps one timer for its earliest deadline
arms it at Pending::next_deadlinePending.next_deadlinepending.nextDeadline()
and, when it fires, takes what is due with
Pending::expirePending.expirepending.expire(now). The shop's payments
keep their charges in a Pending table, with no deadline; the
timeouts page shows both ways of keeping deadlines.
Input that answers no Effect, such as a message from the network, is sent
to a mount directly through the bus's
EventSinkSink.tSink, from any threadfrom any threadat any time:
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 5 }).unwrap();
let request = shop.store.state().payments.pending.iter().next().unwrap().0;
// A duplicate answer arrives from outside, for the same request.
shop.sink.try_send_to(&shop.payments, Charged { request, approved: true }).unwrap();
shop.store.drain_events(16).unwrap();
// The gateway's answer and the duplicate both ran; only the first matched.
assert_eq!(shop.store.state().payments.paid, [5]);let () =
let shop = open_ () in
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 5 }));
let request = fst (List.hd (Pending.bindings (Store.state shop.store).payments.pending)) in
(* A duplicate answer arrives from outside, for the same request. *)
assert (Sink.try_send_to shop.sink shop.payments_mount charged_message { request; approved = true } = Ok ());
ignore (Store.drain_events shop.store 16);
(* The gateway's answer and the duplicate both ran; only the first matched. *)
assert ((Store.state shop.store).payments.paid = [ 5 ])import assert from "node:assert/strict";
import { charged, open } from "causet/guide";
const shop = open();
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 5 });
const [entry] = shop.store.state.payments.pending.entries();
assert.ok(entry);
const [request] = entry;
// A duplicate answer arrives from outside, for the same request.
const duplicate = { kind: "payments.charged", request, approved: true } as const;
assert.deepEqual(shop.sink.trySendTo(shop.payments, charged, duplicate), { ok: true });
shop.store.drainEvents(16);
// The gateway's answer and the duplicate both ran; only the first matched.
assert.deepEqual(shop.store.state.payments.paid, [5]);Only a component that adapts an Event can be sent one; the Event is handed back; the Event is handed back:
use causet::guide::shop::*;
let shop = Shop::open(StoreOptions::default());
let request = todo!();
shop.sink.try_send_to(&shop.cart, Charged { request, approved: true }).unwrap();let () =
let shop = open_ () in
let request = { Request_id.session = 1; execution = 1; index = 0 } in
match Sink.try_send_to shop.sink shop.cart_mount charged_message { request; approved = true } with
| Error (Unregistered _) -> ()
| _ -> assert falseimport assert from "node:assert/strict";
import { RequestId } from "causet";
import { type Charged, charged, open } from "causet/guide";
const shop = open();
const request = new RequestId(shop.store.session, 1, 0);
const answer: Charged = { kind: "payments.charged", request, approved: true };
// The cart adapts no Charged: the send is refused, and the Event handed back.
assert.deepEqual(shop.sink.trySendTo(shop.cart, charged, answer), {
ok: false,
error: { kind: "unregistered", event: answer },
});Context from the parent
A component sees its own State only. When its decision depends on the rest of the application (a balance a sibling keeps, whether a request is still open, which inputs another part already spent), the parent, which can read it, computes that fact and passes it in the child's Action. The child stays a pure transition of its own State and the Action; the fact it decided on is in the Action, so it shows in the trace and a test can give the child any context without building the rest of the application. Requests the other way leave as Outputs, which the parent lowers.
use causet::*;
/// Pays out; the balance it must not exceed is kept by its parent.
struct Sender;
#[derive(Debug, Default)]
struct SenderState {
sent: Vec<u64>,
refused: Vec<u64>,
}
/// `affordable` is context: the parent read it, the child cannot.
#[derive(Debug, Action)]
#[causet(type = "sender.action", kind = "sender.send")]
struct Send {
amount: u64,
affordable: bool,
}
#[derive(Debug, Output)]
#[causet(type = "sender.output", kind = "sender.spent")]
struct Spent {
amount: u64,
}
impl Component for Sender {
type State = SenderState;
type Action = Send;
type Output = Spent;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, Send { amount, affordable }: Send, _: &ActionMeta) {
if !affordable {
ctx.state_mut().refused.push(amount);
return;
}
ctx.state_mut().sent.push(amount);
ctx.into_emitter().emit_output(Spent { amount });
}
}
struct Wallet;
#[derive(Debug, Default)]
struct WalletState {
balance: u64,
sender: SenderState,
}
#[derive(Debug, Action)]
#[causet(type = "wallet.action")]
enum WalletAction {
Pay { amount: u64 },
Debit { amount: u64 },
}
const SENDER: Child<Wallet, Sender> = Child::new("sender");
impl Component for Wallet {
type State = WalletState;
type Action = WalletAction;
type Output = Never;
no_effects!();
fn reduce(mut ctx: ComponentContext<'_, Self>, action: WalletAction, _: &ActionMeta) {
match action {
WalletAction::Pay { amount } => {
// The parent reads what the child cannot, and passes it on.
let affordable = ctx.state().balance >= amount;
ctx.reduce_child(SENDER, Send { amount, affordable });
}
WalletAction::Debit { amount } => ctx.state_mut().balance -= amount,
}
}
fn register(r: &mut ComponentRegistry<'_, Self>) {
r.child(SENDER, lens!(WalletState => sender)).on_output(debit).bind();
}
}
/// The child's request, as the parent's Action.
fn debit(_: Child<Wallet, Sender>, Spent { amount }: Spent, port: &mut ActionPort<'_, Wallet>) {
port.emit_action(WalletAction::Debit { amount });
}
let state = WalletState { balance: 10, ..WalletState::default() };
let (mut store, _sink) = Store::start::<Wallet>(state, (), StoreOptions::default()).unwrap();
let wallet = store.mount(&root::<Wallet>()).unwrap();
store.dispatch_to(&wallet, WalletAction::Pay { amount: 7 }).unwrap();
store.dispatch_to(&wallet, WalletAction::Pay { amount: 7 }).unwrap(); // 3 left
assert_eq!(store.state().sender.sent, [7]);
assert_eq!(store.state().sender.refused, [7]);
assert_eq!(store.state().balance, 3);type sender_state = { sent : int list; refused : int list }
(* [affordable] is context: the parent read it, the child cannot. *)
type send = { amount : int; affordable : bool }
[@@deriving message ~name:"sender.action" ~kind:"sender.send"]
type spent = Spent of int [@@deriving message ~name:"sender.output"]
(* Pays out; the balance it must not exceed is kept by its parent. *)
let sender : (sender_state, unit, send, never, spent) Component.t =
Component.make ~name:"sender" ~actions:send_message ~effects:Message.never
~outputs:spent_message
~reduce:(fun ctx { amount; affordable } _ ->
if not affordable then
Ctx.update ctx (fun s -> { s with refused = s.refused @ [ amount ] })
else (
Ctx.update ctx (fun s -> { s with sent = s.sent @ [ amount ] });
Ctx.emit_output ctx (Spent amount)))
()
type wallet_state = { balance : int; sender : sender_state }
type wallet_action = Pay of int | Debit of int
[@@deriving message ~name:"wallet.action"]
let sender_slot = Child.make "sender" sender
let wallet : (wallet_state, unit, wallet_action, never, never) Component.t =
Component.make ~name:"wallet" ~actions:wallet_action_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun ctx action _ ->
match action with
| Pay amount ->
(* The parent reads what the child cannot, and passes it on. *)
let affordable = (Ctx.state ctx).balance >= amount in
ignore (Ctx.reduce_child ctx sender_slot { amount; affordable })
| Debit amount -> Ctx.update ctx (fun s -> { s with balance = s.balance - amount }))
~register:(fun r ->
Registrar.child r sender_slot
~lens:
(Lens.field ~get:(fun s -> s.sender) ~set:(fun s sender -> { s with sender }))
(* The child's request, as the parent's Action. *)
~on_output:(fun _ (Spent amount) port -> Port.emit_action port (Debit amount))
())
()import assert from "node:assert/strict";
import { child, component, field, message, rootPath, Store } from "causet";
interface SenderState {
readonly sent: readonly number[];
readonly refused: readonly number[];
}
/** `affordable` is context: the parent read it, the child cannot. */
type Send = { readonly kind: "sender.send"; readonly amount: number; readonly affordable: boolean };
const send = message<Send>("sender.action");
type Spent = { readonly kind: "sender.spent"; readonly amount: number };
const spent = message<Spent>("sender.output");
/** Pays out; the balance it must not exceed is kept by its parent. */
const sender = component<SenderState>()({
name: "sender",
actions: send,
outputs: spent,
reduce(ctx, { amount, affordable }) {
if (!affordable) {
ctx.update((s) => ({ ...s, refused: [...s.refused, amount] }));
return;
}
ctx.update((s) => ({ ...s, sent: [...s.sent, amount] }));
ctx.emitOutput({ kind: "sender.spent", amount });
},
});
interface WalletState {
readonly balance: number;
readonly sender: SenderState;
}
type WalletAction =
| { readonly kind: "wallet.pay"; readonly amount: number }
| { readonly kind: "wallet.debit"; readonly amount: number };
const walletAction = message<WalletAction>("wallet.action");
const senderSlot = child<WalletState>()("sender", sender);
const wallet = component<WalletState>()({
name: "wallet",
actions: walletAction,
reduce(ctx, action) {
switch (action.kind) {
case "wallet.pay": {
// The parent reads what the child cannot, and passes it on.
const affordable = ctx.state.balance >= action.amount;
ctx.reduceChild(senderSlot, { kind: "sender.send", amount: action.amount, affordable });
break;
}
case "wallet.debit":
ctx.update((s) => ({ ...s, balance: s.balance - action.amount }));
break;
}
},
register(r) {
r.child(senderSlot, {
lens: field("sender"),
// The child's request, as the parent's Action.
onOutput: ({ amount }, port) => port.emitAction({ kind: "wallet.debit", amount }),
});
},
});
const state: WalletState = { balance: 10, sender: { sent: [], refused: [] } };
const { store } = Store.startOrThrow(wallet, { state, services: undefined });
const mount = store.mountOrThrow(rootPath(wallet));
store.dispatchOrThrow(mount, { kind: "wallet.pay", amount: 7 });
store.dispatchOrThrow(mount, { kind: "wallet.pay", amount: 7 }); // 3 left
assert.deepEqual(store.state.sender.sent, [7]);
assert.deepEqual(store.state.sender.refused, [7]);
assert.equal(store.state.balance, 3);let () =
let state = { balance = 10; sender = { sent = []; refused = [] } } in
let store, _sink = Store.start_exn wallet ~state ~services:() in
let m = Store.mount_exn store (Path.root wallet) in
ignore (Store.dispatch_exn store m (Pay 7));
ignore (Store.dispatch_exn store m (Pay 7)) (* 3 left *);
let s = Store.state store in
assert (s.sender.sent = [ 7 ] && s.sender.refused = [ 7 ] && s.balance = 3)A check that only reads the parent's State, and only says yes or no, can be a guard on the slot instead; a fact the child's reducer works with goes in the Action.
Where an Effect belongs
A reply returns to the mount whose Effect made it, and its Event is adapted and reduced there, with that component's view. So put an Effect on the component that can interpret its answer. If understanding the answer needs State the component cannot see (whether the request it answers is still wanted, what changed meanwhile), the Effect belongs to the parent: the parent issues it, adapts the answer, and passes the child what it decided, as above. Usually that leaves the child with no Effects at all: a lifecycle of its own State, driven by its parent.
The wallet-sendwallet_sendwallet-send example in the repository
is built this way: the wallet-send component holds a send's lifecycle; the
root holds the RPC requests, the chain's root and the mempool, issues every
read and the proving, and tells the component, with each answer, whether
its attempt is still current.