brote — reactive UIs in OCaml

Build reactive browser UIs in OCaml with brote, using signals, typed views and shared types across client and server.

When to use brote

araara's default frontend is hypermedia. A route returns HTML, htmx swaps it into the page, and rendering happens on the server. The frontend guide describes this approach and when it fits an application.

brote is for interfaces such as a canvas, a live dashboard, or an editor, where the client holds state and updates many times a second. In this case the server sends state deltas, which are small messages describing what changed. Each client keeps a copy of the data and computes its view in OCaml compiled to JavaScript. Server and client are written in one language and can share types.

brote is an independent library that works with araara. The brote_hcs adapter serves live collections over an hcs WebSocket, and brote_hive replicates them across a hive cluster. A server that renders htmx pages can also serve a brote client.

The packages

brote is five packages. The core depends only on the standard library. Adapters add a browser, a server, or a cluster dependency when they are used.

Package Depends on What it is
brote stdlib only the engine (Signal) and the data layer (Net, Sync, Collab, Crdt_map, App, Json)
brote_web brote, brr reactive HTML/SVG on the live DOM, plus an auto-reconnecting WebSocket transport
brote_hcs brote, hcs, simdjsont server adapter: serves a Sync/Collab collection over an hcs WebSocket
brote_hive brote, hive, swim cluster adapter: replicates a Sync/Collab collection across nodes
ppx_brote_json ppxlib, brote [@@deriving brote_json]: derives to_json/of_json over Brote.Json.value

The engine does not handle display. It does not refer to a specific kind of UI element. Each adapter defines what an element is, such as a browser DOM node. The brote core builds for native code and for JavaScript without change.

The model

