lily/client
The client owns the browser-side Runtime, pretty much
everything that makes a Lily app tick in the page. The update loop,
component subscriptions, and (once a transport is connected) keeping your
model in sync with the server all live here. A connector can hold messages
while you’re disconnected and replay them the moment the server is back,
see with_offline_queue. On
Erlang it does nothing, letting shared code compile.
A frontend comes together as one pipeline, build a
Store with store.new (and
store.sync if you have a server), start the runtime
with start, mount your components,
pipe on your event handlers, and connect to the server:
import lily/client
import lily/component
import lily/transport
pub fn main() {
shared.store()
|> client.start
|> component.mount(
selector: "#app",
to_html: element.to_string,
to_placeholder: fn() { element.element("lily-nest", [], []) },
view: app,
)
|> client.connect(with: transport.websocket("/ws"))
}
If you aren’t syncing with a server, stop after mount, the runtime is
perfectly happy on its own. When you are, the topics this client listens to
come from the store’s subscriptions function, and Lily subscribes and
unsubscribes as your model changes (see store).
To feed messages in from outside your components, a timer, a callback, an
FFI shim, grab a dispatch function with dispatch:
let dispatch = client.dispatch(runtime)
dispatch(Increment)
Everything you dispatch, plus every frame the server sends, runs through a single message queue, meaning your update function is only ever called one message at a time even when several land at once. That ordering is what keeps optimistic client updates from racing the server’s authoritative snapshots.
For client-side reactions that don’t belong in update, focus management,
analytics, kicking off a fetch, register an observer with
observe. It sees every ClientEvent with
the full model, from an applied message to a connection opening or a
fresh server snapshot. Routing, persistence, connection status and hot
reload are built on that same seam and live in
lily/browser.
Because the wire only ever carries messages, an offline client keeps
working and catches up on reconnect. A message the store routes to Local
stays on this client.
Your own messages apply straight away and stay applied until the server
answers them. If another client’s update lands in between, or the server
refuses one of yours, you may have applied things in a different order
from the server. Once everything you sent to that topic (or the session)
is answered, the client fetches the server’s copy and plays whatever you
sent since back on top of it through your update, meaning clients agree
again after concurrent edits. A reconnect does the same, edits made
offline included.
A message in flight when a connection drops is sent again, applied exactly
once within server.session_grace and at
most once past it.
Lily doesn’t need to know whether your messages commute. It only replays
your own messages through your own update on top of the server’s state,
which suits CRDT style messages (they converge whatever the order) as well
as OT style ones (a message that transforms against the version it was
made on sees the newer one). Keep update free of side effects, it can
run more than once for the same message.
An update that crashes is logged and skipped, and whatever was queued behind it still runs.
Each Runtime is fully isolated, letting several coexist on
one page, but we’d steer you towards one runtime per page. Splitting your
state across many runtimes gets hard to reason about fast (badly designed
React apps with state scattered everywhere come to mind). If you need
independent, self-contained stateful widgets, a different framework might
suit you better.
Types
Something that happened to the runtime, given to every observer
registered with observe.
Match the variants you care about and ignore the rest with a catch-all, new variants are not a breaking change.
pub type ClientEvent(model, message) {
ClientIdAssigned(client_id: String)
ConnectionClosed
ConnectionOpened
Diagnostic(level: transport.DiagnosticLevel, message: String)
MessageApplied(message: message, origin: MessageOrigin)
ModelUpdated
ProtocolMismatch(server: Int, client: Int)
SnapshotApplied(target: transport.SyncTarget, previous: model)
SnapshotUnchanged(target: transport.SyncTarget)
SubscriptionRejected(
topic_id: String,
reason: transport.RejectionReason,
)
VersionAnnounced(hash: String)
}
Constructors
-
ClientIdAssigned(client_id: String)The server gave this client an id, on every connect and reconnect
-
ConnectionClosedThe connection dropped
-
ConnectionOpenedThe connection opened, including the first time
-
Diagnostic(level: transport.DiagnosticLevel, message: String)A warning from Lily itself
-
MessageApplied(message: message, origin: MessageOrigin)updateran for a message, from this client or from a server frame -
ModelUpdatedupdate_modelran -
ProtocolMismatch(server: Int, client: Int)The server speaks another wire protocol, the connection is closed for good
-
SnapshotApplied(target: transport.SyncTarget, previous: model)The server replaced a slice of the model,
previousis the model before -
SnapshotUnchanged(target: transport.SyncTarget)A resync found the slice already current, nothing was replaced
-
SubscriptionRejected( topic_id: String, reason: transport.RejectionReason, )The server refused a subscription
-
VersionAnnounced(hash: String)The server’s build version, on every connect and reconnect
Where an applied message came from.
pub type MessageOrigin {
Dispatched
Received
}
Constructors
-
DispatchedDispatched on this client, through
dispatchor a listener -
ReceivedArrived from the server
Values
pub fn connect(
runtime: Runtime(model, message, store.Synced),
with connector: transport.Connector,
) -> Runtime(model, message, store.Synced)
Connects the runtime to a server, usually the last step of your pipeline.
The connector comes from
transport.websocket, or from
transport.connector for a transport of your
own. Edits made offline before a reload show up in the model straight away.
import lily/transport
runtime
|> client.connect(with: transport.websocket("/ws"))
pub fn dispatch(
runtime: Runtime(model, message, mode),
) -> fn(message) -> Nil
Gets a function that sends messages to the runtime, for updates from outside your components like fetch callbacks and timers.
let runtime = client.start(shared.store())
let dispatch = client.dispatch(runtime)
fetch("/api/data", fn(response) {
dispatch(DataReceived(response))
})
pub fn model(runtime: Runtime(model, message, mode)) -> model
The current model.
let count = client.model(runtime).count
pub fn observe(
runtime: Runtime(model, message, mode),
observer: fn(ClientEvent(model, message), model) -> Nil,
) -> Runtime(model, message, mode)
Calls a function with every ClientEvent and the model
after it, for side effects that don’t belong in update. Observers add up.
A message it dispatches or a change it makes runs once the current event is
done. Calling update_model on every ModelUpdated loops
forever.
runtime
|> client.observe(fn(event, model) {
case event {
client.ConnectionClosed -> show_offline_toast()
_ -> Nil
}
})
pub fn start(
store: store.Store(model, message, mode),
) -> Runtime(model, message, mode)
Starts the client runtime from a store, the first step of your frontend.
Only a store passed through store.sync can
connect to a server. A page with an
store.embed starts from that model.
let runtime = client.start(shared.store())
runtime
|> component.mount(
selector: "#app",
to_html: element.to_string,
to_placeholder: fn() { element.element("lily-nest", [], []) },
view: app,
)
pub fn update_model(
runtime: Runtime(model, message, mode),
with change: fn(model) -> model,
) -> Nil
Changes the model without sending anything to the server.
Observers see it as ModelUpdated.
client.update_model(runtime, with: fn(model) {
Model(..model, menu_open: False)
})