Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 5
Running an application
Starting a Store in one call, driving it with a loop of your own, Services that answer from other threads, and assembling it by hand.
Components describe what an application does; something still has to put them together and keep them running. The tree must be built once and checked, given its Services, and fed the answers those Services send, often from threads of their own. Causet leaves the thread and the loop to the application: a Store runs on whichever thread calls it, and does nothing between calls.
This page covers starting a Store, the loop that drives it, how Services on other threads reach the Store and what happens when they send faster than it drains, assembling the pieces by hand when an application must choose them, and what is left when something goes wrong.
Starting a Store
An application starts a Store in one call, from its root component, its
initial State and its Services:
Store::start::<Root>(state, services, options), where StoreOptions holds the clock, SystemClock by defaultStore.start ?clock root ~state ~services, or Store.start_exn, where the clock defaults to the system'sStore.start(root, { state, services, clock }), or Store.startOrThrow, where the clock defaults to the system's.
It mounts the root component at /, and that registers the whole tree:
each component's register declares its slots and the Events it adapts,
and each child bound there registers its own. It checks the tree (below),
makes the Store's Event bus, and returns the Store with the bus's sending
side, the EventSinksinkSink, which other threadsother threadsother code keep to send Events
in. Its worker lane holds
hosting::DEFAULT_WORKER_CAPACITYEvent_bus.default_worker_capacityDEFAULT_WORKER_CAPACITY
Events, 1024 (below), and its session is fresh. If the tree has problems,
start returns them, a RegistrationErrorStore.start returns Error problems, and Store.start_exn raises with themStore.start returns { ok: false, problems }, and Store.startOrThrow throws with them.
store.mount(&path)Store.mount store pathstore.mount(path) resolves a path into the
mount that dispatches and sends address, or says why it cannot(store.mountOrThrow throws instead), and
store.protocol()Store.protocol storestore.protocol returns the Protocol the Store runs.
use causet::guide::shop::*;
let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
let (mut store, _sink) =
Store::start::<ShopRoot>(ShopState::default(), services, StoreOptions::default())
.expect("a valid registration");
let cart = store.mount(&root::<ShopRoot>().child(CART)).unwrap();
store.dispatch_to(&cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
assert_eq!(store.state().cart.total, 4);open Causet
open Causet_guide.Shop
let () =
let services = { gateway = approve_up_to 100 } in
let store, _sink = Store.start_exn shop_root ~state:empty ~services in
let cart = Result.get_ok (Store.mount store (Path.child (Path.root shop_root) cart_slot)) in
ignore (Store.dispatch_exn store cart (Add { item = "tea"; price = 4 }));
assert ((Store.state store).cart.total = 4)import assert from "node:assert/strict";
import { rootPath, Store } from "causet";
import { approveUpTo, cartSlot, empty, shopRoot } from "causet/guide";
const services = { gateway: approveUpTo(100) };
const { store } = Store.startOrThrow(shopRoot, { state: empty, services });
const cart = store.mountOrThrow(rootPath(shopRoot).child(cartSlot));
store.dispatchOrThrow(cart, { kind: "cart.add", item: "tea", price: 4 });
assert.equal(store.state.cart.total, 4);What freeze checks
Mistakes in wiring are found when the tree is frozen, which starting a
Store does, not when a message first takes the wrong path. Freezing reports every problem it
finds, not only the first: freeze returns a RegistrationError, which holds the list of ProblemsRegistry.freeze returns Error with the list of problems, and problem_message describes eachfreeze returns { ok: false, problems }, problemMessage describes each, and freezeOrThrow throws with all of them.
It refuses:
- a slot bound twice: two slots of one parent with the same name;
- a child that reports Outputs, on a slot with no lowerer;
- a component with Effects that no Service projection reaches: every mount between it and the root must project the Service on;
- an Event registered twice on one mount;
- two mount paths whose instance IDs collide (rename a slot);
- a root registered twice, no root, or a root that reports Outputs;
- a root guard whose path names no mount or another component, one on the root itself, or a second one on a mount (scheduling).
It also refuses a slot declared with r.child(…) and never bound with
.bind().
use causet::guide::shop::*;
use causet::{Problem, RegistrationError};
/// A root that gets its wiring wrong three ways.
struct Miswired;
const FIRST: Child<Miswired, Cart> = Child::new("cart");
const SECOND: Child<Miswired, Cart> = Child::new("cart");
const PAY: Child<Miswired, Payments> = Child::new("payments");
impl Component for Miswired {
type State = ShopState;
type Action = ShopAction;
type Output = Never;
no_effects!(ShopServices);
fn reduce(_: ComponentContext<'_, Self>, _: ShopAction, _: &ActionMeta) {}
fn register(r: &mut ComponentRegistry<'_, Self>) {
// The cart reports Outputs, and nothing lowers them.
r.child(FIRST, lens!(ShopState => cart)).bind();
// A second slot with the same name.
r.child(SECOND, lens!(ShopState => cart)).bind();
// Payments has Effects, and no Service lens reaches it.
r.child(PAY, lens!(ShopState => payments)).bind();
}
}
let mut registry = Registry::<ShopState, ShopServices>::new();
registry.root::<Miswired>();
let Err(RegistrationError(problems)) = registry.freeze() else { panic!("frozen") };
assert_eq!(problems, [
Problem::NoLowerer { path: "/cart".into() },
Problem::SlotBoundTwice { path: "/cart".into() },
Problem::NoServiceProjection { path: "/payments".into(), at: "/payments".into() },
]);let () =
let first = Child.make "cart" cart in
let second = Child.make "cart" cart in
let pay = Child.make "payments" payments in
let cart_lens = Lens.field ~get:(fun s -> s.cart) ~set:(fun s cart -> { s with cart }) in
(* A root that gets its wiring wrong three ways. *)
let miswired =
Component.make ~name:"miswired" ~actions:shop_action_message ~effects:Message.never
~outputs:Message.never
~reduce:(fun _ _ _ -> ())
~register:(fun r ->
(* The cart reports Outputs, and nothing lowers them. *)
Registrar.child r first ~lens:cart_lens ();
(* A second slot with the same name. *)
Registrar.child r second ~lens:cart_lens ();
(* Payments has Effects, and no Service projection reaches it. *)
Registrar.child r pay
~lens:
(Lens.field
~get:(fun s -> s.payments)
~set:(fun s payments -> { s with payments }))
())
()
in
let registry : (shop_state, shop_services) Registry.t = Registry.create () in
Registry.root registry miswired;
assert (
Registry.freeze registry
= Error
[
No_lowerer "/cart";
Slot_bound_twice "/cart";
No_service_projection { path = "/payments"; at = "/payments" };
])import assert from "node:assert/strict";
import { child, component, field, Registry } from "causet";
import { cart, payments, type ShopServices, type ShopState, shopAction } from "causet/guide";
const first = child<ShopState>()("cart", cart);
const second = child<ShopState>()("cart", cart);
const pay = child<ShopState>()("payments", payments);
/** A root that gets its wiring wrong three ways. */
const miswired = component<ShopState, ShopServices>()({
name: "miswired",
actions: shopAction,
reduce() {},
register(r) {
// The cart reports Outputs, and nothing lowers them.
r.child(first, { lens: field("cart") });
// A second slot with the same name.
r.child(second, { lens: field("cart") });
// Payments has Effects, and no Service projection reaches it.
r.child(pay, { lens: field("payments") });
},
});
const registry = new Registry<ShopState, ShopServices>();
registry.root(miswired);
assert.deepEqual(registry.freeze(), {
ok: false,
problems: [
{ kind: "noLowerer", path: "/cart" },
{ kind: "slotBoundTwice", path: "/cart" },
{ kind: "noServiceProjection", path: "/payments", at: "/payments" },
],
});One Services value, split by lenses
The Store holds one Services value, the root's. Each Effect handler sees
only its own part of it, projected from its parent's by the slot's Service
lensprojectionprojection. The shop's root binds payments with
.service(lens!(ShopServices => gateway))~service:(fun svc -> svc.gateway)service: (svc) => svc.gateway,
so the payments handler sees the gateway and nothing else. Mounts that
share a Service project the same part, or the whole value with
Lens::identity()Fun.id(svc) => svc.
A component without Effects has no handler and needs no Service of its
own. no_effects!() sets its Effect to Never and its Service to (). A composite whose children have Effects writes no_effects!(T) instead, so that its Service is T and its children's lenses can reach into it: the shop's root is no_effects!(ShopServices).It passes ~effects:Message.never and no ~handle. Its Service type is still whatever its children's projections read from: the shop's root's is shop_services.It leaves out effects and handle. Its Service type, the second type argument of component<S, Svc>(), is still whatever its children's projections read from: the shop's root's is ShopServices.
Driving the Store
A Store does work only when it is called.
dispatch_toStore.dispatch_tostore.dispatchTo runs an Action with
everything it causes; drain_events(max)Store.drain_events store maxstore.drainEvents(max)
delivers up to max Events waiting on the bus and returns how many it
delivered. Draining never blocks: when nothing waits, it returns 0 at
once. The application owns the loop and can wait for Event readiness
alongside its other inputs and deadlines. Each turn it typically:
- takes in outside input (requests it received, dispatched as Actions; a
threadthreadcallback that receives input can instead send it as Events through the
EventSinksinkSink); - drains a bounded batch of Events, so the turn ends even while Events keep arriving;
- checks whether it is done: a shutdown request, or, for a batch job, nothing left pending;
- waits for readiness, another input or a deadline when nothing was delivered, so it does not spin.
This loop runs the shop assembled by hand (as at the end of this page) with
a worker lane of two Events, so the waiting below shows:
open(gateway, 2)open_with ~worker_capacity:2open(gateway, 2).
The gateway answers every charge from a thread of its ownfrom a thread of its ownwhen a promise settles, outside the Store's run, and the
loop drains until every charge is settled.
The dedicated driver waits on the bus between bounded drains.
The dedicated driver waits on the bus between bounded drains.
The host schedules bounded, synchronous turns with setImmediate;
the notification only requests a turn.
use std::thread;
use std::time::{Duration, Instant};
/// Answers each charge from a thread of its own.
struct OnThreads;
impl Gateway for OnThreads {
fn charge(&mut self, request: RequestId, amount: u64, reply: Reply<Charged>) {
// The reply moves to the worker thread, which answers when it is done.
thread::spawn(move || {
let answer = Charged { request, approved: amount <= 100 };
// Waits while the worker lane is full; fails once the Store is gone or faulted.
let _ = reply.send_timeout(answer, Duration::from_secs(5));
});
}
}
// A worker lane of 2, for 5 charges: some answers wait for room.
let mut shop = open(Box::new(OnThreads), 2);
for amount in [10, 20, 30, 40, 500] {
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount }).unwrap();
}
// The driver loop: drain what has arrived, and rest briefly when nothing has.
let ready = shop.store.readiness();
let deadline = Instant::now() + Duration::from_secs(10);
while !shop.store.state().payments.pending.is_empty() {
assert!(Instant::now() < deadline, "the gateway never answered");
if shop.store.drain_events(64).unwrap() == 0 {
ready.wait_timeout(deadline.saturating_duration_since(Instant::now()));
}
}
// The threads answered in any order.
let mut paid = shop.store.state().payments.paid.clone();
paid.sort();
assert_eq!(paid, [10, 20, 30, 40]);
assert_eq!(shop.store.state().payments.declined, [500]);(* Answers each charge from a thread of its own. *)
let on_threads =
{
charge =
(fun request amount reply ->
(* The reply moves to the worker thread, which answers when it is done. *)
ignore
(Thread.create
(fun () ->
let answer = { request; approved = amount <= 100 } in
(* Waits while the worker lane is full; fails once the Store is gone. *)
ignore (Reply.send_timeout reply answer ~timeout:5.0))
()));
}
let () =
(* A worker lane of 2, for 5 charges: some answers wait for room. *)
let shop = open_with ~worker_capacity:2 on_threads in
List.iter
(fun amount -> ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount })))
[ 10; 20; 30; 40; 500 ];
(* A dedicated native driver waits on the bus between bounded drains. *)
let waiter =
match Readiness.Blocking.create (Store.readiness shop.store) with
| Ok waiter -> waiter | Error Already_subscribed -> assert false
in
let deadline = Unix.gettimeofday () +. 10.0 in
Fun.protect ~finally:(fun () -> Readiness.Blocking.close waiter)
(fun () ->
while not (Pending.is_empty (Store.state shop.store).payments.pending) do
assert (Unix.gettimeofday () < deadline);
match Store.drain_events shop.store 64 with
| Ok 0 -> ignore (Readiness.Blocking.wait_timeout waiter
~timeout:(max 0. (deadline -. Unix.gettimeofday ())))
| Ok _ -> ()
| Error _ -> assert false
done);
(* The threads answered in any order. *)
let { paid; declined; _ } = (Store.state shop.store).payments in
assert (List.sort compare paid = [ 10; 20; 30; 40 ]);
assert (declined = [ 500 ])import assert from "node:assert/strict";
/** Stands in for a call to a payment provider: it settles later. */
async function provider(amount: number): Promise<boolean> {
return amount <= 100;
}
/** Answers each charge when the provider's promise settles: outside the Store's run. */
const later: Gateway = {
charge(request, amount, reply) {
// The reply is kept, and the answer sent when the work is done.
void provider(amount).then((approved) => {
// Waits while the worker lane is full; settles with `closed` once the
// Store is closed or faulted.
void reply.sendTimeout({ kind: "payments.charged", request, approved }, 5_000);
});
},
};
// A worker lane of 2, for 5 charges: some answers wait for room.
const shop = open(later, 2);
for (const amount of [10, 20, 30, 40, 500]) {
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount });
}
// The host schedules synchronous, bounded turns on Node's event loop.
const ready = shop.store.readiness();
let scheduled = false;
let stopped = false;
function schedule(): void {
if (!scheduled && !stopped) { scheduled = true; setImmediate(turn); }
}
function turn(): void {
scheduled = false;
if (stopped) return;
const drained = shop.store.drainEvents(64);
assert.ok(drained.ok);
if (shop.store.state.payments.pending.isEmpty()) {
stopped = true;
subscription.cancel();
clearTimeout(deadline);
assert.deepEqual(shop.store.state.payments.paid, [10, 20, 30, 40]);
assert.deepEqual(shop.store.state.payments.declined, [500]);
shop.store.close();
} else if (ready.current() === "closed") {
stopped = true;
subscription.cancel();
clearTimeout(deadline);
} else if (ready.current() === "events") schedule();
}
const registered = ready.subscribe(schedule);
if (!registered.ok) throw new Error(registered.error);
const subscription = registered.subscription;
const deadline = setTimeout(() => { throw new Error("payment replies timed out"); }, 5_000);
schedule();The example has a deadline because a Service that never answers should fail a test, rather than leave it waiting forever.
The rest of this section is what the loop waits on, and the other ways to wait.
Waiting for Events
inbox.readiness()Inbox.readiness inboxinbox.readiness()
returns a readiness handle before the Store takes the inbox;
store.readiness()Store.readiness storestore.readiness()
returns one afterwards. It belongs to that bus, so the host can keep it
separately from the Store. Its
current()Readiness.currentcurrent()
reports deliverable Events, closure, or an open, empty bus. Waiting never
consumes an Event or runs a reducer. Held Events become ready only when
released, and closing or faulting the Store signals its driver too.
Each bus has one registration, held by
a persistent driver notificationa persistent driver notification or by a blocking waiter (below)a persistent driver notification.
ready.subscribe(notify)Readiness.subscribe ready notifyready.subscribe(notify)
installs the notification. While the registration is held, registering
again returns
ReadinessInUseAlready_subscribedalreadySubscribed.
Registration checks readiness too, so already-queued input is signalled
immediately. The same registration signals later batches and closure;
a closed bus signals immediately and retains no callback.
Notifications run outside the queue lock, on the notifying
threadthreadJavaScript turn. They only signal the
host's driver, which runs the Store later. They must not run the Store
inline.
Unwinding panics in notifications are ignored; an aborting panic still traps.
Exceptions from notifications are ignored.
Exceptions from notifications are ignored.
Cancel the subscription with
subscription.cancel(), or drop itReadiness.cancel subscriptionsubscription.cancel()
to release the callback. An already-issued notification may still run.
Bursts may coalesce: a notification says the bus became ready, not how many Events it holds. After each bounded drain, keep scheduling turns while readiness reports Events. A partially drained queue stays ready and does not need another notification. Only the host decides when to call the Store. No executor or async syntax is required.
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
let ready = shop.store.readiness();
let pending = Arc::new(AtomicBool::new(false));
let wake = pending.clone();
// A host integration would schedule its driver or unpark its thread here.
let mut subscription = ready.subscribe(move || { wake.store(true, Ordering::SeqCst); }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
assert!(pending.load(Ordering::SeqCst));
assert!(shop.store.state().payments.paid.is_empty());
shop.store.drain_events(64).unwrap();
assert_eq!(shop.store.state().payments.paid, [4]);
subscription.cancel();let () =
let shop = open_with (approve_up_to 100) in
let ready = Store.readiness shop.store in
(* An event-loop integration would signal its driver here. *)
let notified = Atomic.make false in
let subscription =
match Readiness.subscribe ready (fun () -> Atomic.set notified true) with
| Ok sub -> sub | Error Already_subscribed -> assert false
in
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
assert (Atomic.get notified);
assert (Readiness.current ready = Some Readiness.Events);
ignore (Store.drain_events shop.store 64);
Readiness.cancel subscription;
Store.close shop.storeimport assert from "node:assert/strict";
import { open } from "causet/guide";
const shop = open();
const ready = shop.store.readiness();
let driverPending = false;
// An event-loop integration would schedule its driver here.
const registered = ready.subscribe(() => {
driverPending = true;
});
assert.ok(registered.ok);
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
assert.ok(driverPending);
assert.equal(ready.current(), "events");
assert.deepEqual(shop.store.state.payments.paid, []);
shop.store.drainEvents(64);
assert.deepEqual(shop.store.state.payments.paid, [4]);
registered.subscription.cancel();
shop.store.close();
assert.equal(ready.current(), "closed");Readiness is a level check, not a reservation: it stays ready until the
Events are drained, and the driver rechecks after waking. Keep one driver
in charge of the Store and drain bounded batches before resting.
A Store with Send State and Services can be moved to a driver
thread; mutable access is still exclusive.
A Store may be handed to another thread between calls, but callers
must serialize access.
On a dedicated native thread, ready.wait_timeout(duration) blocks
until Events, closure or the timeout (None). It shares the queue lock
with the predicate check, tolerates spurious wakeups within the same
timeout, and holds no registration, so a notification can still be
installed beside it. WebAssembly and UI event loops use notifications.
On a dedicated native thread, Readiness.Blocking.create ready
returns a (waiter, error) result. The waiter is reusable and takes the
bus's one registration: creating it returns Error Already_subscribed
while a Readiness.subscribe notification is active, and
Readiness.subscribe returns that error while the waiter is open.
Readiness.Blocking.wait_timeout waiter ~timeout blocks until Events,
closure or the timeout in seconds (None). Close it with
Readiness.Blocking.close on the driver thread when done, which releases
the registration. It reuses its socket pair across waits, with no polling.
Waiting and closing belong to that one driver. Native socket wakeups work
on Unix and Windows without a descriptor-number limit.
use std::time::Duration;
use causet::guide::shop::*;
use causet::hosting::EventAvailability;
let mut shop = Shop::open(StoreOptions::default());
let ready = shop.store.readiness();
assert_eq!(ready.wait_timeout(Duration::ZERO), None);
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
assert_eq!(ready.wait_timeout(Duration::from_secs(1)), Some(EventAvailability::Events));
assert!(shop.store.state().payments.paid.is_empty());
shop.store.drain_events(64).unwrap();
assert_eq!(shop.store.state().payments.paid, [4]);let () =
let shop = open_with (approve_up_to 100) in
let waiter =
match Readiness.Blocking.create (Store.readiness shop.store) with
| Ok waiter -> waiter | Error Already_subscribed -> assert false
in
Fun.protect ~finally:(fun () -> Readiness.Blocking.close waiter; Store.close shop.store)
(fun () ->
assert (Readiness.Blocking.wait_timeout waiter ~timeout:0. = None);
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
assert (Readiness.Blocking.wait_timeout waiter ~timeout:1. = Some Readiness.Events);
assert ((Store.state shop.store).payments.paid = []);
ignore (Store.drain_events shop.store 64);
assert ((Store.state shop.store).payments.paid = [ 4 ]))Services on other threads
An Effect handler makes a Reply<Ev>replyReply<Ev> and gives it
to its Service, which may keep it, move it to a worker thread,move it to a worker thread,hand it to a promise or a callback, and send the
answer through it later, as OnThreadson_threadslater does above. The bus has two lanes:
- the Store lane, for sends from the Store's own thread (the one that
last called
dispatch_toordrain_events)from the Store's own thread (the one that last calleddispatch_toordrain_events)made while the Store runs an execution, insidedispatchToordrainEvents: in practice, Effect handlers and Services that answer at once. It is unbounded: such a send never waits and never fails for room; - the worker lane, for sends from every other threadfrom every other threadmade at any other time (a promise's continuation, a timer or I/O callback, a message relayed from a worker thread), bounded by the bus's worker capacity.
A drain takes the Store lane first, then the worker lane, each in the order
sent, except what send_frontsend_frontsendFront puts ahead (below). The bus learns which
thread is the Store's at the Store's first call: until then, every send
goes to the worker lane.The bus learns which
thread is the Store's at the Store's first call: until then, every send
goes to the worker lane.Before the Store's first call, as between
calls, every send goes to the worker lane.
try_send_as_worker and try_send_to_as_workerReply.try_send_as_worker and Sink.try_send_to_as_workerreply.trySendAsWorker and sink.trySendToAsWorker
use the worker lane from any threadfrom any threadeven during an execution, for a simulated Service that stands
in for a threada threadasynchronous work (testing).
A Reply is a capability, not data: structured clone keeps none of its
methods, so it cannot be posted to a worker_thread or a Web Worker. A
Service whose work runs on a worker thread keeps the reply on the main
thread and answers through it when the worker's message arrives there; that
send is outside the Store's run, so it takes the worker lane.
When the worker lane is full
The capacity is the backpressure: a worker that cannot send holds its answer, instead of queueing without bound while the Store falls behind.
try_sendandtry_send_toReply.try_sendandSink.try_send_toreply.trySendandsink.trySendTonever wait. On a full lane they fail withFullFullfull, and hand the Event back: retry later, drop it, or report it.send_timeoutandsend_timeout_toReply.send_timeoutandSink.send_timeout_toreply.sendTimeoutandsink.sendTimeoutTowait up to a timeout, aDuration,, in seconds,, in milliseconds, for room, woken as soon as the Store drains onechecking again every 0.2 msreturning a promise that settles as soon as a drain makes room, then fail withFullFullfull. The threads in the driver loop above wait this way.The threads in the driver loop above wait this way.The gateway in the driver loop above waits this way; senders waiting for room are let in oldest first.
Observers see the pressure: the bus callback, at the start of each drain,
gets both lanes' depths and how many sends were refused for room since the
last report.
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use causet::SendError;
/// Keeps each charge's reply, for a worker to answer later.
#[derive(Clone, Default)]
struct Parked(Arc<Mutex<Vec<(RequestId, Reply<Charged>)>>>);
impl Gateway for Parked {
fn charge(&mut self, request: RequestId, _amount: u64, reply: Reply<Charged>) {
self.0.lock().unwrap().push((request, reply));
}
}
let parked = Parked::default();
let mut shop = open(Box::new(parked.clone()), 1); // room for one Event
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 10 }).unwrap();
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 20 }).unwrap();
let replies = std::mem::take(&mut *parked.0.lock().unwrap());
// A worker answers both, while the Store drains nothing.
thread::spawn(move || {
let [(first, a), (second, b)]: [_; 2] = replies.try_into().ok().unwrap();
assert!(a.try_send(Charged { request: first, approved: true }).is_ok());
// The lane is full: the Event is handed back, to retry, drop or report.
let Err(SendError::Full(answer)) = b.try_send(Charged { request: second, approved: true })
else { panic!("sent") };
// Waiting for room gives up after its timeout.
let waited = b.send_timeout(answer, Duration::from_millis(10));
assert!(matches!(waited, Err(SendError::Full(_))));
})
.join()
.unwrap();
assert_eq!(shop.store.drain_events(16).unwrap(), 1);
assert_eq!(shop.store.state().payments.paid, [10]);
assert_eq!(shop.store.state().payments.pending.len(), 1); // its answer was never sent(* Keeps each charge's reply, for a worker to answer later. *)
let parked () =
let replies = ref [] in
({ charge = (fun request _ reply -> replies := !replies @ [ (request, reply) ]) }, replies)
let () =
let gateway, replies = parked () in
(* Room for one Event. *)
let shop = open_with ~worker_capacity:1 gateway in
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 10 }));
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 20 }));
let[@warning "-8"] [ (first, a); (second, b) ] = !replies in
(* A worker answers both, while the Store drains nothing. *)
let worker =
Thread.create
(fun () ->
assert (Reply.try_send a { request = first; approved = true } = Ok ());
(* The lane is full: the Event is handed back, to retry, drop or report. *)
match Reply.try_send b { request = second; approved = true } with
| Error (Full answer) ->
(* Waiting for room gives up after its timeout. *)
assert (Reply.send_timeout b answer ~timeout:0.01 = Error (Full answer))
| _ -> assert false)
()
in
Thread.join worker;
assert (Store.drain_events shop.store 16 = Ok 1);
assert ((Store.state shop.store).payments.paid = [ 10 ]);
(* Its answer was never sent. *)
assert (Pending.cardinal (Store.state shop.store).payments.pending = 1)import assert from "node:assert/strict";
import type { Reply, RequestId } from "causet";
import type { Charged } from "causet/guide";
/** Keeps each charge's reply, to be answered later. */
const parked: Array<readonly [RequestId, Reply<Charged>]> = [];
const keeper: Gateway = {
charge(request, _amount, reply) {
parked.push([request, reply]);
},
};
const shop = open(keeper, 1); // room for one Event
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 10 });
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 20 });
const [[first, a] = [], [second, b] = []] = parked;
assert.ok(first && a && second && b);
// Both are answered outside the Store's run, so to the worker lane, while
// the Store drains nothing.
assert.deepEqual(a.trySend({ kind: "payments.charged", request: first, approved: true }), {
ok: true,
});
// The lane is full: the Event is handed back, to retry, drop or report.
const answer: Charged = { kind: "payments.charged", request: second, approved: true };
const full = { ok: false, error: { kind: "full", event: answer } };
assert.deepEqual(b.trySend(answer), full);
// Waiting for room gives up after its timeout: the promise settles with `full`.
assert.deepEqual(await b.sendTimeout(answer, 10), full);
assert.deepEqual(shop.store.drainEvents(16), { ok: true, delivered: 1 });
assert.deepEqual(shop.store.state.payments.paid, [10]);
assert.equal(shop.store.state.payments.pending.size, 1); // its answer was never sentAhead of the queue
Reply::send_frontReply.send_frontreply.sendFront puts an answer at
the head of its lane. On the Store's threadOn the Store's threadDuring an execution that is the Store lane, ahead
of every Event waiting there: for a Service that answers at once and whose
answer must come before what is already queued. From any other threadFrom any other threadAt any other time it
is the head of the worker lane: it still counts against the lane's
capacity, fails with FullFullfull when the lane is full, and never waits. The
Store drains the Store lane's head, then the Store lane, then the worker
lane's head, then the worker lane, each head newest first.
/// Answers at once, at the head of its lane: on the Store's thread, as here,
/// ahead of everything waiting in the Store lane.
struct Urgent;
impl Gateway for Urgent {
fn charge(&mut self, request: RequestId, _amount: u64, reply: Reply<Charged>) {
reply.send_front(Charged { request, approved: true }).expect("the Store is open");
}
}
let mut shop = open(Box::new(Urgent), 64);
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 1 }).unwrap();
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 2 }).unwrap();
shop.store.drain_events(16).unwrap();
// The second answer went ahead of the first.
assert_eq!(shop.store.state().payments.paid, [2, 1]);(* Answers at once, ahead of everything waiting in the Store lane. *)
let urgent =
{
charge =
(fun request _ reply ->
match Reply.send_front reply { request; approved = true } with
| Ok () -> ()
| Error _ -> failwith "the Store is closed");
}
let () =
let shop = open_with urgent in
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 1 }));
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 2 }));
ignore (Store.drain_events shop.store 16);
(* The second answer went ahead of the first. *)
assert ((Store.state shop.store).payments.paid = [ 2; 1 ])import assert from "node:assert/strict";
/**
* Answers at once, at the head of its lane: during the Store's run, as here,
* ahead of everything waiting in the Store lane.
*/
const urgent: Gateway = {
charge(request, _amount, reply) {
const sent = reply.sendFront({ kind: "payments.charged", request, approved: true });
if (!sent.ok) throw new Error("the Store is closed");
},
};
const shop = open(urgent, 64);
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 1 });
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 2 });
shop.store.drainEvents(16);
// The second answer went ahead of the first.
assert.deepEqual(shop.store.state.payments.paid, [2, 1]);Why a send fails
Every failed send hands its Event back:
SendErrorsend_errorSendError's kind |
When |
|---|---|
FullFullfull |
The worker lane is at capacity. |
ClosedClosedclosed |
The Store is gone, or it faulted. |
ForeignMountWrong_protocolwrongProtocol |
The mount belongs to another Protocol than the bus. |
UnregisteredUnregisteredunregistered |
The mount's component never registered this Event type. |
The last two concern sends to a mount through the
EventSinksinkSink; a reply's route was made by the Store
for its own mount, so a reply fails only with Full or ClosedFull or Closedfull or closed.
The compiler already checks that the component adapts the Event (C: Adapts<Ev>); Unregistered catches one that implements Adapts but never called r.event.A send returns { ok: true } or { ok: false, error }, whose error.event is the Event handed back. The types do not check that the component adapts the Event: unregistered is how a send learns it.
Shutting down
Dropping the Store closes its bus: Events still queued are discarded,
every later send fails with Closed, on every thread, and senders waiting
for room wake with Closed. The bus closes before the State and Services
drop, so a Service that joins its worker threads as it drops finds their
sends already failing, rather than waiting for room. Dropping an inbox that
no Store took closes its bus too, and so does a fault.
Store.close closes the Store's bus: Events still queued are discarded,
every later send fails with Closed, on every thread, and senders waiting
for room give up with Closed. Only that and a fault close it, so an
application closes its Store when it is done with it.
store.close() closes the Store's bus: Events still queued are discarded,
every later send fails with closed, and a sendTimeout waiting for room
settles with closed at once. The readiness notification signals the driver,
which observes closed and stops its own loop. Only that and a fault close
it, so an application closes its Store when it is done with it.
use causet::SendError;
let parked = Parked::default();
let mut shop = open(Box::new(parked.clone()), 64);
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 10 }).unwrap();
let (request, reply) = parked.0.lock().unwrap().pop().unwrap();
let Shop { store, sink, payments, .. } = shop;
drop(store); // closes the bus
// Every later send fails, on every thread, and hands the Event back.
let answer = Charged { request, approved: true };
assert!(matches!(reply.try_send(answer), Err(SendError::Closed(_))));
let answer = Charged { request, approved: true };
assert!(matches!(sink.try_send_to(&payments, answer), Err(SendError::Closed(_))));let () =
let gateway, replies = parked () in
let shop = open_with gateway in
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 10 }));
let request, reply = List.hd !replies in
Store.close shop.store;
(* Every later send fails, on every thread, and hands the Event back. *)
let answer = { request; approved = true } in
assert (Reply.try_send reply answer = Error (Closed answer));
assert (Sink.try_send_to shop.sink shop.payments_mount charged_message answer
= Error (Closed answer))import assert from "node:assert/strict";
import type { Reply, RequestId } from "causet";
import { type Charged, charged } from "causet/guide";
const shop = open(keeper, 64);
const ready = shop.store.readiness();
let notified = false;
const registered = ready.subscribe(() => { notified = true; });
assert.ok(registered.ok);
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 10 });
const [[request, reply] = []] = parked;
assert.ok(request && reply);
shop.store.close(); // closes the bus and signals the host
assert.ok(notified);
assert.equal(ready.current(), "closed");
registered.subscription.cancel();
// ...and every later send fails, and hands the Event back.
const answer: Charged = { kind: "payments.charged", request, approved: true };
const closed = { ok: false, error: { kind: "closed", event: answer } };
assert.deepEqual(reply.trySend(answer), closed);
void reply.sendTimeout(answer, 5_000).then((result) => assert.deepEqual(result, closed)); // settles at once
assert.deepEqual(shop.sink.trySendTo(shop.payments, charged, answer), closed);Assembling by hand
An application assembles the pieces itself when it must choose them: a Registry of its own for root guards (scheduling), one Protocol for several Stores (the nodes of a simulation), a chosen session or worker capacity, or a held bus for tests (testing). It takes the four steps that starting a Store takes:
- A Registry, typed by the root's State and Services:
Registry::<S, Svc>::new()Registry.create ()new Registry<S, Svc>(). Itsrootmounts the root component, which registers the whole tree (above). - Freeze it into a Protocol: the mounted tree, checked, and from then on immutable. Every Store of the application (in production, in tests, in a simulation of several nodes) runs from one Protocol, and mounts are resolved against it. Each freeze makes a Protocol of its own, even of the same tree.
- An Event bus for one Store:
EventBus::new(&protocol, worker_capacity)Event_bus.create proto ~worker_capacityeventBus(protocol, { workerCapacity })returns its sending side, theEventSinksinkSink, which Services and other threadsother threadsother code keep, and its inbox, which the Store takes.Store.sinkreturns the sink from the Store too.store.sinkreturns the sink from the Store too. The capacity bounds the worker lane (above). Each bus starts a fresh session;EventBus::with_sessionEvent_bus.with_sessionthe bus'ssessionoption chooses it (determinism). - A Store, from the Protocol, the initial State, the Services and the
inbox:
Store::new(protocol, state, services, inbox, options), whereStoreOptionsholds the clock,SystemClockby defaultStore.create ?clock proto ~state ~services inbox, where the clock defaults to the system'sStore.create(protocol, { state, services, inbox, clock }), which returns the Store or why it refused the inbox (Store.createOrThrowthrows instead), and where the clock defaults to the system's.
use std::sync::Arc;
use causet::guide::shop::*;
use causet::hosting::EventBus;
/// The shop, assembled by hand: a Protocol, its bus, a Store and its mounts.
fn open(gateway: Box<dyn Gateway>, worker_capacity: usize) -> Shop {
let mut registry = Registry::<ShopState, ShopServices>::new();
registry.root::<ShopRoot>(); // registers the whole tree
let protocol = registry.freeze().expect("a valid registration");
let (sink, inbox) = EventBus::new(&protocol, worker_capacity);
let services = ShopServices { gateway };
let store = Store::new(
Arc::clone(&protocol), ShopState::default(), services, inbox, StoreOptions::default(),
)
.expect("the bus is this Protocol's");
let cart = protocol.resolve(&root::<ShopRoot>().child(CART)).unwrap();
let payments = protocol.resolve(&root::<ShopRoot>().child(PAYMENTS)).unwrap();
Shop { store, sink, cart, payments }
}
let mut shop = open(Box::new(ApproveUpTo(100)), 64);
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
assert_eq!(shop.store.state().payments.paid, [4]);open Causet
open Causet_guide.Shop
(* The shop, assembled by hand: a Protocol, its bus, a Store and its mounts. *)
let open_with ?(worker_capacity = 64) gateway =
let registry = Registry.create () in
(* Registers the whole tree. *)
Registry.root registry shop_root;
let proto =
match Registry.freeze registry with
| Ok proto -> proto
| Error problems -> failwith (String.concat "; " (List.map problem_message problems))
in
let sink, inbox = Event_bus.create proto ~worker_capacity in
let store =
match Store.create proto ~state:empty ~services:{ gateway } inbox with
| Ok store -> store
| Error _ -> failwith "the bus belongs to another Protocol"
in
let at slot = Protocol.resolve_exn proto (Path.child (Path.root shop_root) slot) in
{ store; sink; cart_mount = at cart_slot; payments_mount = at payments_slot }
let () =
let shop = open_with (approve_up_to 100) in
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16);
assert ((Store.state shop.store).payments.paid = [ 4 ])import assert from "node:assert/strict";
import { Registry, rootPath, Store } from "causet";
import {
approveUpTo,
cartSlot,
empty,
type Gateway,
paymentsSlot,
type Shop,
type ShopServices,
type ShopState,
shopRoot,
} from "causet/guide";
import { eventBus } from "causet/hosting";
/** The shop, assembled by hand: a Protocol, its bus, a Store and its mounts. */
function open(gateway: Gateway, workerCapacity = 64): Shop {
const registry = new Registry<ShopState, ShopServices>();
registry.root(shopRoot); // registers the whole tree
const protocol = registry.freezeOrThrow(); // throws with every problem found
const { sink, inbox } = eventBus(protocol, { workerCapacity });
const created = Store.create(protocol, { state: empty, services: { gateway }, inbox });
if (!created.ok) throw new Error("the bus belongs to another Protocol");
const root = rootPath(shopRoot);
const cart = protocol.resolveOrThrow(root.child(cartSlot));
const payments = protocol.resolveOrThrow(root.child(paymentsSlot));
return { store: created.store, sink, cart, payments };
}
const shop = open(approveUpTo(100));
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
assert.deepEqual(shop.store.state.payments.paid, [4]);Store::open(&protocol, state, services, options)Store.open_protocol ?clock protocol ~state ~servicesStore.open(protocol, { state, services, clock })
does the last two for a Protocol frozen by hand, with a bus of its own as
start makes it.
When something goes wrong
Assembling can fail in two places besides freezing.
Store::newStore.createStore.create refuses an inbox from a bus
made for another Protocol (ForeignBusForeign_busforeignBus), and
closes that bus. Giving one inbox to a second Store raises Invalid_argument.Giving one inbox to a second Store throws.
Later, a dispatch to a mount resolved against another Protocol returns
ForeignMountForeign_mountforeignMount, and does nothing.
use std::sync::Arc;
use causet::guide::shop::*;
use causet::hosting::EventBus;
use causet::{DispatchError, ExecutionId, SendError, root};
// A bus made for one Protocol, given to a Store of another.
let (_sink, inbox) = EventBus::new(&protocol(), 64);
let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
let refused = Store::new(protocol(), ShopState::default(), services, inbox, StoreOptions::default());
assert_eq!(refused.err(), Some(DispatchError::ForeignBus));
// A Mount resolved against another Protocol.
let mut shop = Shop::open(StoreOptions::default());
let foreign = protocol().resolve(&root::<ShopRoot>().child(CART)).unwrap();
let refused = shop.store.dispatch_to(&foreign, CartAction::Checkout);
assert_eq!(refused, Err(DispatchError::ForeignMount));
/// A gateway whose code panics.
struct Down;
impl Gateway for Down {
fn charge(&mut self, _: RequestId, _: u64, _: Reply<Charged>) {
panic!("the gateway is down");
}
}
// A panic faults the Store: this call and every later one say why...
let shop = protocol();
let (sink, inbox) = EventBus::new(&shop, 64);
let services = ShopServices { gateway: Box::new(Down) };
let mut store =
Store::new(Arc::clone(&shop), ShopState::default(), services, inbox, StoreOptions::default())
.unwrap();
let payments = shop.resolve(&root::<ShopRoot>().child(PAYMENTS)).unwrap();
let faulted = Err(DispatchError::Faulted("the gateway is down".into()));
assert_eq!(store.dispatch_to(&payments, PaymentsAction::Charge { amount: 1 }), faulted);
assert_eq!(store.drain_events(16).err(), faulted.err());
// ...and its bus is closed, as if it had been dropped.
let request = RequestId { session: store.session(), execution: ExecutionId(1), index: 0 };
let late = Charged { request, approved: true };
assert!(matches!(sink.try_send_to(&payments, late), Err(SendError::Closed(_))));let () =
(* A bus made for one Protocol, given to a Store of another. *)
let _sink, inbox = Event_bus.create (protocol ()) ~worker_capacity:64 in
let services = { gateway = approve_up_to 100 } in
match Store.create (protocol ()) ~state:empty ~services inbox with
| Error Foreign_bus -> ()
| _ -> assert falseimport assert from "node:assert/strict";
import { RequestId, rootPath, Store } from "causet";
import {
approveUpTo,
type Charged,
cartSlot,
charged,
empty,
type Gateway,
open,
paymentsSlot,
protocol,
shopRoot,
} from "causet/guide";
import { eventBus } from "causet/hosting";
// A bus made for one Protocol, given to a Store of another.
const { inbox } = eventBus(protocol(), { workerCapacity: 64 });
const services = { gateway: approveUpTo(100) };
const refused = Store.create(protocol(), { state: empty, services, inbox });
assert.deepEqual(refused, { ok: false, error: { kind: "foreignBus" } });
// A Mount resolved against another Protocol.
const shop = open();
const foreign = protocol().resolveOrThrow(rootPath(shopRoot).child(cartSlot));
const wrong = shop.store.dispatchTo(foreign, { kind: "cart.checkout" });
assert.deepEqual(wrong, { ok: false, error: { kind: "foreignMount" } });
/** A gateway whose code throws. */
const down: Gateway = {
charge() {
throw new Error("the gateway is down");
},
};
// A throw faults the Store: this call and every later one say why...
const proto = protocol();
const bus = eventBus(proto, { workerCapacity: 64 });
const store = Store.createOrThrow(proto, {
state: empty,
services: { gateway: down },
inbox: bus.inbox,
});
const payments = proto.resolveOrThrow(rootPath(shopRoot).child(paymentsSlot));
const faulted = { ok: false, error: { kind: "faulted", message: "the gateway is down" } };
assert.deepEqual(store.dispatchTo(payments, { kind: "payments.charge", amount: 1 }), faulted);
assert.deepEqual(store.drainEvents(16), faulted);
// ...and its bus is closed, as if the Store had been closed.
const request = new RequestId(store.session, 1, 0);
const late: Charged = { kind: "payments.charged", request, approved: true };
assert.deepEqual(bus.sink.trySendTo(payments, charged, late), {
ok: false,
error: { kind: "closed", event: late },
});A State or Services of another type than the root's does not compile: a
Protocol carries its root's types(Protocol<S, Svc>)(('s, 'svc) protocol)(Protocol<S, Svc>).
use causet::guide::shop::*;
use causet::hosting::EventBus;
// A Protocol is typed by its root State and Services: a Store of other
// types does not compile.
let shop = protocol(); // Arc<Protocol<ShopState, ShopServices>>
let (_sink, inbox) = EventBus::new(&shop, 64);
let store = Store::new(shop, 0_u32, (), inbox, StoreOptions::default());import { Store } from "causet";
import { protocol } from "causet/guide";
import { eventBus } from "causet/hosting";
// A Protocol is typed by its root State and Services: a Store of other
// types does not compile.
const shop = protocol(); // Protocol<ShopState, ShopServices>
const { inbox } = eventBus(shop, { workerCapacity: 64 });
const store = Store.create(shop, { state: 0, services: undefined, inbox });A panicraisethrow in application code faults the Store
(scheduling): the call that ran it, and every
call after, returns DispatchError::FaultedError (Faulted message)a faulted error
with the message, which Store::faultStore.faultstore.fault also
returns; Store.fault_location says where it was raised, when backtraces are recorded; store.faultLocation says where it was thrown, when the error's stack tells.
Nothing is rolled back, and the Store runs nothing more. A fault closes the
Store's bus at once, as droppingclosingclosing the Store does:
Events still queued are discarded, and every later send fails with
ClosedClosedclosed, so Services learn the Store is gone and stop. If the application
goes on, it opens a new Store, with a new bus, on the same Protocol:
Store::open(store.protocol(), state, services, options)Store.open_protocol (Store.protocol store) ~state ~servicesStore.open(store.protocol, { state, services }).
The mounts it holds stay valid there; starting from the root component
again would freeze a new Protocol, whose Stores refuse them.