brote's model has three parts: a source, a signal, and a node.

  • A signal ('a Signal.t) is a value that changes over time. Anything built from a signal recomputes automatically when it changes, so you describe how a value is derived once and brote keeps it up to date. You build new signals from existing ones with map / both. By default a recomputation propagates even when the result is unchanged; a cutoff (~equal) tells brote to skip the rest of the work when the new value equals the old one.
  • A source ('a Signal.source) is an input signal that new values are pushed into. Change enters the graph through a source, and other signals are derived from it.
  • A node is a piece of rendered UI. It is built once from signals, leaving reactive holes that are patched in place as those signals change. Updates patch the existing elements rather than re-rendering the whole tree, and there is no virtual DOM.

Keeping the shape of the UI fixed and changing the values inside it limits the work per update. Using bind to swap whole branches of UI as data changes discards the existing elements and rebuilds them. Rebuilding can cost more and loses local state such as focus, scroll position, and selection. Branching on data with signals, and varying the items in a collection with assoc / Brote_web.keyed, reuses the elements that did not change.

Data flows one way; events flow back as callbacks that set a source. A counter shows the model:

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

txt takes a signal and patches that text node when n changes; the surrounding div and buttons are built once. let+ / and+ are the applicative syntax for composing signals.

Live data over WebSockets

Brote.Net builds reactive state on a transport. A transport has three operations: send, receive, and status. brote depends only on the standard library, so a browser socket, a test double, or a link to another cluster node can act as a transport if it provides those operations. Brote.Net treats them in the same way. On top of it:

  • a typed Channel carries one logical stream of values;
  • a Store is an Elm-style reducer over incoming messages (a CRDT is a store whose reduce is its merge);
  • an Rmap is a local reactive keyed map with one fine-grained source per key, which feeds keyed for high-fan-out feeds;
  • a Mux multiplexes several logical channels over one transport, length-framed and tagged, so one WebSocket carries many streams.

Two higher-level collections sit on that layer:

  • Sync: one-writer replicated keyed collections. A Sync.Server is authoritative; Sync.Client is a read-only mirror that exposes entries, find, and a values_signal.
  • Collab: multi-writer collaborative keyed collections backed by a last-writer-wins Crdt_map. Each Collab.Client can set / remove, and replicas converge.

In the browser you connect a stream or a collection to a transport and get a client back:

val connect_stream :
  transport:Brote.Net.Transport.t -> ('k, 'v) Brote.App.stream -> ('k, 'v) Brote.Sync.Client.t

val connect_collection :
  transport:Brote.Net.Transport.t -> ('k, 'v) Brote.App.collection -> ('k, 'v) Brote.Collab.Client.t

Brote_web.Ws.transport url provides the browser WebSocket. It reconnects automatically, using exponential backoff with jitter, and buffers sends while it is down. A reconnect is a new server connection, so brote_hcs sends its snapshot again and Sync / Collab clients resync. Removed keys are tombstones in the CRDT. Their growth can be bounded with Crdt_map.gc / Collab.Server.gc for long-lived collections.

ppx_brote_json and shared wire types

The wire types are ordinary OCaml records and variants with [@@deriving brote_json], which generates to_json / of_json over the backend-neutral Brote.Json.value. Compiling the same module to native code and to JavaScript gives both ends the same definition.

type tick = {
  last : int;  (* last trade price, cents *)
  bid : int;  (* best bid in cents, 0 when the side is empty *)
  ask : int;  (* best ask in cents, 0 when the side is empty *)
}
[@@deriving brote_json]

type order_response =
  | Accepted_response of { filled : int; avg : int; resting : int; cash : int } [@json.name "accepted"]
  | Routed_response of { owner : string } [@json.name "routed"]
  | Rejected_response of { reason : string } [@json.name "rejected"]
[@@deriving brote_json]

It handles records, string enums, payload variants (with [@json.name] to control the tag), recursive and mutually-recursive types, and optional fields. An optional field set to None is omitted from the output instead of being written as null.

An App descriptor names a stream, collection, or command and pairs it with its key and value codecs. Both ends refer to this descriptor:

let value to_json of_json = App.Value.make ~to_json ~of_json

let quotes = App.stream ~name:"floor.quotes" ~key:App.Key.string ~value:(value tick_to_json tick_of_json) ()
let chat   = App.collection ~name:"floor.chat" ~key:App.Key.string ~value:(value chat_msg_to_json chat_msg_of_json) ()
let control = App.command ~name:"floor.control" ~value:(value control_to_json control_of_json) ()

brote_hcs — serving live state

brote_hcs exposes a Sync or Collab server as an hcs WebSocket handler. The serve_sync function sends the snapshot, streams each delta, and routes inbound messages to an on_command callback:

val serve_sync :
  ?max_message_bytes:int ->
  server:('k, 'v) Brote.Sync.Server.t ->
  on_command:(string -> unit) ->
  Hcs.Websocket.t ->
  unit

Each connection has a writer fiber that drains a bounded mailbox. A slow client fills its own mailbox without blocking the producer for other connections. A client that falls too far behind is disconnected. Authentication and origin checks belong to the WebSocket upgrade policy at the endpoint.

When one socket must carry several streams, serve gives the connection as a Net.Transport.t to multiplex. The trading floor runs six streams (quotes, leaderboard, trades, a private portfolio, chat, and control) over a single WebSocket in this way:

let handler ~exchange ~sim ~room ~router ws =
  Brote_hcs.serve ws ~setup:(fun transport ->
      let mux = Mux.create transport in
      let q = Mux.channel mux "q" in
      let detach_q = Sync.Server.attach (Exchange.quotes_server exchange) ~send:q.T.send () in
      q.T.on_message (fun raw ->
          match App.decode_command Wire.control raw with Some c -> Sim.apply_control sim c | None -> ());
      let c = Mux.channel mux "c" in
      let client = Collab.Server.attach (Chatroom.room room) ~send:c.T.send in
      c.T.on_message (Collab.Server.receive (Chatroom.room room) client);
      fun () -> detach_q (); Collab.Server.detach (Chatroom.room room) client)

brote_hive — replicating across a cluster

For a clustered deployment, brote_hive replicates a Sync or Collab server across the nodes of a joined hive.cluster.swim membership. A Sync stream replicates from its single writer to read-only mirrors on each node. A Collab collection merges as a CRDT, so each node is a writer and the replicas converge.

ignore (Brote_hive.replicate_collection Wire.chat ~server:(Floor.Chatroom.room room) ~node ~name:"floor-chat");
ignore (Brote_hive.replicate_stream Wire.quotes ~server:(Floor.Exchange.quotes_server exchange) ~node ~name:"floor-quotes");

Replication is loop-free (it gossips only local ops, dedups by sequence, and merges idempotently), so a browser connected to any node sees one converging market and one shared chat log. The trading-floor tutorial ends by switching the same application from single-node to clustered with these lines.

In a full application

Where this fits: brote works alongside the hypermedia frontend. An araara application can render most pages on the server with htmx and use a brote client on screens that need client-side state. The brote_hcs adapter lets the same hcs endpoint serve both. The frontend guide covers the default path and the other options. The tutorial builds a complete brote application.