Roc Solid
Markup in Roc ยท pages on a native server ยท components in WebAssembly

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:

site/routes/api/platform/live/lobby/+server.roc
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:

site/Demos/Lobby.rocx, in part
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:

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.

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):

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 streamMeans
event: hello, data: the stream's idfirst: the id the runtime uses to change the tab's subscriptions (192 random bits, unique to this stream)
event: resync, data: /org/acme/newsread 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 stringthe check refused it at a beat
: beatevery 15 s (--live-beat-ms): the server is there, and has checked each channel again
event: replaceda 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

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:

server/test/app/main.roc, in part
("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:

server/test/app/main.roc, in part
("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#

ForUseLasts
live data for pages, checkeda channel (channel!, .subscribe!, .publish!)while the subscribers last
who is here, nowa room (Live.join!, Live.count!), or a channel's hookswhile the calls in it last
telling every listening calla topic (Live.publish!, Live.listen!)while the listeners last
a count, a cache, a token used oncea 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 timean actor (Actor: ask!, tell!)in the database: survives restarts
data, queried every waya table (Db)in the database
work that may fail and should run againa job (Job.enqueue!)in the database, until done