Skip to content

Real-time: Events & WebSockets ​

Runcobo has two ways to push data to a client over a long-lived connection:

Server-sent eventsWebSockets
DirectionServer → clientBoth ways
Routeget "/path"ws "/path"
In callstream do |events| ... endwebsocket do |socket| ... end
Browser APIEventSource (reconnects by itself)WebSocket
Good forNotifications, live feeds, progressChat, collaboration, games

Prefer server-sent events when only the server talks: they're plain HTTP, pass through proxies, and browsers reconnect automatically.

Both run inside an action: before filters and validate run first, as for any endpoint, so a request that fails authentication or validation gets a normal 401 or 422 and never opens a stream. Both are closed cleanly when the server shuts down.

Server-sent events ​

Call stream in call. It responds with text/event-stream and yields an event stream; the response ends when the block returns.

src/actions/posts/watch_post.cr
crystal
class Posts::WatchPost < Blog::BaseAction
  get "/posts/:id/events"

  call do
    input = validate(WatchPostContract)
    stream do |events|
      events.send "watching", event: "hello"
      while events.wait(5.seconds)
        events.send store.count_comments(post_id: input.id).total.to_s, event: "comments"
      end
    end
  end
end
js
const source = new EventSource("/posts/1/events")
source.addEventListener("comments", (e) => console.log(e.data))
MethodDescription
events.send(data, event:, id:, retry:)Sends an event. Data with line breaks is sent as several data: lines. Returns false once the stream is closed
events.wait(span)Waits up to span, returning early when the stream closes. Returns true while it's open, so it can drive a loop
events.closed?Whether the client went away, the server is stopping, or the block returned
events.on_close { ... }Runs when the stream closes — for example to unsubscribe
events.comment(text)Sends a comment, which clients ignore

Runcobo sends a comment every 15 seconds while the stream is idle. It keeps proxies from timing the connection out and notices clients that disconnected; change it with stream(heartbeat: 30.seconds). The response also carries Cache-Control: no-cache and X-Accel-Buffering: no, so nginx passes events through without buffering.

A stream holds one connection and one fiber per client. Fibers are cheap, but don't keep a database connection checked out while waiting: query, then wait.

WebSockets ​

Declare the route with ws and accept the connection with websocket:

src/actions/chat/connect.cr
crystal
class Chat::Connect < Blog::BaseAction
  ws "/chat/:room"
  before authenticate

  call do
    input = validate(ConnectContract)
    websocket do |socket|
      socket.send "joined #{input.room}"
      socket.on_message do |message|
        socket.send message.upcase
      end
      socket.on_close do |code, reason|
        # clean up
      end
    end
  end
end
js
const socket = new WebSocket("ws://localhost:3000/chat/lobby")
socket.onmessage = (e) => console.log(e.data)
socket.onopen = () => socket.send("hello")
  • ws "/chat/:room" matches only upgrade requests. A plain GET to the same path goes to a get route, if there is one.
  • The handshake happens when call finishes, after the before filters and validate. Return byebye from a filter, or fail validation, and the client gets that HTTP response instead of a socket.
  • The block receives Crystal's HTTP::WebSocket: register on_message, on_binary and on_close, and call send or close. Runcobo then reads frames until the connection closes.
  • The block can use the local variables of call, such as input above.
  • An exception in the block is logged as websocket_failed and closes the socket with code 1011.

Authentication ​

Authenticate in a before filter, as for any action. Browsers' EventSource and WebSocket can't set an Authorization header, so a browser client authenticates with a cookie, or with a short-lived token in the query string:

crystal
private def authenticate
  token = request.headers["Authorization"]?.try(&.lchop?("Bearer ")) || request.query_params["token"]?
  unless token && valid_token?(token)
    render_json({error: "unauthorized"}, status_code: 401)
    return byebye
  end
end

Runcobo's request log records the path without the query string. A WebSocket also isn't protected by CORS: check the Origin header in a filter if cookies authenticate it. See Security.

Sending to many clients ​

stream and websocket handle one client each. To push one update to everyone watching, connect them through a small publish/subscribe hub. In one process, channels are enough:

src/web/hub.cr
crystal
# Delivers messages published on a topic to every subscriber of that topic.
class Blog::Hub
  @subscribers = {} of String => Array(Channel(String))
  @mutex = Mutex.new

  def subscribe(topic : String) : Channel(String)
    channel = Channel(String).new(16)
    @mutex.synchronize { (@subscribers[topic] ||= [] of Channel(String)) << channel }
    channel
  end

  def unsubscribe(topic : String, channel : Channel(String)) : Nil
    @mutex.synchronize { @subscribers[topic]?.try &.delete(channel) }
    channel.close
  end

  def publish(topic : String, message : String) : Nil
    channels = @mutex.synchronize { @subscribers[topic]?.try(&.dup) || [] of Channel(String) }
    channels.each do |channel|
      select
      when channel.send(message)
      else
        # A subscriber that isn't keeping up misses this message instead of blocking everyone.
      end
    rescue Channel::ClosedError
    end
  end
