The platform ยท live and channels
Live updates, from the server to the page
Some pages change while someone looks at them: a chat, a shared board, who is online. The server pushes messages to them, usually on a channel: a typed stream pages subscribe to, checked against who may read it. Channels are built on rooms and topics, which your own event streams can use directly. All of it lives in the server's memory; what must survive a restart belongs in an actor or a table.
Channels: live data for pages#
A channel lives in a route's +server.roc, beside its endpoints, so it has a path. Its definition, channel!, is a check: given the request, the path's params and what the route's middleware handed on, it returns who the subscriber is (Channel.allow(who)) or a refusal. Its type says what the server publishes and what pages may say. This page's lobby lets everyone in:
import pf.Server
import pf.Endpoint
import pf.Channel
## The lobby, a channel: anyone may join, and every tab that has hears each wave as it is
## made. Its check lets everyone in; a tab is named by the first letters of its id.
channel! : { request : Server.Request, params : {}, context : c } => Try(Channel({}, { hand : Str, from : Str }, [Wave(Str)]), Endpoint.Refusal)
channel! = |_| Ok(Channel.allow({}))
## What a page says: a wave, published to everyone in the lobby. Only these hands.
receive! = |{ tab, said, channel, .. }|
match said {
Wave(hand) =>
if ["๐", "๐", "๐"].contains(hand) {
Endpoint.publish!(channel, { hand, from: short(tab) })
Ok({})
} else {
Err(BadRequest("wave ๐, ๐ or ๐"))
}
}
## A subscriber is greeted first, each time it joins.
on_open! = |{ tab, .. }| [{ hand: "๐", from: "the lobby, to tab ${short(tab)}" }]
short = |tab| Str.from_utf8_lossy(tab.to_utf8().take_first(4))rocx build puts each channel in Generated/Api as a function of its params, like endpoints: Api.channel_api_platform_live_lobby({}) here, Api.channel_org_org_news({ org }) for /org/[org]/news. Its type is the Channel(who, message, said) from channel!'s annotation. Generated/Api imports no route file, so a job, an actor or any server module can import it and publish on a channel by name, type-checked.
A component subscribes from an effect. The subscription ends when the effect runs again or the component goes away:
lobby = Api.channel_api_platform_live_lobby({})
create_effect!(
|| {},
|{}|
lobby.subscribe!(
|event|
match event {
Resync => set_state!("In the lobby. Open this page in another tab, join there too, and wave.")
Message(wave) => set_waves!(waves!().take_last(5).append("${wave.hand} from ${wave.from}"))
Refused(_, why) => set_state!("No lobby here: ${why}")
Ended(why) => set_state!("Left: ${why}")
},
),
)
โฆ
{...["๐", "๐", "๐"].map(|hand|
<button key={hand} type="button" class="wave" on:click={|| lobby.say!(Wave(hand))}>{hand}</button>A subscriber hears these events, in order, one at a time:
Resync: the page may have missed something, so it should read its data again (refresh!). Sent each time the tab's stream connects or reconnects, when the subscriber fell behind, and when a page asks (channel.resync!()). The route'son_open!messages follow it.Message(message): something published, as the channel's type.Refused(status, why): the check refused the subscriber when the stream opened.Ended(why): the check ran again at a beat (every 15 s) and refused it. Someone who loses access stops hearing within a beat.
The server publishes with Api.channel_org_org_news({ org: "acme" }).publish!(news), from a request, a job or an actor. Only subscribers with the same params hear it, in publish order. A page's first data comes from a get! endpoint, often in the channel's file (.read!()); the channel carries the changes after that.
- Only the latest matters?
channel.publish_latest!(key, message)is for values where only the newest counts (a cursor's position). A subscriber that is behind gets only the newest message per key, unordered with the channel's other messages. - Falling behind. A subscriber more than 256 messages behind hears
Resyncinstead of what it missed, never a silent gap.
What pages say, and hooks#
Beside channel!, a route may define three hooks. Each gets the path's params, who the subscriber is (from the check), its tab id, and the channel (to publish on):
receive!handles what a page says (channel.say!(said)) after the same middleware and check, or refuses it. What a page says within one frame goes in one request.on_open!returns the messages a subscriber gets first, each time it subscribes (who is here, say), right after itsResync.on_close!is told when a subscription ends, and why:Dropped(the tab stays but the page stopped subscribing: the component went, or follows another channel),Gone(the tab closed or reloaded, its network went, or the server stopped), orRefused(why)(the check, at a beat). It runs outside the middleware, since losing access may be what ended it.
who stays on the server, as JSON, from the check until on_close!. A tab id is random and lasts the tab's life (a reload keeps it); it names a tab, not a person.
A tab's hooks run in order. If a page drops a channel and subscribes again, the route hears the end first. If a tab's new stream (after a reload or reconnect) arrives before the server noticed the old one end, the old one ends first: its on_close! calls run before the new stream's checks and on_open!. So a route can keep "who is here" per tab with nothing to count by hand: join on on_open!, leave on on_close! (at once when Dropped; after a moment when Gone, in case the tab comes back). The presence package does this for you, with names, colours and cursors.
One stream per tab#
All of a tab's subscriptions share one server-sent events stream, GET /rocx/live?tab=โฆ&c=/org/acme/news&c=โฆ, and two components on one channel share one subscription. The browser's runtime opens the stream once the page has rendered. If it drops, the runtime reopens it after a wait that doubles each time, from half a second up to 30 s.
When the page's subscriptions change (after the render that changed them), the runtime posts the change, naming the stream's id, and the stream stays open. With nothing left to subscribe to, the runtime says so, then closes the stream. A static copy of a site (files, no server) has no channels: a subscriber hears Refused(404, โฆ), once.
| On the stream | Means |
|---|---|
event: hello, data: the stream's id | first: the id the runtime uses to change the tab's subscriptions (192 random bits, unique to this stream) |
event: resync, data: /org/acme/news | read your data again; on_open!'s messages follow |
event: message, the URL, then data: {"title":โฆ} | what was published, as JSON |
event: refused, the URL, then data: {"status":403,"why":"Forbidden"} | the check refused this channel; the stream goes on for the others |
event: ended, the URL, then why, as a JSON string | the check refused it at a beat |
: beat | every 15 s (--live-beat-ms): the server is there, and has checked each channel again |
event: replaced | a newer stream for this tab replaced this one, which ends. A page still reading it is a second tab with the same id (a duplicated tab copies it); it takes its own id |
- No call is held open. The host keeps the open streams and passes messages on. Roc runs only briefly: a check, a hook, a beat's checks.
- Middleware applies. Each check is a request to the app for the channel's path, with the tab's cookies, behind the app's and the route's middleware, like a
GETof that path. The cookies are the stream's, or the last subscription change's, so a page that signs in without a reload reaches members' channels. A sign-in guard guards a channel by its path;/rocx/liveitself never reaches the app's middleware. - A lost tab is gone in about 35 s. A tab that lost its network never closes its stream. The next beat goes unacknowledged; 20 s later the server drops the connection and tells
on_close!. - What pages say goes in
POST /rocx/live/send?tab=โฆ&stream=โฆ: a JSON list of{"channel":"/org/acme/news","message":โฆ}, with the stream's changes ({"channel":โฆ,"subscribe":true},{"channel":โฆ,"unsubscribe":true}). The answer is 204, or 200 with each refusal ({"refused":[{"index":0,"status":403,"why":โฆ}]}). A post from another site's page is refused (403), and so is a change naming no open stream of the tab (404). - Limits: a stream carries at most 64 channels; a post carries at most 256 items and 1 MiB.
Rooms: who is here#
Rooms and topics are the building blocks under channels, for event streams you write yourself (streams). A room counts who is in it. A call joins one with Live.join! and stays until the call ends: for a stream, until its client goes or it crashes. Live.count! reads a room's count from anywhere. This stream sends the count at the start and whenever someone comes or goes:
("GET", "/online") =>
# Who is here: this stream counts until it ends, and hears when others come and go.
Server.events(
Events.stream(
|{ send!, .. }| {
Live.join!("online")
var $open = Bool.True
while $open {
send!(Live.count!("online").to_str())?
$open = Live.next!(15_000) != Gone
}
Ok({})
},
),
)Live.next!(ms) waits for what the call hears: Heard (a message on a topic it listens to, or someone joining or leaving its room), Quiet after ms milliseconds of nothing, or Gone when the client has gone. So this loop sleeps until there is something to say, and ends with its client.
Topics: messages between calls#
A topic carries messages to every call listening to it. Live.listen! listens for the rest of the call. Live.publish!, from any request, job or actor, sends to every listener:
("GET", "/shouts") =>
Server.events(
Events.stream(
|{ send!, .. }| {
Live.listen!("shouts")
send!("listening")?
var $open = Bool.True
while $open {
match Live.next!(15_000) {
Heard({ message, .. }) => send!(message)?
Quiet => send!("quiet")?
Gone => {
$open = Bool.False
}
}
}
Ok({})
},
),
)
("POST", "/shout") => {
Live.publish!("shouts", Server.text_of(request))A component listens to such a stream like any endpoint's events. On the server, it is a call that stays open: it holds no thread while it waits, but keeps its stack. In the browser, it takes one of the six connections a browser opens to a host over HTTP/1.1. And there is one per page, not one per tab. For what pages follow live, a channel is better.
Which to use#
| For | Use | Lasts |
|---|---|---|
| live data for pages, checked | a channel (channel!, .subscribe!, .publish!) | while the subscribers last |
| who is here, now | a room (Live.join!, Live.count!), or a channel's hooks | while the calls in it last |
| telling every listening call | a topic (Live.publish!, Live.listen!) | while the listeners last |
| a count, a cache, a token used once | a value in memory (Kv: Kv.increment!, Kv.set!, Kv.take!) | its time to live, or until a restart |
| state many requests change, one at a time | an actor (Actor: ask!, tell!) | in the database: survives restarts |
| data, queried every way | a table (Db) | in the database |
| work that may fail and should run again | a job (Job.enqueue!) | in the database, until done |