Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 1
Messages
Declaring Actions, Effects, Events and Outputs: each type's name and each value's kind, what logging records, nesting one message in another, and writing one by hand.
Everything a component is asked, asks for, hears back or reports is a message. Logs, traces, statistics and failing tests all have to say which message ran, so each one needs a name a person can read, the same from run to run and from one port to the other.
In causet every message type has a name, such as cart.action, and every
value a kind, such as cart.add. The derives writeThe deriver writesA descriptor, made by message, gives
both from the type you declare, with the level and fields logging
records, and a printer that shows a value as the Rust port prints it, and a printer that shows a value as the Rust port prints it.
Messages need no serialization.
Four categories
A message's category says what it is for, and so who may send it (authority):
| Category | What it is | Rust derive | OCaml: given to | TypeScript: given to |
|---|---|---|---|---|
| Action | A request to a component: admitted by its enabling checks, then handled by its reducer | #[derive(Action)] |
Component.make ~actions |
component's actions |
| Effect | A command a reducer gives a Service, carried out by the component's Effect handler | #[derive(Effect)] |
Component.make ~effects |
component's effects |
| Event | A fact from outside the Store, such as a Service's answer, sent through the Event bus | #[derive(Event)] |
Registrar.event, Effect_ctx.reply |
register's r.event, ctx.reply |
| Output | A fact a child reports to its parent | #[derive(Output)] |
Component.make ~outputs |
component's outputs |
Each derive implements Message (the type's name, TYPE, and each value's
kind()) and the category's marker trait, which is what a component's
type Action, type Effect and type Output, and an Adapts impl for an
Event, ask for. A message is also Debug, Send and 'static. The derives
do not add Debug: derive it beside them.
One deriver, [@@deriving message ~name:"…"], serves all four. For a type
foo it defines foo_message, a foo Message.t that describes every value
of the type (its name, how to tell a value's kind, what logging records, how
to print it), and pp_foo, the printer. The category is where the
description goes. A type named t gives message and pp, and a trailing
_, as in effect_, is dropped: effect_message.
A message is a discriminated union whose tag is its kind: each value
carries its kind, written in full where the value is made, and a
switch on it takes the place of a match. No deriver is needed.
message<T>("…", options) gives the type's descriptor, a Message<T>: its
name, and how to read a value's kind, level and logged fields and print
it. The descriptor is also the type's identity at run time: the Store tells
payloads apart by their descriptor, never by their shape. The category is
where the descriptor goes.
Here are a kettle's messages, one of each category:
use causet::{Action, Effect, Event, Message, Output};
/// What the kettle can be asked to do.
#[derive(Debug, Action)]
#[causet(type = "kettle.action")]
enum KettleAction {
SwitchOn { target: u32 },
SwitchOff,
}
/// What it asks of its heater.
#[derive(Debug, Effect)]
#[causet(type = "kettle.effect")]
enum KettleEffect {
HeaterOn,
HeaterOff,
}
/// The thermometer's answer.
#[derive(Debug, Event)]
#[causet(type = "kettle.temperature")]
struct Temperature {
celsius: u32,
}
/// What it tells its parent.
#[derive(Debug, Output)]
#[causet(type = "kettle.output")]
enum KettleOutput {
Boiled,
}
assert_eq!(KettleAction::TYPE, "kettle.action");
assert_eq!(KettleAction::SwitchOn { target: 100 }.kind(), "kettle.switch_on");
assert_eq!(KettleEffect::HeaterOff.kind(), "kettle.heater_off");
assert_eq!(Temperature { celsius: 20 }.kind(), "kettle.temperature");
assert_eq!(KettleOutput::Boiled.kind(), "kettle.boiled");(* What the kettle can be asked to do. *)
type kettle_action = Switch_on of { target : int } | Switch_off
[@@deriving message ~name:"kettle.action"]
(* What it asks of its heater. *)
type kettle_effect = Heater_on | Heater_off [@@deriving message ~name:"kettle.effect"]
(* The thermometer's answer. *)
type temperature = { celsius : int } [@@deriving message ~name:"kettle.temperature"]
(* What it tells its parent. *)
type kettle_output = Boiled [@@deriving message ~name:"kettle.output"]
let () =
assert (kettle_action_message.name = "kettle.action");
assert (kettle_action_message.kind (Switch_on { target = 100 }) = "kettle.switch_on");
assert (kettle_effect_message.kind Heater_off = "kettle.heater_off");
assert (temperature_message.kind { celsius = 20 } = "kettle.temperature");
assert (kettle_output_message.kind Boiled = "kettle.boiled")import assert from "node:assert/strict";
import { message } from "causet";
/** What the kettle can be asked to do. */
type KettleAction =
| { readonly kind: "kettle.switch_on"; readonly target: number }
| { readonly kind: "kettle.switch_off" };
const kettleAction = message<KettleAction>("kettle.action");
/** What it asks of its heater. */
type KettleEffect = { readonly kind: "kettle.heater_on" } | { readonly kind: "kettle.heater_off" };
const kettleEffect = message<KettleEffect>("kettle.effect");
/** The thermometer's answer. */
interface Temperature {
readonly kind: "kettle.temperature";
readonly celsius: number;
}
const temperature = message<Temperature>("kettle.temperature");
/** What it tells its parent. */
type KettleOutput = { readonly kind: "kettle.boiled" };
const kettleOutput = message<KettleOutput>("kettle.output");
assert.equal(kettleAction.name, "kettle.action");
assert.equal(kettleAction.kind({ kind: "kettle.switch_on", target: 100 }), "kettle.switch_on");
assert.equal(kettleEffect.kind({ kind: "kettle.heater_off" }), "kettle.heater_off");
assert.equal(temperature.kind({ kind: "kettle.temperature", celsius: 20 }), "kettle.temperature");
assert.equal(kettleOutput.kind({ kind: "kettle.boiled" }), "kettle.boiled");Names and kinds
The type's name is required: #[causet(type = "…")]~name:"…"message's first argument.
It is never guessed from the RustOCamlTypeScript type's name, so
renaming the type changes no log or statistic, and every port can give a
message the same name.
A value's kind is what logs and statistics count it by, under its type's name:
- A variant's kind is a prefix, a
., and its name in snake case:kettle.switch_on. Every capital starts a word, soHTTPGetgivesh_t_t_p_get; writeHttpGet.A constructor's kind is a prefix, a., and its name in snake case:kettle.switch_on.Switch_onandSwitchOnboth giveswitch_on, as Rust'sSwitchOndoes. Every capital starts a word, soHTTPGetgivesh_t_t_p_get; writeHttp_get.A value's kind is itskindtag, written in full where the value is made:{ kind: "kettle.switch_on", target: 100 }. Nothing is derived from a name, and the type checker refuses a tag the union does not have. - The prefix is the type's name without its last
.segment:kettle.actiongiveskettle, and a name with no.is its own prefix.prefix = "…"sets another.The prefix is the type's name without its last.segment:kettle.actiongiveskettle, and a name with no.is its own prefix.~prefix:"…"sets another.Write the kind the other ports derive, usually the type's name without its last.segment, a., and the variant's name in snake case. Nothing checks it, and a trace matches the other ports' only where the kinds are the same. #[causet(kind = "…")]on a variant gives its kind outright.[@kind "…"]on a constructor gives its kind outright.A kind that breaks the pattern, such askettle.heater.offfor a heater's cut, is written the same way: every kind is given outright.- A struct has one
kind: the type's name, unless
kind = "…"gives another.A record, or any type that is not a variant, has one kind: the type's name, unless~kind:"…"gives another.A type of one kind, such as most Events, carries it as its tag too, and it need not be the type's name. A type whose values carry no tag gives its kind as a function (see writing one by hand, below).
use causet::{Effect, Message, Output};
#[derive(Debug, Effect)]
#[causet(type = "kettle.heater", prefix = "kettle.heater")]
enum Heater {
Warm, // the prefix and the variant
#[causet(kind = "kettle.heater.off")]
Cut, // given
}
/// A struct has one kind: its own, here, rather than the type's name.
#[derive(Debug, Output)]
#[causet(type = "kettle.alarm", kind = "kettle.dry")]
struct DryAlarm {
dry_secs: u32,
}
assert_eq!(Heater::Warm.kind(), "kettle.heater.warm");
assert_eq!(Heater::Cut.kind(), "kettle.heater.off");
assert_eq!(DryAlarm { dry_secs: 3 }.kind(), "kettle.dry");type heater =
| Warm (* the prefix and the constructor *)
| Cut [@kind "kettle.heater.off"] (* given *)
[@@deriving message ~name:"kettle.heater" ~prefix:"kettle.heater"]
(* A record has one kind: its own, here, rather than the type's name. *)
type dry_alarm = { dry_secs : int }
[@@deriving message ~name:"kettle.alarm" ~kind:"kettle.dry"]
let () =
assert (heater_message.kind Warm = "kettle.heater.warm");
assert (heater_message.kind Cut = "kettle.heater.off");
assert (dry_alarm_message.kind { dry_secs = 3 } = "kettle.dry")import assert from "node:assert/strict";
import { message } from "causet";
/** Each value's kind is its tag, written in full. */
type Heater = { readonly kind: "kettle.heater.warm" } | { readonly kind: "kettle.heater.off" };
const heater = message<Heater>("kettle.heater");
/** A type of one kind carries it too: its own, here, rather than the type's name. */
interface DryAlarm {
readonly kind: "kettle.dry";
readonly drySecs: number;
}
const dryAlarm = message<DryAlarm>("kettle.alarm");
assert.equal(heater.kind({ kind: "kettle.heater.warm" }), "kettle.heater.warm");
assert.equal(heater.kind({ kind: "kettle.heater.off" }), "kettle.heater.off");
assert.equal(dryAlarm.kind({ kind: "kettle.dry", drySecs: 3 }), "kettle.dry");Kinds need not be unique across types. The shop's Action and Effect that
charge a card are both payments.charge; a trace tells them apart by
category and type.
What logging records
Each message chooses the level it is logged at and which of its fields appear, so a log shows what matters and leaves out what must not be logged. Both can be chosen for the whole type and for each variantconstructorkind, which wins over the type:
- The level is one of trace, debug, info, warn and error; debug unless
chosen. It is written
log(level = "warn")~level:Warnon the type,[@level Warn]on a constructorlevel: "warn"for the type,levels: { "door.unlock": "warn" }for a kind. - The fields are named fields of a struct or a variantof a record or of a constructor's inline recordof a value,
none unless chosen, and written
log(fields(peer, n = count, display(addr)))~fields:peeron a record,[@fields peer, n = count, display addr]on a constructorfields: { "p2p.dial": ["peer", { field: "count", as: "n" }, { field: "addr", display: true }] }. Each is recorded by itsDebugprinter'sDebugform, so a string appears quoted, unless writtendisplay, which usesDisplaythe display form: a string unquoted,M.tbyM.to_string,foobyfoo_to_stringthe display form: a string unquoted, anything else byString(value).n = countn = count{ field: "count", as: "n" }records the fieldcountunder the namen; any other field is recorded under its name in snake case, as the Rust port names it, sodialSecsasdial_secs. The fields of a enumvariant typeunion go on its variantsconstructorskinds.
use causet::{Action, Event, LogLevel, Message};
#[derive(Debug, Action)]
#[causet(type = "door.action", log(level = "info"))]
enum DoorAction {
/// At info, the type's level, with no fields.
Ring,
/// At warn, with the person's name by `Display`, and never the code.
#[causet(log(level = "warn", fields(who = display(name))))]
Unlock { name: String, code: String },
}
/// At trace, with whether the door is ajar, by `Debug`.
#[derive(Debug, Event)]
#[causet(type = "door.sensor", log(level = "trace", fields(ajar)))]
struct DoorSensor {
ajar: bool,
battery: u8,
}
let unlock = DoorAction::Unlock { name: "Ada".into(), code: "1234".into() };
assert_eq!(DoorAction::Ring.log_level(), LogLevel::Info);
assert_eq!(unlock.log_level(), LogLevel::Warn);
assert_eq!(DoorSensor { ajar: true, battery: 80 }.log_level(), LogLevel::Trace);type door_action =
| Ring (** At info, the type's level, with no fields. *)
| Unlock of { name : string; code : string } [@level Warn] [@fields who = display name]
(** At warn, with the person's name by its display form, and never the code. *)
[@@deriving message ~name:"door.action" ~level:Info]
(* At trace, with whether the door is ajar, by its printer. *)
type door_sensor = { ajar : bool; battery : int }
[@@deriving message ~name:"door.sensor" ~level:Trace ~fields:ajar]
let () =
let unlock = Unlock { name = "Ada"; code = "1234" } in
assert (door_action_message.level Ring = Message.Info);
assert (door_action_message.level unlock = Message.Warn);
assert (door_action_message.fields unlock = [ ("who", "Ada") ]);
let sensor = { ajar = true; battery = 80 } in
assert (door_sensor_message.level sensor = Message.Trace);
assert (door_sensor_message.fields sensor = [ ("ajar", "true") ])import assert from "node:assert/strict";
import { message } from "causet";
type DoorAction =
/** At info, the type's level, with no fields. */
| { readonly kind: "door.ring" }
/** At warn, with the person's name by its display form, and never the code. */
| { readonly kind: "door.unlock"; readonly name: string; readonly code: string };
const doorAction = message<DoorAction>("door.action", {
level: "info",
levels: { "door.unlock": "warn" },
fields: { "door.unlock": [{ field: "name", as: "who", display: true }] },
});
/** At trace, with whether the door is ajar, by its `Debug` form. */
interface DoorSensor {
readonly kind: "door.sensor";
readonly ajar: boolean;
readonly battery: number;
}
const doorSensor = message<DoorSensor>("door.sensor", {
level: "trace",
fields: { "door.sensor": ["ajar"] },
});
const unlock: DoorAction = { kind: "door.unlock", name: "Ada", code: "1234" };
assert.equal(doorAction.level({ kind: "door.ring" }), "info");
assert.equal(doorAction.level(unlock), "warn");
assert.deepEqual(doorAction.fields(unlock), [["who", "Ada"]]);
const sensor: DoorSensor = { kind: "door.sensor", ajar: true, battery: 80 };
assert.equal(doorSensor.level(sensor), "trace");
assert.deepEqual(doorSensor.fields(sensor), [["ajar", "true"]]);Observers read both, and the stock logger writes them with every execution: see logging.
Nested messages
A variant marked #[causet(nested)]constructor marked [@nested]variant named in the descriptor's nested
holds a message of another type, and takes that message's kind, level and
fields. A parent's Action can then carry a child's Actions whole, or one
type can gather the messages of several. The type's name stays the outer
one: statistics count a lamp.dim under room.action.
use causet::{Action, LogLevel, Message};
#[derive(Debug, Action)]
#[causet(type = "lamp.action")]
enum LampAction {
#[causet(log(level = "info", fields(percent)))]
Dim { percent: u8 },
Unplug,
}
#[derive(Debug, Action)]
#[causet(type = "room.action")]
enum RoomAction {
Vacate,
#[causet(nested)]
Lamp(LampAction),
}
let dim = RoomAction::Lamp(LampAction::Dim { percent: 40 });
assert_eq!(RoomAction::TYPE, "room.action");
assert_eq!(RoomAction::Vacate.kind(), "room.vacate");
// The inner message's kind, level and fields.
assert_eq!(dim.kind(), "lamp.dim");
assert_eq!(dim.log_level(), LogLevel::Info);
assert_eq!(format!("{dim:?}"), "Lamp(Dim { percent: 40 })");type lamp_action = Dim of { percent : int } [@level Info] [@fields percent] | Unplug
[@@deriving message ~name:"lamp.action"]
type room_action = Vacate | Lamp of lamp_action [@nested]
[@@deriving message ~name:"room.action"]
let () =
let dim = Lamp (Dim { percent = 40 }) in
assert (room_action_message.name = "room.action");
assert (room_action_message.kind Vacate = "room.vacate");
(* The inner message's kind, level and fields. *)
assert (room_action_message.kind dim = "lamp.dim");
assert (room_action_message.level dim = Message.Info);
assert (room_action_message.fields dim = [ ("percent", "40") ]);
assert (Debug.to_string pp_room_action dim = "Lamp(Dim { percent: 40 })")import assert from "node:assert/strict";
import { message } from "causet";
type LampAction =
| { readonly kind: "lamp.dim"; readonly percent: number }
| { readonly kind: "lamp.unplug" };
const lampAction = message<LampAction>("lamp.action", {
levels: { "lamp.dim": "info" },
fields: { "lamp.dim": ["percent"] },
});
type RoomAction =
| { readonly kind: "room.vacate" }
| { readonly kind: "room.lamp"; readonly lamp: LampAction };
const roomAction = message<RoomAction>("room.action", {
nested: { "room.lamp": { field: "lamp", message: lampAction } },
});
const dim: RoomAction = { kind: "room.lamp", lamp: { kind: "lamp.dim", percent: 40 } };
assert.equal(roomAction.name, "room.action");
assert.equal(roomAction.kind({ kind: "room.vacate" }), "room.vacate");
// The inner message's kind, level and fields; the tag stays the outer one.
assert.equal(roomAction.kind(dim), "lamp.dim");
assert.equal(roomAction.level(dim), "info");
assert.deepEqual(roomAction.fields(dim), [["percent", "40"]]);
assert.equal(roomAction.debug(dim), "Lamp(Dim { percent: 40 })");The variant holds exactly one unnamed field, the inner message, as
Lamp(LampAction) does.
The constructor has one argument, a message type: foo, whose description
the deriver takes as foo_message, or M.t, taken as M.message. The
p2p example builds its Action this way: an Intent holds the Intents a
parent sends, a Transport the transport's Events, and each keeps its own
kinds, such as p2p.dial.
The variant keeps a tag of its own, such as room.lamp, and holds the
inner message in the field its nested entry names, beside the inner
descriptor: nested: { "room.lamp": { field: "lamp", message: lampAction } }.
The tag is what a reducer switches on; the kind, the inner message's, is
what logs and statistics see.
A nested variantconstructorvariant has no kind or logging of its
own: the derive refuses kind and log on itthe deriver refuses [@kind], [@level] and [@fields] on itits own entries in levels and fields are never read.
How a message prints
An observer can print any payload. It prints a message by its Debug form, from #[derive(Debug)], which every field's type needs as well.It prints a message with its description's printer, through Message.pp_payload.It prints a message with its descriptor's printer, through debugPayload.
The ports print a payload alike, in Rust's Debug form:
Lamp(Dim { percent: 40 }).
The printer the deriver writes prints each field with the printer of the
field's type, found by name: pp_foo for a field of type foo, M.pp for
M.t, M.pp_foo for M.foo. The Debug module has them for the base
types (int, string, bool, float, char, bytes, …), and the
deriver itself handles lists, arrays, options and tuples of printable types.
Any other field type needs its printer in scope, so a first real message
type usually needs one of these:
[@@deriving debug], which makes the printer alone, for a type a message holds;- a printer written by hand with the
Debugmodule'stuple,recordand base printers, which print in the same form; [@debug_name "…"]on a constructor, the name to print for it, when the OCaml name differs from the Rust one. The constructors of two types in one module cannot share a name, so an Effect that carries out an Action of the same name is named apart, and keeps the Rust port's kind with[@kind]and its printed name with[@debug_name].
A type the deriver cannot print, such as an abstract one, takes one of two
options. ~pp:<printer> gives the printer by hand, a function of type
Format.formatter -> <type> -> unit: it is bound as pp_<type>, so the
message and the printers of types that hold this one all use it, and it may
name the type's own constructors and fields. ~pp:Causet.Debug.opaque is
the one-liner for a type whose values print as _ but that other types
hold. ~no_pp leaves the printer out altogether: the message's values
print as _, and a type that holds this one needs a printer of its own.
The printer reads a value's shape and prints it as Rust's Debug prints
the type it stands for: a tagged value as the variant its kind names (the
last segment in CamelCase: lamp.dim is Dim), with its other fields in
order, each under its name in snake case as the Rust port names it
(steepSecs prints as steep_secs); a string quoted, a whole number as an
integer, an array as a list, undefined as None. Where the Rust name is
not the one the kind tells, as for a variant whose kind is given in full or
a struct of one kind, the descriptor's debugNames gives it. A value of a
class that should print otherwise, such as a newtype, prints itself with a
[debugCustom] method, written with the Debug module's printers. A form
no shape tells takes a printer by hand, the descriptor's debug option: a
tuple variant, a float that holds a whole number (Rust's 4.0), or an
optional field that holds a value (Rust's Some(4)). Since a kind is not a
TypeScript name, an Action and an Effect of the same name need nothing
apart.
(* A field of type [cup_id] is printed by [pp_cup_id]: [@@deriving debug]
makes it. *)
type cup_id = Cup_id of int [@@unboxed] [@@deriving debug]
(* A field of type [Millilitres.t] by [Millilitres.pp], written here with
[Debug], which prints as Rust's [Debug] does. *)
module Millilitres = struct
type t = int
let pp f n = Debug.tuple f "Millilitres" [ (fun f -> Debug.int f n) ]
end
type tea_action =
| Pour of { cup : cup_id; amount : Millilitres.t }
| Rinse of cup_id list
[@@deriving message ~name:"tea.action"]
(* The Effect that carries out a Pour is named apart, as one OCaml module
needs, and keeps the Rust port's kind and printed name. *)
type tea_effect =
| Pour_effect of { cup : cup_id } [@kind "tea.pour"] [@debug_name "Pour"]
[@@deriving message ~name:"tea.effect"]
let () =
let show pp v = Debug.to_string pp v in
assert (
show pp_tea_action (Pour { cup = Cup_id 1; amount = 250 })
= "Pour { cup: CupId(1), amount: Millilitres(250) }");
assert (
show pp_tea_action (Rinse [ Cup_id 1; Cup_id 2 ]) = "Rinse([CupId(1), CupId(2)])");
assert (
show tea_effect_message.pp (Pour_effect { cup = Cup_id 1 }) = "Pour { cup: CupId(1) }")import assert from "node:assert/strict";
import { Debug, debugCustom, message } from "causet";
// A field is printed by its shape: a string quoted, a number as an
// integer, an array as a list, a tagged value as its variant. A value of a
// class prints itself with `[debugCustom]`, here as Rust's newtypes do.
class CupId {
readonly id: number;
constructor(id: number) {
this.id = id;
}
[debugCustom](): string {
return Debug.tuple("CupId", [Debug.int(this.id)]);
}
}
class Millilitres {
readonly ml: number;
constructor(ml: number) {
this.ml = ml;
}
[debugCustom](): string {
return Debug.tuple("Millilitres", [Debug.int(this.ml)]);
}
}
type TeaAction =
| { readonly kind: "tea.pour"; readonly cup: CupId; readonly amount: Millilitres }
| { readonly kind: "tea.rinse"; readonly cups: readonly CupId[] };
// Rinse is a tuple variant in Rust, a form no shape tells: the descriptor
// prints it by hand, and every other value by its shape.
const teaAction = message<TeaAction>("tea.action", {
debug: (a) =>
a.kind === "tea.rinse"
? Debug.tuple("Rinse", [Debug.list(Debug.debugValue, a.cups)])
: Debug.debugValue(a),
});
// The Effect that carries out a Pour shares its kind and its printed name:
// nothing needs naming apart.
type TeaEffect = { readonly kind: "tea.pour"; readonly cup: CupId };
const teaEffect = message<TeaEffect>("tea.effect");
// A type of one kind is a struct in Rust, whose name its kind does not
// tell: `debugNames` gives it. Fields print in snake case, as Rust names them.
interface SteepTimer {
readonly kind: "tea.steep";
readonly cup: CupId;
readonly steepSecs: number;
}
const steepTimer = message<SteepTimer>("tea.timer", {
debugNames: { "tea.steep": "SteepTimer" },
});
assert.equal(
teaAction.debug({ kind: "tea.pour", cup: new CupId(1), amount: new Millilitres(250) }),
"Pour { cup: CupId(1), amount: Millilitres(250) }",
);
assert.equal(
teaAction.debug({ kind: "tea.rinse", cups: [new CupId(1), new CupId(2)] }),
"Rinse([CupId(1), CupId(2)])",
);
assert.equal(teaEffect.debug({ kind: "tea.pour", cup: new CupId(1) }), "Pour { cup: CupId(1) }");
assert.equal(
steepTimer.debug({ kind: "tea.steep", cup: new CupId(1), steepSecs: 180 }),
"SteepTimer { cup: CupId(1), steep_secs: 180 }",
);Writing one by hand
The derives coverderiver coversdescriptor's defaults cover variants and structsrecordstagged values. When a kind depends on more than the variantconstructortag, write the description yourself.
Implement Message: TYPE and kind(), and log_level() and
log_fields() when they are not the defaults (debug, and no fields). Then
implement the category's marker trait, which has no methods. The timer's
Event, TimerFired, is written this way, and so is the p2p example's
Action: a struct around a private enum, so that a parent can build only an
Intent, with a kind for each variant of the enum inside.
Build the Message.t yourself. Message.make ~name ~kind () takes a
function from a value to its kind, and ~level, ~fields and ~pp when
they are not the defaults (debug, no fields, and a printer of _).
Message.single name is a type of one kind, its name. The timer's Event,
Timer.fired, is made this way.
Give message the kind as a function, kind: (value) => …, as a type
whose values carry no tag must; and level, levels, fields and
debug when they are not the defaults (debug, no fields, and the printer
that reads the value's shape).
use causet::{Event, LogLevel, Message};
/// A thermometer tick, too frequent to log above trace.
#[derive(Debug)]
struct Tick {
reading: u32,
}
impl Message for Tick {
const TYPE: &'static str = "kettle.tick";
fn kind(&self) -> &'static str {
Self::TYPE
}
fn log_level(&self) -> LogLevel {
LogLevel::Trace
}
}
impl Event for Tick {}
let tick = Tick { reading: 21 };
assert_eq!(tick.kind(), "kettle.tick");
assert_eq!(tick.log_level(), LogLevel::Trace);
assert_eq!(format!("{tick:?}"), "Tick { reading: 21 }");open Causet
(* A thermometer tick, too frequent to log above trace. *)
type tick = { reading : int }
let tick_message : tick Message.t =
Message.single
~level:(fun _ -> Message.Trace)
~pp:(fun f t -> Debug.record f "Tick" [ ("reading", fun f -> Debug.int f t.reading) ])
"kettle.tick"
let () =
let tick = { reading = 21 } in
assert (tick_message.kind tick = "kettle.tick");
assert (tick_message.level tick = Message.Trace);
assert (Debug.to_string tick_message.pp tick = "Tick { reading: 21 }")import assert from "node:assert/strict";
import { Debug, message } from "causet";
/** A thermometer tick, too frequent to log above trace. It carries no tag. */
interface Tick {
readonly reading: number;
}
const tick = message<Tick>("kettle.tick", {
kind: () => "kettle.tick",
level: "trace",
debug: (t) => Debug.record("Tick", [["reading", Debug.int(t.reading)]]),
});
const reading: Tick = { reading: 21 };
assert.equal(tick.kind(reading), "kettle.tick");
assert.equal(tick.level(reading), "trace");
assert.equal(tick.debug(reading), "Tick { reading: 21 }");What fails to compile
The derives refuseThe deriver refusesThe type checker refuses, at compile time, anything that would otherwise be guessed or left out:
- a type with no name;
- a nested variant that holds anything but exactly one unnamed field,
and a nested one with a
kindor alog;a nested constructor that holds anything but one argument of a message type, and a nested one with a[@kind],[@level]or[@fields];a kind the union does not have, in a value or as a key oflevels,fieldsornested; - an attributeattributeoption it does not know, such as a misspelt
#[causet(knd = "…")][@causet.knd]levles; - a type-level
kindon an enum: give the variants kinds, or set the prefix;a type-level~kindon a variant type: give the constructors kinds, or set the prefix;a type whose values carry nokindtag, unless its kind is given by hand; - logged fields for a whole enum, or fields that are not named.logged fields for a whole variant type, or fields that are not named.a logged field that values of its kind do not have.
// error: missing `#[causet(type = "...")]`: the type's name
#[derive(Debug, causet::Action)]
enum KettleAction {
SwitchOff,
}import { message } from "causet";
type KettleAction = { readonly kind: "kettle.switch_off" };
// error: Expected 1-2 arguments, but got 0: the type's name is required
export const kettleAction = message<KettleAction>();#[derive(Debug, causet::Action)]
#[causet(type = "lamp.action")]
enum LampAction {
Unplug,
}
// error: a `nested` variant holds exactly one unnamed field: the inner message
#[derive(Debug, causet::Action)]
#[causet(type = "room.action")]
enum RoomAction {
#[causet(nested)]
Lamp { lamp: LampAction },
}A type with no name fails with
[@@deriving message] needs ~name, the type's name; a nested
constructor of no argument, or of several, with
a nested constructor holds exactly one message; and one with a kind with
a constructor is either [@nested] or has a [@kind], not both. Each error
points at the attribute or option at fault.