lily/transport
This is how Lily deals with the communication between client/browser and
the server, ensuring that the centralised model within
Store on both sides remains in sync by exchanging
serialised Protocol messages. For most use cases, this
module won’t be needed but the details below will be helpful, especially
if you want to supply your own transport layer.
It works on both Erlang and JS targets since both ends need it, although the WebSocket connector only connects in a browser.
The wire format is the Protocol exchanged. A
Serialiser is built with automatic for
any Gleam type, or with serialiser from your own encoders
and decoders. The connectors are websocket (with automatic
reconnection and offline queueing), connector (to wrap a
transport of your own), and with_offline_queue
(to give it the same queueing and replay).
When a connection opens, the server sends Version and then Connected,
and the client answers that with a Resync with the session name and every
topic it wants to subscribe to, each naming the state it already holds when
it can, and the token from the last Connected to resume a session. A
client on another wire protocol stops at Version instead. The server
replies with a Snapshot per target, or Unchanged for one the client
already holds as it is, then each message travels as a numbered
SessionMessage or TopicMessage and comes back to the other subscribers
as an update. The sender gets an Acknowledge, or a Dropped when the
server didn’t apply it.
For most apps, use transport.automatic for
serialisation and transport.websocket to connect.
import lily/client
import lily/transport
pub fn main() {
let runtime = client.start(shared.store())
client.connect(runtime, with: transport.websocket("/ws"))
}
With the default functions Lily gives you, the communication is done
through JSON when a page is served from localhost, 127.0.0.1 or
[::1] and MessagePack otherwise. This is mainly to make dev environments
have more debuggable frames and smaller transport frames for prod.
To use one format consistently (everywhere), build the serialiser yourself
and pass it to store.sync_with:
transport.automatic(
format: transport.MessagePack,
max_decode_depth: 128,
modules: [transport.module("my_shared")],
)
The automatic serialiser uses positional encoding. Each custom type is a
map like {"_":"ConstructorName","0":field0,"1":field1}. On JavaScript,
constructors must be registered so the decoder can reconstruct them.
To register constructors, name the compiled modules that define the
types you’re sending via the wire when you build the store.
store.new(init: initial_model(), update: update)
|> store.sync(
route: route,
modules: [
transport.module("my_shared"),
transport.module_in(package: "other_package", path: "other/types"),
],
)
The automatic serialiser builds whatever constructors a frame names, so a
hostile client can put a String where your message has an Int. A
Schema built with schema and piped into
store.schema has the server drop such a message
instead.
This also means that constructor names that cross the wire must be unique (per arity) across the modules as the browser matches on name and arity alone. Lily should warn you in the browser when this happens. For unavoidable clashes (e.g. you have two deps that share constructors), it might be worth it to create your own types and conversion functions.
Types
What a transport gives the client, a function to send a frame and one to close the connection.
send returns Error when the frame didn’t go out, letting
with_offline_queue hold it and send it later.
pub type Channel {
Channel(
send: fn(BitArray) -> Result(Nil, Nil),
close: fn() -> Nil,
)
}
Constructors
-
Channel( send: fn(BitArray) -> Result(Nil, Nil), close: fn() -> Nil, )
A way for the client to reach the server. Build one with
websocket or connector and pass it to
client.connect.
pub opaque type Connector
The callbacks a transport calls. received for each frame from the
server, opened every time the connection opens (the first time included),
and closed when it is lost.
pub type ConnectorHandler {
ConnectorHandler(
received: fn(BitArray) -> Nil,
opened: fn() -> Nil,
closed: fn() -> Nil,
)
}
Constructors
-
ConnectorHandler( received: fn(BitArray) -> Nil, opened: fn() -> Nil, closed: fn() -> Nil, )
One constructor of a CustomDefinition, from
constructor.
pub opaque type ConstructorDefinition
A target in a Resync, with how far the client’s copy got.
pub type Cursor {
Unknown(target: SyncTarget)
Known(target: SyncTarget, epoch: Int, sequence: Int)
}
Constructors
-
Unknown(target: SyncTarget)Nothing the client can vouch for, it wants a
Snapshot -
Known(target: SyncTarget, epoch: Int, sequence: Int)The state at
sequencewithinepoch, from the lastSnapshotand what followed it, answered withUnchangedwhile that’s still current
A custom type’s constructors in a Schema, from
custom_type.
pub opaque type CustomDefinition
Severity of a Diagnostic from Lily.
pub type DiagnosticLevel {
Warning
Failure
}
Constructors
-
WarningSomething was dropped or refused, continues as usual
-
FailureLily gave up on something, a topic that kept crashing for example
Wire format the automatic serialiser encodes frames in.
transport.automatic(
format: transport.Json,
max_decode_depth: 128,
modules: [],
)
pub type Format {
Json
MessagePack
JsonOnLocalhost
}
Constructors
-
Json -
MessagePack -
JsonOnLocalhostJSON when served from
localhost,127.0.0.1or[::1], MessagePack otherwise.
The frames a client and server exchange. You only handle them yourself
when you write a serialiser of your own.
Sequence numbers count separately for each SyncTarget,
within an epoch the server names in each Snapshot, so the pair says
which state a client holds.
pub type Protocol(model, message) {
Acknowledge(target: SyncTarget, sequence: Int, id: Int)
Connected(
client_id: String,
resume: String,
answered: Int,
owner: String,
)
Dropped(target: SyncTarget, id: Int)
Rejected(topic_id: String, reason: RejectionReason)
Resync(
cursors: List(Cursor),
resume: option.Option(String),
delivered: Int,
)
SessionMessage(id: Int, payload: message)
SessionUpdate(sequence: Int, payload: message)
Snapshot(
target: SyncTarget,
epoch: Int,
sequence: Int,
state: model,
)
Subscribe(topic_id: String)
TopicMessage(topic_id: String, id: Int, payload: message)
TopicUpdate(topic_id: String, sequence: Int, payload: message)
Unchanged(target: SyncTarget)
Unsubscribe(topic_id: String)
Version(hash: String, protocol: Int)
}
Constructors
-
Acknowledge(target: SyncTarget, sequence: Int, id: Int)Server, confirming the
SessionMessageorTopicMessagewith thisidwas applied. A topic that stops sends every subscriber one withid0, answering no message. -
Connected( client_id: String, resume: String, answered: Int, owner: String, )Server, right after a client connects and again when it resumes a session, with the session’s id, the single-use token that resumes it, the highest message id it has answered and a fingerprint of the session’s seed, empty without one. A client observer sees it as
ClientIdAssigned. -
Dropped(target: SyncTarget, id: Int)Server, in place of an
Acknowledgewhen theSessionMessageorTopicMessagewith thisidwasn’t applied, such as one for a topic the client hasn’t joined, one that fails the schema, one the server refused under its rate limit or load, or one it has answered already. -
Rejected(topic_id: String, reason: RejectionReason)Server, when a
Subscribeis refused or an admitted topic is revoked. -
Resync( cursors: List(Cursor), resume: option.Option(String), delivered: Int, )Client, after it connects, listing every target it wants a
Snapshotof, with the state it holds when it can vouch for it. The first one on a connection carries the token from the lastConnected, to resume that session, and the highest message id this page has sent. -
SessionMessage(id: Int, payload: message)Client, a message for its own session store. Ids count up from 1 across every message a page sends.
-
SessionUpdate(sequence: Int, payload: message)Server, a session update sent by
server.dispatch_toorserver.dispatch_to_all. -
Snapshot( target: SyncTarget, epoch: Int, sequence: Int, state: model, )Server, the whole state of a target, in reply to
ResyncorSubscribe, atsequencewithinepoch. -
Subscribe(topic_id: String)Client, to join a topic. The server replies with
SnapshotorRejected. -
TopicMessage(topic_id: String, id: Int, payload: message)Client, a message for a shared topic store, its id counted with the session’s.
-
TopicUpdate(topic_id: String, sequence: Int, payload: message)Server, a topic message from another subscriber.
-
Unchanged(target: SyncTarget)Server, in place of a
Snapshotwhen theResynccursor named the state the target is still in. -
Unsubscribe(topic_id: String)Client, to leave a topic. Nothing is sent back.
-
Version(hash: String, protocol: Int)Server, on every connect, with a build identifier and the wire protocol version. See
browser.reload_on_new_version.
How the WebSocket connector waits between reconnection attempts.
transport.websocket_with(
url: "ws://localhost:8080/ws",
reconnect: transport.DefaultBackoff,
)
pub type Reconnect {
DefaultBackoff
Backoff(
base_milliseconds: Int,
max_milliseconds: Int,
jitter_ratio: Float,
multiplier: Float,
)
}
Constructors
-
DefaultBackoffExponential backoff with the built-in settings, the same as
Backoff(1000, 30_000, 0.25, 2.0). -
Backoff( base_milliseconds: Int, max_milliseconds: Int, jitter_ratio: Float, multiplier: Float, )Tuned exponential backoff.
base_millisecondsis the first delay, multiplied bymultiplierafter each failed attempt and capped atmax_milliseconds.jitter_ratiorandomises each delay by plus or minus that fraction, keeping clients dropped together from all reconnecting at once.transport.websocket_with( url: "ws://localhost:8080/ws", reconnect: transport.Backoff( base_milliseconds: 2000, max_milliseconds: 60_000, jitter_ratio: 0.25, multiplier: 2.0, ), )
Why the server refused or revoked a topic subscription.
pub type RejectionReason {
AccessDenied
NotFound
OverLimit
}
Constructors
-
AccessDeniedThe topic’s
Allowrule refused the client, or crashed -
NotFoundNo declaration claims the topic id, or the topic would not start
-
OverLimitA subscription, topic id or topic count cap was reached
The message types a client may send, checked by the server before it builds
a payload. Build it with schema and pipe it into
store.schema.
pub opaque type Schema
Turns Protocol frames into bytes and back. Build one with
automatic or serialiser.
pub opaque type Serialiser(model, message)
Which store a frame applies to, the per-connection session store or a named shared topic store.
pub type SyncTarget {
Session
Topic(id: String)
}
Constructors
-
Session -
Topic(id: String)
A field’s type in a Schema.
Variable is the enclosing custom type’s parameter by position, and
Anything skips the check, for opaque and external types.
pub type WireType {
IntType
FloatType
StringType
BoolType
NilType
ListOf(WireType)
DictOf(key: WireType, value: WireType)
SetOf(WireType)
TupleOf(List(WireType))
Custom(
module: String,
name: String,
parameters: List(WireType),
)
Variable(index: Int)
Anything
}
Constructors
Values
pub fn automatic(
format format: Format,
max_decode_depth max_decode_depth: Int,
modules modules: List(Module),
) -> Serialiser(model, message)
Creates a serialiser that encodes any Gleam value, with no codecs to write.
Pass it to store.sync_with.
format picks what this end writes, and it reads either format whatever
you pick. max_decode_depth caps how deeply a frame may nest, in either
format.
modules lists the modules that define the types you send. Constructor
names that cross the wire must be unique per arity across them.
transport.automatic(
format: transport.MessagePack,
max_decode_depth: 128,
modules: [transport.module("shared")],
)
Supported shapes
- Primitives,
Int,Float,String,Bool,Nil. AnIntmust be within 2^53 - 1 either side of zero, the range both targets hold exactly, aFloatmust be finite and aStringcan’t hold a lone surrogate. Encoding refuses anything else, and so does decoding. - Custom types, records and variants, a tagged map whose
_field carries the PascalCase constructor name. - Lists, as arrays.
- Tuples,
#(a, b)as tag-less maps with positional keys ({"0":a,"1":b}). gleam/dict.Dict, as{"_":"$dict","0":[[k,v],...]}.gleam/set.Set, as{"_":"$set","0":[v,...]}.
Not supported
A tuple whose first element is a Bool, Nil or a zero-field
constructor, #(True, x) say, looks like a custom type on Erlang and is
written as one. JavaScript reads it back as the tuple, unless a constructor
with that name and arity is registered, so keep such names distinct.
A one-field constructor of your own named Set holding a Dict looks
like gleam/set.Set on Erlang and is written as one, so name it something
else.
BitArray fields are not encoded, since on Erlang they can’t be told
apart from a String. Wrap raw bytes in a type of your own and write a
serialiser that base64-encodes them:
pub type Bytes {
Bytes(data: BitArray)
}
pub fn connector(
connect connect: fn(ConnectorHandler) -> Channel,
) -> Connector
Wraps a connect function as a Connector, for a transport
of your own.
connect gets the ConnectorHandler to call and
returns the Channel to send frames through. Wrap the result
in with_offline_queue to queue frames sent while
it is down.
pub fn constructor(
name name: String,
fields fields: List(WireType),
) -> ConstructorDefinition
A constructor and its field types, for a Schema.
transport.constructor(name: "SetName", fields: [transport.StringType])
pub fn custom_type(
module module: String,
name name: String,
constructors constructors: List(ConstructorDefinition),
) -> CustomDefinition
A custom type and its constructors, for a Schema.
transport.custom_type(module: "shared", name: "Message", constructors: [
transport.constructor(name: "Increment", fields: []),
])
pub fn decode(
bytes: BitArray,
serialiser serialiser: Serialiser(model, message),
) -> Result(Protocol(model, message), Nil)
Decodes bytes into a Protocol frame. A serialiser of your
own that crashes counts as a failure.
pub fn encode(
protocol: Protocol(model, message),
serialiser serialiser: Serialiser(model, message),
) -> BitArray
Encodes a Protocol frame into bytes, in the serialiser’s
format.
JsonOnLocalhost writes MessagePack where there is no page, such as on the
server.
The automatic serialiser raises for a value it can’t write, an Int past
the wire range, a non-finite Float or a lone surrogate, see
automatic. Lily’s own calls are rescued, so a frame of
yours should only hold values in range.
pub fn module(path: String) -> Module
Names a module whose types are sent over the wire, by its path.
The first segment is taken as the package, meaning module("shared") is
module shared in package shared, and module("shared/views/note") is
that package’s views/note. Use module_in when the package
has another name.
pub fn module_in(
package package: String,
path path: String,
) -> Module
Names a module in package, for when the package isn’t the first segment
of the path, as with a dependency.
transport.module_in(package: "some_dep", path: "some/dep/module")
pub fn schema(
message message: WireType,
model model: WireType,
types types: List(CustomDefinition),
) -> Schema
Builds a Schema from the root message and model types and
every custom type they reach.
transport.schema(
message: transport.Custom("shared", "Message", []),
model: transport.Custom("shared", "Model", []),
types: [message_type, model_type],
)
pub fn serialiser(
encode encode: fn(Protocol(model, message)) -> BitArray,
decode decode: fn(BitArray) -> Result(
Protocol(model, message),
Nil,
),
) -> Serialiser(model, message)
pub fn websocket(url: String) -> Connector
Connects to the server over a WebSocket at url, reconnecting with the
default backoff. Pass it to client.connect.
url may be relative, /ws becomes wss://host/ws on an https page.
Frames sent while disconnected are queued and sent when it reconnects.
client.connect(runtime, with: transport.websocket("/ws"))
pub fn with_offline_queue(
inner: Connector,
storage_key storage_key: String,
) -> Connector
Holds frames a connector couldn’t send and sends them, in order, when it next opens.
The queue is kept in sessionStorage under storage_key, letting it
survive a reload without being shared between tabs. Your
Channel’s send must return Error for a frame that didn’t
go out.
The first frame sent after the connection opens goes out ahead of the queue,
which follows right behind it. That’s the client’s Resync, sent once the
server has greeted it, letting the server rejoin your topics before your
offline edits reach them. Messages still unanswered when a connection closes
go back in the queue too.
The queue is the tab’s own. Unsent edits survive a reload and a tab the
browser restores, and they’re lost if the tab is closed for good while
offline. Edits queued under one sign-in are discarded when the server
greets the tab as someone else, and
browser.clear_persisted empties it.