An experimental library to build reactive web applications in Ocaml, inspired by lwd, bonsai, and others.
README.md

brote #

A reactive engine for dynamic UIs in OCaml: incremental signals with cutoff and keyed-stable collections, on a stdlib-only core that compiles to native and to JavaScript.

The reactive graph runs in the browser (via js_of_ocaml) or a native process, not on the server. The wire carries state deltas, not HTML, and each client computes its own view locally.

Packages #

Package Deps What it is
brote stdlib only the engine (Signal) + the data/sync layer (Net, Sync, Collab, Crdt_map, App, Json)
brote_web brote, brr reactive HTML/SVG components on the live DOM + an auto-reconnecting WebSocket transport
brote_hcs brote, hcs, simdjsont server adapter: serve a Sync/Collab collection over a WebSocket (per-connection writer fiber, slow-client backpressure)
brote_hive brote, hive, swim optional cluster adapter: replicate a Sync/Collab collection across nodes
ppx_brote_json ppxlib, brote derive to_json/of_json over Brote.Json.value (records, enums, payload + recursive variants, optional fields)

The engine is view-agnostic: the view/element type lives in the adapter, not the core.

The model #

Three nouns and one rule.

  • Source ('a Signal.source) — the only mutable input; where change enters.
  • Signal ('a Signal.t) — a value derived from sources with map/both; recomputed incrementally. Cutoff (~equal) stops a recomputation from propagating when the value did not actually change.
  • Node — your UI, built once from signals with reactive holes that patch in place. No virtual DOM, no re-render of the page: an attribute or a text changes where it is, and a list that changes shape (el_dyn, keyed) rebuilds its children (only the ones that changed, for keyed).

The rule: structure is static, values are dynamic. Don't branch structure with bind; branch data with signals and vary collections with assoc / Brote_web.keyed. That keeps value updates O(what changed) and keeps local state (focus, scroll, selection) alive across updates. For a long list that rows join and leave (a feed, a big table fed by Net.Rmap, Sync or Collab), use Brote_web.el_rows: it follows the collection's changes, so a row joining costs one DOM call at 20,000 rows as at 20, where keyed re-reads every row (about 2 µs each) on each structural change.

Data flows one way; events flow back as callbacks that set a source, or, when state transitions must all be applied in order, as actions sent to a Brote.Machine (an Elm-style reducer over a signal, with effects as data; see doc/machine.mld):

  source ──get──▶ signal ──map──▶ node ──mount──▶ DOM
     ▲                                              │
     └──────────────── on_click (set source) ◀──────┘
open Brote_web
open Brote.Signal.Syntax

let counter () =
  let n = Brote.Signal.source 0 in
  div [ class_ "counter" ] [
    button [ on_click (fun () -> Brote.Signal.update n ~f:pred) ] [ txt' "-" ];
    span [] [ txt (let+ v = Brote.Signal.get n in string_of_int v) ];
    button [ on_click (fun () -> Brote.Signal.update n ~f:succ) ] [ txt' "+" ];
  ]

let () = run counter

Live data over WebSockets #

Brote.Net turns an injected transport into reactive state — a typed Channel, a Store (a CRDT is a store whose reduce is its merge), and an Rmap (one fine-grained source per key, feeding keyed for high-fan-out feeds). Brote_web.Ws.transport url provides the browser WebSocket, which reconnects automatically (exponential backoff + jitter) and buffers sends while down; because a reconnect is a fresh server connection, brote_hcs re-ships its snapshot, so Sync/Collab clients resync automatically. Removed keys are tombstones in the CRDT — bound their growth with Crdt_map.gc / Collab.Server.gc for long-lived collections.

Serving it safely. Mount the socket as a route and upgrade it with Brote_hcs.upgrade ~origin ~secure req (Brote_hcs.serve_collab ~server), which checks the request's Origin first (the ~origin policy is required). Do not register it with Hcs.Endpoint.websocket: hcs's default there is to accept any origin, so any web page the user visits could open the socket. The serve_* functions also bound each connection's queued bytes and inbound message rate, serve_collab ?accept is the hook for per-key authorization, and Collab.Server.create ?max_keys caps what clients can create.

When hcs terminates TLS itself (Hcs.Server.with_tls, hcs 0.39), upgrade reads that from the request and expects an https origin whatever ~secure is; ~secure:true is for a proxy that terminates TLS, which hcs sees as plain HTTP and which a forwarded header cannot be trusted to describe.

Two more things come with hcs 0.38. ~compression:(Hcs.Websocket.permessage_deflate ()) on upgrade (and on the serve_* call, so a broadcast is compressed once for all its connections) shrinks the feed several times over; it leaks how well a message compresses, so use it only where no frame mixes a secret with text a client chooses. The sessions also cap the size a connection may send (?byte_rate), because a compressed frame of a kilobyte can inflate to the message limit. And brote_web runs under hcs's Security_headers.strict policy (no inline script, no inline style, no eval): it assigns inline styles through the CSSOM, which style-src 'self' allows. A WebSocket on another origin needs with_connect_src. Since hcs 0.39 that policy also sends HSTS by default on connections hcs terminates TLS on, and browsers that have seen it refuse plain HTTP to the host for a year: serve TLS with strict only if that is what you mean (with_hsts Off otherwise).

Examples #

  • examples/counter/, examples/hello/, examples/todo/ — the engine and the DOM DSL in the small.
  • examples/components/ — the ready-made Brote_web.Components (a time-series line chart with hover crosshair/tooltip, a <meter> bar-gauge panel, and a sortable data table with in-cell bars), each fed a signal of plain data. Its app.css is a starter theme — the components ship unstyled, so it doubles as a worked example of styling them.
  • examples/collabtable/ — a multi-writer Collab grid that converges across browsers.
  • examples/trading-floor/ — the most complete example: an event-sourced limit-order-book matching engine streaming to many browsers, modelled with domain-driven design. Its lib/ is the domain (compiled to native and JavaScript, so both ends share one protocol definition); lib/floor_web/ is an araara-style hcs server; client/ is the layered brote client (a live table with SVG, a sector heatmap, an order ticket, private portfolios, a trades tape, and CRDT chat); and bin/ opts into clustering via brote_hive in a few lines. Who a browser is comes from a signed session cookie, not from anything it sends: the socket and the order API read the trader from it (FLOOR_SESSION_SECRET is the signing secret; set it so that sessions survive a restart). Tests live in examples/trading-floor/test/ (native unit/property tests, plus the checks identity_smoke.mjs (plain HTTP and WebSocket), browser_smoke.mjs, reconnect_smoke.mjs, reconnect_rows.mjs, drop_smoke.mjs, session_recovery_smoke.mjs, compression_smoke.mjs, tls_smoke.mjs and half_open_smoke.mjs). The page shows its link to the server (live, reconnecting, out of date, session ended) and reloads itself when its session is no longer good or the wire changed. FLOOR_TLS_CERT and FLOOR_TLS_KEY make the server speak https itself.
dune build
PORT=8096 FLOOR_STATIC=$PWD/examples/trading-floor/priv/static \
  ./_build/default/examples/trading-floor/bin/main.exe
# open http://localhost:8096

Build & test #

dune build
dune runtest          # example + property (qcheck) tests for the engine

The browser checks are run by hand (they need Playwright and a Chromium, and the last three a built floor server): web/test/keyed_smoke.mjs (after dune build web/test/keyed.bc.js), web/test/csp_smoke.mjs (after dune build web/test/csp.bc.js), web/test/rows_smoke.mjs (after dune build web/test/rows.bc.js), web/test/int64_smoke.mjs and web/test/transport_smoke.mjs and web/test/components_smoke.mjs (after building int64.bc.js, transport.bc.js and components.bc.js), web/test/perf_probe.mjs (a measurement, after dune build web/test/perf.bc.js) and the scripts in examples/trading-floor/test/ (half_open_smoke.mjs takes about a minute). Point PLAYWRIGHT at the playwright module and CHROME at the browser binary, e.g. PLAYWRIGHT=/usr/lib/node_modules/playwright CHROME=/usr/bin/chromium node web/test/keyed_smoke.mjs. ENGINE=webkit (with CHROME at Playwright's pw_run.sh) runs the same scripts on WebKit, Safari's engine; they all pass there too. Firefox is not covered.