The ecosystem · packages/websocket
A WebSocket client for your server, in Roc
Slack's Socket Mode, Discord's Gateway, a market's price feed: a connection to another server that stays open for hours, with messages both ways. WebSocket.connect! opens one, send! and receive! carry the messages, and a wait that ends in Quiet lets a loop send its heartbeat on time.
The package runs on the server only, in plain Roc on the platform's Tcp: ws:// over TCP, wss:// over TLS.
Installing it#
Name the package in your app's header, beside the platform:
app [program] { pf: platform "../server/platform/main.roc", websocket: "../packages/websocket/main.roc" }Then import websocket.WebSocket where you use it.
Connecting, sending, receiving#
socket = WebSocket.connect!("wss://feed.example.com/v1", [{ name: "Authorization", value: "Bearer ${token}" }])?
socket.send!("{\"subscribe\":\"prices\"}")?
received = socket.receive!(30000)?
match received.got {
Text(text) => …
Binary(bytes) => …
Quiet => …
Closed({ code, reason }) => …
}
received.socket.close!(1000, "done")connect! takes the URL and the headers for the upgrade request (a token, say). It waits 10 s at most for the server to agree, and anything but 101 Switching Protocols is a WsErr that names the status the server gave. send! sends text, send_binary! bytes, ping! a ping.
receive!(socket, ms) waits ms milliseconds at most for the next message. It answers pings on the way and joins a message sent in parts. What it got:
| Got | What it means |
|---|---|
Text(Str), Binary(List(U8)) | a whole message |
Quiet | no whole message came in the time given; the socket is still open, and part of a message that came stays in it |
Closed({ code, reason }) | the server closed it, and was answered with the same code; 1006 when the connection just ended |
A socket belongs to the call that opened it, like any Tcp connection, and closes when that call ends. To keep one open for hours, open it in a background loop (a plugin's loops), which runs as long as the server does.
A heartbeat while it waits#
Discord's Gateway wants a heartbeat every so many seconds, whether messages come or not, and drops a client that misses them. The loop waits for the next message only until the next heartbeat is due: then receive! answers Quiet, and the loop sends it. From the package's example, which its tests run against a WebSocket server of their own:
import pf.Env
import pf.Time
import websocket.WebSocket
## Following Acme's feed (FEED_URL, with FEED_TOKEN): its messages as they come, and a heartbeat
## sent on time, as Discord's Gateway asks of a client (it drops one that misses them). The loop
## waits for the next message only until the next heartbeat is due: then `receive!` answers
## `Quiet`, and the loop sends it.
Feed := [].{
## A connection to `path` on the feed, the token in its `Authorization` header.
connect! : Str => Try(WebSocket, [WsErr(Str)])
connect! = |path| {
url = Env.var!("FEED_URL") ?? "ws://127.0.0.1:9"
token = Env.var!("FEED_TOKEN") ?? ""
WebSocket.connect!("${url}${path}", [{ name: "Authorization", value: "Bearer ${token}" }])
}
## What the feed sent in `ms` milliseconds, with a heartbeat (`{"op":1,"d":<count>}`) every
## `beat_ms`; then a close. If the feed closes first, its last line says how.
listen! : WebSocket, U64, U64 => Try({ heard : List(Str), beats : U64 }, [WsErr(Str)])
listen! = |socket, ms, beat_ms| {
start = Time.now_millis!({})
end = start + ms
var $socket = socket
var $heard = []
var $beats = 0
var $next_beat = start + beat_ms
var $now = start
while $now < end {
received = $socket.receive!(U64.min($next_beat, end) - $now)?
$socket = received.socket
match received.got {
Text(text) => {
$heard = $heard.append(text)
}
Binary(bytes) => {
$heard = $heard.append("${bytes.len().to_str()} bytes")
}
Closed({ code, reason }) => return Ok({ heard: $heard.append("closed ${code.to_str()} ${reason}"), beats: $beats })
Quiet => {}
}
$now = Time.now_millis!({})
if $now >= $next_beat and $now < end {
$beats = $beats + 1
$socket.send!("{\"op\":1,\"d\":${$beats.to_str()}}")?
$next_beat = $next_beat + beat_ms
}
}
$socket.close!(1000, "done")
Ok({ heard: $heard, beats: $beats })
}
}What it refuses#
A server that breaks the protocol is sent a close frame that says why, the connection is closed, and receive! answers WsErr:
| Code | When |
|---|---|
| 1009 | a message longer than 16 MiB (WebSocket.max_message), refused as soon as its header says so, before the rest is read |
| 1002 | a masked frame, reserved bits set, an unknown opcode, a control frame split or longer than 125 bytes, a part with no message to continue, a message begun before the last one ended |
| 1007 | a text message that isn't UTF-8 |
connect! refuses, before it connects, a URL with a #fragment or a user in it (send credentials in a header), a header with a line break, and the headers the handshake writes itself. After connecting, it refuses an answer whose Sec-WebSocket-Accept isn't the one for the key it sent, and an extension nobody asked for.
How it works#
The package is plain Roc. Handshake writes the upgrade request, with a key of 16 random bytes, and checks the answer (SHA-1 and Base64 from packages/crypto). Frame writes and reads frames: lengths in 7, 16 or 64 bits, and every frame the client sends masked with four new random bytes, as RFC 6455 requires. Both are pure, and their expects check them against the RFC's own examples.
receive! reads with the platform's Tcp.read_within!, which waits only as long as it is told and then answers TimedOut, losing nothing. That is how a quiet socket (Quiet) is told from a broken one (WsErr, or Closed with 1006).
Not yet#
- Compression (
permessage-deflate, Discord'szlib-stream): ask the server for plain messages. - Sending from another call while one reads: the call that opened the socket does both. Hand it messages through
Kvor an actor. - A server side: browsers reach an app over its channels.
wss://through an HTTP proxy.
The package's PROPOSALS.md says what each would take.