lily/server
The Server is, well, the server of a Lily app. Clients can
apply their own changes optimistically, although the server has the final
say and streams the corrected state back, keeping the two in sync (see
transport for the frames that carry it). This means
that ultimately, the server is usually authoritative when it comes to
decisions but this can be managed by you in more detail.
Every message a client sends to the server lands in one of two places, either that client’s own per-connection session model, or a topic model shared between clients. (The client can also keep a message to itself.) See store for how topics are declared.
The server starts a topic the first time anyone subscribes to it, and
starts it again from the same declaration if it crashes. A topic that
stopped, or was given up on after crashing too often, keeps its holders,
who are subscribed again when it next starts. Each topic’s
Access rule is checked on every subscribe, on a
resync and whenever the client’s session changes, and a topic the rule
now refuses is left with a Rejected frame. A subscribe to an id no
declaration covers is rejected too.
While the server compiles for both targets, not using the Erlang one means that you aren’t leveraging BEAM’s model and a full-stack JS model might be better suited.
To build an Erlang server from the same synced store your client gets,
plus an Origins policy saying which browser origins may open
a connection, you can do this:
import lily/server
pub fn main() {
let assert Ok(#(_supervisor, app)) =
server.new(shared.store(), origins: server.AllowedOrigins([
"http://localhost:8080",
]))
|> server.observe(log_events)
|> server.start_under_supervisor
}
Using start_under_supervisor rather than
start ensures that the server and the topics are placed in an
OTP supervision tree so the crash can be isolated and restarted rather than
taking the node down with it.
The server doesn’t import mist or wisp or ewe, it’s completely
transport-agnostic (the same way Lustre leaves the transport to you),
leaving you to wire it into whatever WebSocket or HTTP handler you’re
running. Open a Connection with connect,
feed every inbound frame to receive, and call
disconnect when the socket closes:
let assert Ok(connection) =
server.connect(
app,
origin: request.get_header(req, "origin") |> option.from_result,
send: process.send(outgoing_subject, _),
)
// for every frame the socket receives
case server.receive(connection, bytes:) {
server.Closed -> close_socket()
_ -> Nil
}
// when it closes
server.disconnect(connection)
With connect watching the process that calls it, the server runs the
same cleanup disconnect does if that process dies. A transport that
connects from a short-lived process, such as an HTTP request, uses
connect_as with Unwatched.
A client id that is already connected is taken over by the newer
connection, see connect_as.
A connection that closes doesn’t end its session straight away. The server
keeps it for session_grace, and a client that
reconnects in time picks it up again, which fires no events. So presence
built from ClientConnected and ClientDisconnected lags by that long.
Most apps then just need observe. An observer sees every
ServerEvent, a client coming and going, a message applied
to a session or a topic, a client joining, leaving or being refused a
topic, together with the server it happened on. Most events run in the
server process, where every client waits on the observer, so keep those
quick and spawn anything slow (e.g. HTTP calls, process sleeps).
When the server itself needs to change state, rather than react to
something a client sent, use dispatch_to for a single
client’s session or dispatch_to_topic for a shared
topic. Both are safe to call from any process (an observer included) where
they apply once the current event is done. Thus an observer can answer a
client joining straight away, and something slow can be spawned and
dispatch when it’s ready.
A topic whose state lives somewhere else, like a database, can load it with
load_topic, or a whole family of them with
load_topic_family. Running inside the topic itself
when it starts and every time it restarts, a slow loader only holds up that
topic.
Write it back from TopicMessageApplied, which also runs in the topic,
before the sender’s Acknowledge, and in no order with the server’s own
events.
The server treats every client as possibly hostile. A frame is decoded in
the process that calls receive, refused past
max_frame_bytes, and each client is held to a
rate_limit, where a frame past it waits its turn rather
than being refused. One client may hold
max_subscriptions topics, 100 by default, with ids
up to max_topic_id_bytes, and the server as a
whole caps max_clients and max_topics.
On Erlang a socket from attach that reads too slowly is cut
off past max_outbound_queue, and frames are shed
past max_mailbox, a shed message still
answered with a Dropped.
stop_idle_topics stops the topics nobody holds.
Shut a server down with stop, which asks every topic to stop
first, settling each subscriber’s pending messages with a final
Acknowledge, before the underlying actor terminates.
Sample server combining everything together (using mist):
import gleam/bytes_tree
import gleam/erlang/process
import gleam/http/request
import gleam/http/response
import gleam/option
import lily/server
import mist
import shared
pub fn main() {
let assert Ok(#(_supervisor, app)) =
server.new(
shared.store(),
origins: server.AllowedOrigins(["http://localhost:8080"]),
)
|> server.start_under_supervisor
let assert Ok(_) =
mist.new(fn(http_request) {
let origin =
request.get_header(http_request, "origin") |> option.from_result
case server.admit(app, origin:) {
Error(_) ->
response.new(403)
|> response.set_body(mist.Bytes(bytes_tree.new()))
Ok(opened) ->
mist.websocket(
request: http_request,
on_init: fn(_socket) {
let #(connection, frames) = server.attach(opened)
#(connection, option.Some(frames))
},
on_close: server.disconnect,
handler: fn(connection, message, socket) {
case message {
mist.Binary(bytes) ->
case server.receive(connection, bytes:) {
server.Closed -> mist.stop()
_ -> mist.continue(connection)
}
mist.Custom(Ok(bytes)) -> {
let _ = mist.send_binary_frame(socket, bytes)
mist.continue(connection)
}
mist.Text(_) -> mist.continue(connection)
mist.Custom(Error(Nil)) | mist.Closed | mist.Shutdown ->
mist.stop()
}
},
)
}
})
|> mist.port(8080)
|> mist.start
process.sleep_forever()
}
Types
Description of the server before starting, construct from new.
pub opaque type Builder(model, message)
Why a connection was refused before it was registered.
pub type ConnectError {
OriginNotAllowed(origin: String)
OriginMissing
TooManyClients
}
Constructors
-
OriginNotAllowed(origin: String)The
Originheader did not match the allowlist. -
OriginMissingRequest had no
Originheader and the policy wants one. -
TooManyClientsThe server already holds
max_clientsconnections.
One client’s registration with a server, from connect.
Give it each inbound frame and close it when the transport closes.
pub opaque type Connection(model, message)
Which process the server should watch for a connection, its death disconnecting the client.
pub type ConnectionWatch {
WatchCaller
WatchProcess(process.Pid)
Unwatched
}
Constructors
-
WatchCallerThe process calling
connect_as(whatconnectdoes) -
WatchProcess(process.Pid)Some other process, such as the one owning the socket
-
UnwatchedNothing, for a transport whose requests are short-lived
Why the server cut a client off, in a
ClientEvicted event.
pub type EvictionReason {
RateLimited
SlowReader
Superseded
}
Constructors
-
RateLimitedIt kept sending past its
rate_limit -
SlowReaderIt read its frames too slowly and its queue passed
max_outbound_queue -
SupersededAnother connection registered with its id and took its place
Which browser origins may open a connection to this server.
Passed to new and evaluated by connect and
check_origin.
server.AllowedOrigins(["https://example.com", "http://localhost:8080"])
AnyOrigin lets a page on any site connect with the user’s cookies, so
keep it for a server that doesn’t sign clients in by cookie. It’s logged at
start-up.
pub type Origins {
AllowedOrigins(List(String))
AnyOrigin
}
Constructors
-
AllowedOrigins(List(String)) -
AnyOrigin
What receive did with a frame. A WebSocket transport only
needs Closed, an HTTP one can answer the others with a status.
pub type Received {
Accepted
TooLarge
Overloaded
Closed
}
Constructors
-
AcceptedHanded to the server, where it may wait its turn under the client’s
rate_limit -
TooLargeOver
max_frame_bytes, refused unread, a 413 -
OverloadedThe server’s mailbox is past
max_mailboxand the frame was shed, a 503. A message still gets itsDropped, so the client’s edit rolls back -
ClosedThe server cut this connection off, another took its id, or it belongs to a server that has since restarted or stopped, so close the socket
A running Lily server.
Use start to start one.
pub opaque type Server(model, message)
Something that happened on the server, given to every observer.
pub type ServerEvent(model, message) {
ClientConnected(client_id: String)
ClientDisconnected(client_id: String)
ClientEvicted(client_id: String, reason: EvictionReason)
ClientThrottled(client_id: String)
SessionMessageApplied(
client_id: String,
message: message,
model: model,
)
TopicMessageApplied(
client_id: option.Option(String),
topic_id: String,
message: message,
model: model,
)
Subscribed(client_id: String, topic_id: String)
SubscriptionRejected(
client_id: String,
topic_id: String,
reason: transport.RejectionReason,
)
Unsubscribed(client_id: String, topic_id: String)
Diagnostic(level: transport.DiagnosticLevel, message: String)
}
Constructors
-
ClientConnected(client_id: String)A session started, on a client’s first frame, once per session
-
ClientDisconnected(client_id: String)A session ended, its grace period over or the client cut off
-
ClientEvicted(client_id: String, reason: EvictionReason)The server cut a client off, a
ClientDisconnectedfollows -
ClientThrottled(client_id: String)A client went past its rate limit, reported once per window, whether its frames waited or were refused
-
SessionMessageApplied( client_id: String, message: message, model: model, )A session message was applied (
modelis the client’s model after it) -
TopicMessageApplied( client_id: option.Option(String), topic_id: String, message: message, model: model, )A topic applied a message, from a client or
Nonefordispatch_to_topic, with the topic’s model after it -
Subscribed(client_id: String, topic_id: String)A topic admitted a client
-
SubscriptionRejected( client_id: String, topic_id: String, reason: transport.RejectionReason, )A subscribe was refused with a
Rejectedframe -
Unsubscribed(client_id: String, topic_id: String)A client left a topic it had joined
-
Diagnostic(level: transport.DiagnosticLevel, message: String)Lily dropped something (
Warning) or gave up on something (Failure)
Values
pub fn admit(
server: Server(model, message),
origin origin: option.Option(String),
) -> Result(Admission(model, message), ConnectError)
Checks a WebSocket request’s origin before upgrading it, returning an
error for a refused one that you answer with a 403, and refuses with
TooManyClients once the server holds max_clients.
Erlang only. Pass the result to attach once the socket is up.
case server.admit(app, origin:) {
Ok(opened) -> upgrade(request, opened)
Error(_) -> forbidden()
}
pub fn admit_as(
server: Server(model, message),
origin origin: option.Option(String),
client_id client_id: String,
seed seed: List(message),
) -> Result(Admission(model, message), ConnectError)
Like admit, choosing the client’s id and seeding its session,
for a socket you’ve authenticated. Erlang only. Pass the result to
attach.
seed is applied before anything the client sends, the place for who
signed in. A connected id is taken over, as with
connect_as.
case server.admit_as(app, origin:, client_id:, seed: [SignedInAs(user)]) {
Ok(opened) -> upgrade(request, opened)
Error(_) -> forbidden()
}
pub fn attach(
opened: Admission(model, message),
) -> #(
Connection(model, message),
process.Selector(Result(BitArray, Nil)),
)
Registers a WebSocket with the server from inside its socket process, once
admit or admit_as has accepted the request.
Erlang only.
Give it the Admission value. You get back the connection and a selector
that yields Ok(bytes) for each frame to send, and Error(Nil) when the
socket should close, because the server restarted or cut this client off, or
was already full when it attached.
on_init: fn(_socket) {
let #(connection, frames) = server.attach(opened)
#(connection, option.Some(frames))
},
pub fn check_origin(
server: Server(model, message),
origin origin: option.Option(String),
) -> Result(Nil, ConnectError)
Checks a request’s Origin header against the server’s
Origins, for refusing a request before you connect it.
case server.check_origin(app, origin:) {
Ok(Nil) -> upgrade(request)
Error(_) -> forbidden()
}
pub fn client_id(
connection: Connection(model, message),
) -> String
The id of a connection.
pub fn connect(
server: Server(model, message),
origin origin: option.Option(String),
send send: fn(BitArray) -> Nil,
) -> Result(Connection(model, message), ConnectError)
Registers a client with the server, from the process that owns its socket.
Give it the request’s Origin header and a send function that delivers a
frame to this client. send runs inside the server and its topics, so it
must not block and should bound what it queues itself. The client is
disconnected if the calling process dies. With mist or ewe,
admit and attach are simpler and bound the queue
for you.
let assert Ok(connection) =
server.connect(app, origin:, send: process.send(outgoing, _))
pub fn connect_as(
server: Server(model, message),
origin origin: option.Option(String),
send send: fn(BitArray) -> Nil,
client_id client_id: String,
seed seed: List(message),
watch watch: ConnectionWatch,
) -> Result(Connection(model, message), ConnectError)
Registers a client like connect, letting you choose its id,
seed its session and pick which process to watch.
seed is a list of messages applied to a new session before anything it
sends, such as who signed in, and a client resuming its session must come
back with the same seed (see session_grace). A tab
greeted under another seed than last time discards the messages it had
queued offline. Use watch: Unwatched for short-lived HTTP requests.
An id that’s already connected is taken over. The old connection is
unsubscribed from everything and reported as
ClientEvicted with Superseded, and its later frames and
disconnect are ignored. Ids from generate_client_id
are random, so only reuse one you’ve authenticated.
send runs inside the server and its topics. It must not block, and should
bound what it queues for a slow socket itself.
server.connect_as(
app,
origin:,
send:,
client_id: server.generate_client_id(),
seed: [SignedInAs(user)],
watch: server.WatchCaller,
)
pub fn connection(
server: Server(model, message),
client_id client_id: String,
) -> Connection(model, message)
The connection for a client id you kept, for transports that store the id rather than the connection.
It reaches whichever connection holds the id now, a newer one included.
It can’t tell the transport the client was cut off, so receive only
says Closed after a restart.
case server.connection(app, client_id:) |> server.receive(bytes:) {
server.Closed -> close_stream()
_ -> Nil
}
pub fn diagnostic_budget(
builder: Builder(model, message),
per_second per_second: Int,
burst burst: Int,
) -> Builder(model, message)
Caps the diagnostics every client’s frames can set off together,
per_second on average and up to burst at once, 10 and 100 by default.
Each client is also held to one per 10 seconds on its own. Both values are
clamped to between 1 and 1,000,000,000.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.diagnostic_budget(per_second: 1, burst: 20)
pub fn disconnect(connection: Connection(model, message)) -> Nil
Ends a client’s connection, usually when its socket closes. Its session is
kept for session_grace for the client to resume.
pub fn dispatch_to(
server: Server(model, message),
client_id client_id: String,
message message: message,
) -> Nil
Applies a message to one client’s session and sends it the update, for changes the server makes on its own, like the result of async work.
A parked session takes it too, and it does nothing once a session has ended. Safe to call from any process.
server.dispatch_to(app, client_id:, message: Welcome)
pub fn dispatch_to_all(
server: Server(model, message),
message message: message,
) -> Nil
Applies a message to every connected client’s session and sends each the update.
server.dispatch_to_all(app, message: BannerChanged(banner))
pub fn dispatch_to_topic(
server: Server(model, message),
topic_id topic_id: String,
message message: message,
) -> Nil
Applies a message to a topic and sends the update to its subscribers, starting the topic if it isn’t running. Safe to call from any process.
A dispatch to an id no declaration covers, or to a new topic once
max_topics are running and every one is held, is dropped
with a Diagnostic.
server.dispatch_to_topic(app, topic_id: "chat", message: Chat(Notice(text)))
pub fn evict_after(
builder: Builder(model, message),
refusals refusals: Int,
within milliseconds: Int,
) -> Builder(model, message)
Cuts a client off once more than refusals of its frames are refused
within within milliseconds, reported as ClientEvicted
with RateLimited. By default that’s the rate_limit’s
burst within 10 seconds, the same window ClientThrottled is reported
once in. Both values are clamped to at least 1.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.evict_after(refusals: 2000, within: 30_000)
pub fn generate_client_id() -> String
Generates a new random client id, for connect_as.
pub fn load_topic(
builder: Builder(model, message),
id id: String,
init init: fn() -> model,
) -> Builder(model, message)
Loads the starting model of the topic with this exact id, for state kept
somewhere else like a database. Pipe it from new, matching a
store.topic declaration.
init runs again if the topic restarts. If it crashes, the topic starts
from the store’s initial model instead.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.load_topic(id: "lobby", init: fn() {
Model(..shared.initial_model(), lobby: database.load_lobby())
})
|> server.start
pub fn load_topic_family(
builder: Builder(model, message),
prefix prefix: String,
init init: fn(String) -> model,
) -> Builder(model, message)
Loads the starting model of every topic whose id starts with prefix,
matching a store.topic_family declaration.
Mirrors load_topic.
init gets the rest of the id after the prefix. An exact load_topic id
beats any prefix, then the longest prefix wins.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.load_topic_family(prefix: "room:", init: fn(room) {
Model(..shared.initial_model(), room: database.load_room(room))
})
|> server.start
pub fn max_clients(
builder: Builder(model, message),
count count: Int,
) -> Builder(model, message)
Caps how many clients may be connected at once, 10,000 by default. Past
it connect, connect_as, admit and
admit_as refuse with TooManyClients.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_clients(count: 2000)
pub fn max_frame_bytes(
builder: Builder(model, message),
bytes bytes: Int,
) -> Builder(model, message)
Caps the size of a frame a client may send, 1 MiB by default. A bigger one
is dropped before it’s decoded and charged against the client’s
rate_limit, a message gets a Dropped when its head names
its id.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_frame_bytes(bytes: 64 * 1024)
pub fn max_mailbox(
builder: Builder(model, message),
frames frames: Int,
) -> Builder(model, message)
Caps how many frames may wait in the server’s mailbox, 10,000 by default. Erlang only, a JavaScript server handles each frame as it arrives.
Past it receive sheds the frame instead of queueing work
for it. A connection from attach is closed, the client
reconnects with backoff and resyncs. Otherwise a message frame is answered
with a Dropped, in order behind the client’s earlier answers, rolling
its edit back, and a resync, subscribe or unsubscribe is let through so
the client isn’t left waiting. Shed frames count towards the client’s
rate_limit refusals.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_mailbox(frames: 50_000)
pub fn max_outbound_bytes(
builder: Builder(model, message),
bytes bytes: Int,
) -> Builder(model, message)
Caps the bytes that may wait for a socket from attach to send
them, 16 MiB by default. Erlang only. Like
max_outbound_queue, a client reading slower is cut
off as ClientEvicted with SlowReader. A frame on its
own always fits, so a snapshot bigger than this still reaches the client.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_outbound_bytes(bytes: 4_194_304)
pub fn max_outbound_queue(
builder: Builder(model, message),
frames frames: Int,
) -> Builder(model, message)
Caps how many frames may wait for a socket from attach to
send them, 1000 by default. Erlang only.
A client reading slower than the server writes is cut off past it,
reported as ClientEvicted with SlowReader. A send of
your own passed to connect needs a bound of its own.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_outbound_queue(frames: 200)
pub fn max_subscriptions(
builder: Builder(model, message),
per_client per_client: Int,
) -> Builder(model, message)
Caps how many topics one client may join at once, 100 by default. It also
bounds the work one Resync or one session change costs.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_subscriptions(per_client: 50)
pub fn max_throttled_bytes(
builder: Builder(model, message),
per_client per_client: Int,
total total: Int,
) -> Builder(model, message)
Caps what frames waiting under the rate_limit may take,
per_client bytes for one client and total across every client, 256 KiB
and 64 MiB by default. A message that doesn’t fit gets a Dropped. Raise
per_client for an app whose offline replays carry big edits, and total
alongside max_clients. Both are clamped to at least 0.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_throttled_bytes(per_client: 1_048_576, total: 268_435_456)
pub fn max_topic_id_bytes(
builder: Builder(model, message),
bytes bytes: Int,
) -> Builder(model, message)
Caps the length of a topic id a client may subscribe to, 256 bytes by default.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_topic_id_bytes(bytes: 64)
pub fn max_topics(
builder: Builder(model, message),
count count: Int,
) -> Builder(model, message)
Caps how many topics run at once, 100,000 by default. Topic ids come from
clients, so past it the topic nobody has held for longest is stopped to
make room. If every topic is held, a subscribe is rejected with
OverLimit and a dispatch to a new topic is dropped.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.max_topics(count: 10_000)
pub fn monitor(server: Server(model, message)) -> process.Monitor
Monitors the server process, letting a socket close when the server
restarts. Erlang only. attach already does this for you.
process.new_selector()
|> process.select_specific_monitor(server.monitor(app), fn(_) { Gone })
pub fn new(
store: store.Store(model, message, store.Synced),
origins origins: Origins,
) -> Builder(model, message)
Starts building a server from the synced store your client also uses, and
the origins allowed to connect. Pipe it into start or
start_under_supervisor.
server.new(shared.store(), origins: server.AllowedOrigins([
"https://example.com",
]))
|> server.start_under_supervisor
pub fn observe(
builder: Builder(model, message),
observer: fn(
ServerEvent(model, message),
Server(model, message),
) -> Nil,
) -> Builder(model, message)
Adds a function that’s called with every ServerEvent and
the server it happened on. Pipe it from new.
Keep it quick, every other client waits while it runs. Spawn anything slow.
TopicMessageApplied is the exception, it runs in the topic’s process
before the sender’s acknowledgement, the place to persist a topic (see
server).
server.observe(builder, fn(event, app) {
case event {
server.ClientConnected(client_id:) ->
server.dispatch_to(app, client_id:, message: Welcome)
_ -> Nil
}
})
pub fn rate_limit(
builder: Builder(model, message),
per_second per_second: Int,
burst burst: Int,
) -> Builder(model, message)
Caps how fast one client may send, per_second frames on average and up to
burst at once, 50 and 500 by default. That’s a few times a fast typist,
with room for a reconnect’s resync and an offline replay.
A frame past it waits its turn. Frames are held in arrival order, up to
burst messages within max_throttled_bytes, and
run as the allowance refills. A message that can’t wait, because the held
queue is full, gets a Dropped, so the client’s edit rolls back. A client
refused more than evict_after allows, burst frames
within 10 seconds by default, is cut off, reported as
ClientEvicted with RateLimited.
Both values are clamped to between 1 and 1,000,000,000.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.rate_limit(per_second: 20, burst: 200)
pub fn receive(
connection: Connection(model, message),
bytes bytes: BitArray,
) -> Received
Passes a frame the client sent to the server. Call it for every binary frame
the socket receives, and close the socket when it says Closed.
case server.receive(connection, bytes:) {
server.Closed -> close_socket()
_ -> Nil
}
pub fn recheck_access(
server: Server(model, message),
client_id client_id: String,
) -> Nil
Checks every topic a client joined against its access rule again, for rules that read state outside the session, like a database.
A topic the rule now refuses is left with a Rejected frame. Session
changes are re-checked on their own.
server.recheck_access(app, client_id:)
pub fn server_restarts(
builder: Builder(model, message),
max max: Int,
within milliseconds: Int,
) -> Builder(model, message)
Sets how often start_under_supervisor’s
supervisor restarts a crashing server before it gives up and exits itself,
max crashes within within milliseconds, 3 within 10,000 by default.
Erlang only. The window is rounded up to whole seconds. A server in a tree
of your own, from supervised, follows your supervisor’s
limits instead.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.server_restarts(max: 5, within: 30_000)
|> server.start_under_supervisor
pub fn session_grace(
builder: Builder(model, message),
milliseconds milliseconds: Int,
) -> Builder(model, message)
Keeps a session whose connection closed for milliseconds, 30,000 by
default, so a client that reconnects in time resumes it with its model and
its topics. 0 ends a session the moment its connection closes.
A resume fires no events, and ClientDisconnected only comes once the
session expires, see server for what that means for
presence. Clamped to at least 0.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.session_grace(milliseconds: 10_000)
pub fn start(
builder: Builder(model, message),
) -> Result(Server(model, message), Nil)
Starts the server. Pipe it from new. On Erlang,
start_under_supervisor is usually the better
choice.
let assert Ok(app) =
server.new(shared.store(), origins: server.AnyOrigin)
|> server.start
pub fn start_under_supervisor(
builder: Builder(model, message),
) -> Result(
#(static_supervisor.Supervisor, Server(model, message)),
Nil,
)
Starts the server under its own supervisor, letting a crash restart it instead of taking your app down. Erlang only. Call it once when your program starts.
let assert Ok(#(_supervisor, app)) =
server.new(shared.store(), origins: server.AnyOrigin)
|> server.start_under_supervisor
pub fn stop_idle_topics(
builder: Builder(model, message),
after milliseconds: Int,
) -> Builder(model, message)
Stops a topic once it has gone after milliseconds with no subscribers and
no dispatches, dropping its state until load_topic loads
it again.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.stop_idle_topics(after: 60_000)
pub fn stop_topic(
server: Server(model, message),
topic_id topic_id: String,
) -> Nil
Stops one topic. Its subscribers get a final Acknowledge and then a
Rejected with NotFound, keeping their last state. The next subscribe or
dispatch starts it again from the beginning, and the clients that held it
are subscribed again then, those its access rule still allows, each sent a
fresh snapshot.
server.stop_topic(app, topic_id: "room:1")
pub fn supervised(
builder: Builder(model, message),
) -> supervision.ChildSpecification(Server(model, message))
A child specification for adding the server to your own supervision tree. Erlang only. Call it once when your program starts.
static_supervisor.new(static_supervisor.OneForOne)
|> static_supervisor.add(
server.new(shared.store(), origins: server.AnyOrigin)
|> server.supervised,
)
|> static_supervisor.start
pub fn topic_restarts(
builder: Builder(model, message),
max max: Int,
within milliseconds: Int,
) -> Builder(model, message)
Sets how often a crashing topic is restarted before the server gives up on
it, max crashes each within within milliseconds of the last, 5 within
60,000 by default. A topic given up on rejects its holders with NotFound
and rejoins them when it next starts. Clamped to at least 0 and 1.
server.new(shared.store(), origins: server.AnyOrigin)
|> server.topic_restarts(max: 10, within: 30_000)