end

BLOG_HUB = Blog::Hub.new
src/actions/posts/watch_post.cr
crystal
call do
  input = validate(WatchPostContract)
  topic = "post:#{input.id}"
  stream do |events|
    updates = BLOG_HUB.subscribe(topic)
    events.on_close { BLOG_HUB.unsubscribe(topic, updates) }
    while message = updates.receive?
      events.send message, event: "comment"
    end
  end
end
src/actions/comments/create_comment.cr
crystal
if comment = store.create_comment?(post_id: input.post_id, author: input.author, body: input.body)
  BLOG_HUB.publish("post:#{input.post_id}", {author: comment.author, body: comment.body}.to_json)
  render status_code: 201
end

When the client disconnects or the server stops, the stream closes, on_close unsubscribes and closes the channel, receive? returns nil, and the loop ends.

Across processes ​

With several processes or servers, a message published in one must reach subscribers in all of them. PostgreSQL's LISTEN/NOTIFY does this without extra infrastructure. Each process listens and feeds its hub:

src/main.cr
crystal
PG.connect_listen(ENV["DATABASE_URL"], "blog_events") do |notification|
  topic, _, message = notification.payload.partition('\t')
  BLOG_HUB.publish(topic, message)
end

and publishing becomes a NOTIFY, through a named query. pg_notify returns nothing, so the query counts the notifications to give sqlc a result column:

db/queries/events.sql
sql
-- name: NotifyEvent :one
SELECT count(*) AS sent FROM (SELECT pg_notify('blog_events', sqlc.arg(payload)::text)) AS notified;
crystal
store.notify_event(payload: "post:#{input.post_id}\t#{message}")

A NOTIFY payload is limited to 8000 bytes; send an ID and let subscribers load the rest. For channels, presence and an ActionCable-compatible protocol, see cable-cr/cable.

Shutdown ​

When the server stops, it stops accepting connections and then closes the open ones:

  • event streams close: events.wait returns false, on_close callbacks run, and the response ends;
  • WebSockets receive a close frame with code 1001 Going Away.

Shutdown then waits, up to shutdown_timeout, for them to finish like any other request — see Graceful shutdown. Browsers' EventSource reconnects by itself; WebSocket clients should reconnect when they see 1001.

Behind a proxy ​

Long-lived connections need two things from a reverse proxy: a read timeout longer than the heartbeat, and, for WebSockets, the upgrade headers. With nginx:

nginx
location / {
  proxy_pass http://app;
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection $connection_upgrade;
  proxy_read_timeout 1h;
}

# in the http block
map $http_upgrade $connection_upgrade {
  default upgrade;
  ''      close;
}

Testing ​

require "runcobo/testing" in spec/spec_helper.cr adds helpers that run your app on a random port and read streams and sockets:

spec/watch_post_spec.cr
crystal
require "./spec_helper"
require "runcobo/testing"

describe "GET /posts/:id/events" do
  it "sends new comments" do
    post = TEST_STORE.create_post(title: "Hello", body: "World")
    Runcobo::Testing.serve([Blog::RouteHandler.new(TEST_STORE)] of HTTP::Handler) do |url|
      events = Runcobo::Testing::EventSource.open(url.resolve("/posts/#{post.id}/events"))
      events.status_code.should eq(200)

      HTTP::Client.post(url.resolve("/posts/#{post.id}/comments"),
        headers: HTTP::Headers{"Content-Type" => "application/json"},
        body: %({"author":"Ada","body":"Nice"}))

      comment = events.receive
      comment.event.should eq("comment")
      JSON.parse(comment.data)["author"].should eq("Ada")
      events.close
    end
  end
end

describe "WS /chat/:room" do
  it "echoes messages" do
    Runcobo::Testing.serve([Blog::RouteHandler.new(TEST_STORE)] of HTTP::Handler) do |url|
      socket = Runcobo::Testing::WebSocketClient.open(url.resolve("/chat/lobby"), HTTP::Headers{"Authorization" => "Bearer test-token"})
      socket.receive.should eq("joined lobby")
      socket.send "hi"
      socket.receive.should eq("HI")
      socket.close
    end
  end
end
HelperDescription
Runcobo::Testing.serve(handlers) { |url| ... }Runs the handlers on 127.0.0.1 and a free port, yields the base URL, then shuts down
EventSource.open(url, headers)Opens an event stream; status_code, headers, receive(timeout), ended?, close
WebSocketClient.open(url, headers)Opens a WebSocket; send, receive(timeout), closed (the close code), close. Raises Socket::Error when the handshake is refused

receive raises Runcobo::Testing::Timeout after 5 seconds without a message, so a missing event fails the spec instead of hanging it.

Released under the MIT License.