New to WebSockets? Read WebSockets and follow Add your first WebSocket channel before you use this reference.
mankai-sockets¶
mankai-sockets adds WebSockets to Hanami 3 apps. It provides a Rack endpoint that you mount in your routes, channels that are ordinary container components, a validated frame protocol, and a browser client with no dependencies.
Use mankai-sockets when the server must push updates to the browser without waiting for a request, for example for chat, notifications, or live dashboards. This page is the reference for the provider settings, the channel and broadcaster APIs, authentication, the browser client, events, testing helpers, and the backend contract.
- If you're new to WebSockets in Mankai, follow Add your first WebSocket channel.
- For the concepts behind the API, see How WebSockets work.
- For task-based instructions, see the WebSockets guides.
- For the frame format and close codes, see the mankai-sockets protocol.
Requirements¶
mankai-sockets needs the following:
- Ruby 3.3 or later.
- Hanami 3.0 or later.
- Rack 3.
- A web server that supports Rack full hijack, which lets the app take over the client's TCP socket. Puma, Hanami's default server, supports it.
Installation¶
To add WebSockets to a Hanami app, complete the following steps:
-
Add the gem to your
Gemfile, in both the:defaultand:cligroups. The:cligroup makes thehanami socketscommands available: -
Install the bundle:
-
Run the installer. The following command uses the memory backend and writes no migration:
The installer copies the browser client into your app and prints the provider, route, and session snippets for the next steps. For every option, see The
hanami sockets installcommand. -
Add a base class for your channels, in the same way that
app/action.rbis the base class for actions. The file requires the gem, so that channel classes also load in specs and in the console before the provider starts: -
Register the provider in
config/providers/sockets.rb:# config/providers/sockets.rb require "mankai/sockets" Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do configure do |config| config.backend = :memory config.authenticator = lambda do |request, _token_subject| user_id = request.session[:user_id] user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id) end config.allowed_origins = :same_origin config.channels = {"chat" => "channels.chat"} end endThe app doesn't boot until every container key in
config.channelsexists. For thechannels.chatexample, createapp/channels/chat.rb; see Channels. -
Enable sessions, because this authenticator reads
request.session. rack-session needs a secret of at least 64 bytes: -
Mount the endpoint in
config/routes.rb. The path is your choice; the Mankai docs use/sockets:The endpoint is a Rack app inside your app's middleware stack, so sessions, logging, and security middleware run for the upgrade request.
-
Load the browser client on a page. See Load the browser client.
The hanami sockets install command¶
The installer copies the browser client into your app and prints configuration snippets. It accepts the following option:
| Option | Default | Description |
|---|---|---|
--backend |
sql |
The backend to set up: sql or memory. With sql, the installer also writes the create_mankai_sockets_messages migration. |
The installer copies the client to one of the following paths:
app/assets/js/mankai-sockets.js, if hanami-assets is in the bundle.public/js/mankai-sockets.js, otherwise.
With --backend=sql, the installer can write the migration only if mankai-sockets-sql is in the
:cli group, because the hanami command loads only that group. If the gem isn't loaded, the
installer prints a reminder and writes no migration. If the migration exists, the installer leaves
it alone.
After you upgrade the gem, run the installer again to copy the matching client.
Configuration¶
Components¶
The provider registers the following components in your app's container:
| Key | Description |
|---|---|
sockets.endpoint |
The Rack app to mount in config/routes.rb. |
sockets.broadcaster |
The broadcaster. Inject it wherever you broadcast. |
sockets.server |
The object that owns this process's connections. It provides disconnect. |
sockets.backend |
The configured backend. |
sockets.channels |
The channel map built from config.channels. |
sockets.tokens |
The token issuer. Registered only when token_secret is set. |
The provider validates its settings when it starts, so a mistake fails at boot with
Mankai::Sockets::ConfigurationError. Starting the provider only builds objects. Threads and
database connections start when the process accepts its first WebSocket connection.
Provider settings¶
The following table lists the provider settings and their defaults:
| Setting | Default | Description |
|---|---|---|
backend |
:memory |
The backend: :memory, a backend object, or a factory such as Mankai::Sockets::SQL.backend(...). See Backends. |
authenticator |
nil |
A callable, ->(request, token_subject) { identity_or_nil }. Required unless allow_anonymous is true. See Authentication. |
allow_anonymous |
false |
If true, accepts clients for which the authenticator returns nil, each with its own anonymous identity. If false, closes their connections with code 4401. |
allowed_origins |
nil |
Required. The pages that can connect: :same_origin or an Array of origins. See Allowed origins. |
token_secret |
nil |
The secret that signs tokens, at least 32 bytes. Setting it enables tokens and registers sockets.tokens. |
channels |
{} |
Required. A Hash that maps each public channel name to a container key, such as {"chat" => "channels.chat"}. |
max_frame_size |
65_536 |
The largest inbound frame, in bytes. A larger frame closes the connection with code 1009. |
max_payload_size |
60_000 |
The largest broadcast, and the largest data in a subscribed frame, in bytes of JSON. |
max_subscriptions |
100 |
The most subscriptions on one connection. One more closes the connection with code 4429. |
max_buffered_bytes |
1_048_576 |
The most unsent bytes for one connection. Over this limit, the connection closes as a slow consumer with code 4008. |
max_connections_per_identity |
20 |
The most connections for one identity key in one process. One more closes with code 4430. |
hello_timeout |
10 |
The seconds a client has to send hello after it connects. A late client is closed with code 4408. |
heartbeat_interval |
15 |
The seconds between server pings. A connection that sends nothing for twice this interval closes with code 4000. |
executor_threads |
4 |
The number of threads that run the authenticator and channel code. |
logger_key |
"logger" |
The container key of the logger, if one is registered. |
notifications_key |
"notifications" |
The container key of the dry-monitor bus that receives events. |
clock |
-> { Time.now.utc } |
A callable that returns the current UTC time. Replace it in tests. |
Channel code runs on the executor threads. If your channels query the database, size the database
pool for at least executor_threads connections, plus one for the SQL backend's listener.
For the close codes in this table, see Close codes in the protocol.
Channels¶
A channel is a stateless container component that inherits from Mankai::Sockets::Channel. It
declares its params, chooses streams when a client subscribes, and handles actions from the client.
The following example is a complete channel that delegates its business logic to an operation:
# app/channels/chat.rb
module Bookshelf
module Channels
class Chat < Bookshelf::Channel
include Deps["operations.post_message"]
params do
required(:room).filled(:integer)
end
def subscribe(subscription)
room = subscription.params[:room]
return Failure(:not_allowed) unless room > 0
Success(streams: [Mankai::Sockets::Stream.of("chat", room)], data: {room: room})
end
def receive(subscription, message)
case message.name
when "speak"
post_message.call(
room: subscription.params[:room],
body: message.data[:body],
user_id: subscription.identity.value
)
else
Failure(:unknown_action)
end
end
def unsubscribe(subscription)
end
end
end
end
Channel registration¶
config.channels lists every channel that a client can reach. Mankai has no channel discovery.
Each entry maps a public name to a container key:
- A public name is 1 to 128 characters of lowercase letters, digits,
_,:, and-. The client sends it aschannel. - A container key names the channel component, such as
"channels.chat"forapp/channels/chat.rb. For a channel in a slice, prefix the key with the slice name, such as"admin:channels.reports".
At boot, the provider checks that every key is registered, but it doesn't build the channels. A
channel can therefore depend on components that the provider registers, such as an operation that
injects sockets.broadcaster. Mankai resolves the component again for each request, so code
reloading picks up changes.
Channel methods¶
A channel class has the following methods:
| Method | Description |
|---|---|
params(&block) |
Class method. Declares the dry-schema for subscription params. Without a params block, a subscription must send no params. |
subscribe(subscription) |
Required. Accepts or rejects a subscription and chooses its streams. |
receive(subscription, message) |
Handles one action from the client. Dispatch on message.name yourself. The default returns Failure(:unknown_action). |
unsubscribe(subscription) |
Optional. Runs when the subscription ends, including when the connection closes. Mankai ignores its return value. |
subscribe and receive get a Mankai::Sockets::Subscription with the following attributes:
| Attribute | Description |
|---|---|
id |
The subscription ID that the client chose. Unique on its connection. |
channel |
The public channel name. |
params |
The validated params, as a Hash with Symbol keys. |
identity |
The connection's Identity. |
session_id |
The connection ID, the same as session_id in events. |
receive also gets a Mankai::Sockets::Message with the following attributes:
| Attribute | Description |
|---|---|
name |
The action name, a non-empty String. |
data |
The action data, as a Hash with Symbol keys. |
ref |
The client's reply reference, or nil. |
Return values¶
subscribe and receive return a dry-monads Result. The following table shows what each result
does on the client:
| Method | Return value | What the client gets |
|---|---|---|
subscribe |
Success(streams: [...]) |
A subscribed frame. The browser client runs connected(data). streams is required and must be an Array of Stream objects. |
subscribe |
Success(streams: [...], data: {...}) |
The same, with data in the subscribed frame. Only this subscriber gets data. |
subscribe |
Failure(reason) |
A rejected frame. The browser client runs rejected(reason) with a generic reason. |
receive |
Success(data: {...}) |
An ack frame. The perform promise resolves with data. |
receive |
Success(), or Success with any other value |
An ack frame. The perform promise resolves with undefined. |
receive |
Failure(reason) |
An error frame. The perform promise rejects with a generic reason. |
The server sends ack and error frames only when the action had a ref. The browser client
always sends one.
Failure reasons sent to the client¶
Your Failure reason never reaches the client, so it can't leak details. The client gets one of
three generic reasons instead, as the following table shows:
| Situation | Frame | Reason |
|---|---|---|
subscribe returned Failure or raised an exception |
rejected |
unauthorized |
Unknown channel, invalid params, or streams: isn't an Array of Stream objects |
rejected |
invalid |
The subscribed data is larger than max_payload_size |
rejected |
internal |
receive returned Failure |
error |
unauthorized |
receive raised an exception |
error |
internal |
| An action for a subscription that doesn't exist | error |
invalid |
Exceptions from channel code are published as mankai.sockets.error events.
Broadcaster¶
sockets.broadcaster publishes a message to every subscription that listens to a stream. Inject it
in an action, job, operation, or channel. The following example broadcasts to a chat room:
include Deps["sockets.broadcaster"]
broadcaster.call(Mankai::Sockets::Stream.of("chat", room), body: "Hello", user_id: user.id)
call(stream, data) takes the following arguments:
| Argument | Description |
|---|---|
stream |
The destination, a Mankai::Sockets::Stream. |
data |
The message, a Hash that Mankai encodes as JSON. |
call returns one of the following results:
Success(id), whereidis the message ID, anInteger, that the backend assigned.Failure(:too_large), if the JSON is larger thanmax_payload_size.
call raises ArgumentError if stream isn't a Stream or data isn't a Hash. Each
subscription whose channel selected the stream receives data in a message frame.
Publishing doesn't need a running server, so a job or a console can broadcast. With the memory backend, though, a broadcast reaches only connections in the same process. To reach other processes, use the SQL backend; see Backends.
Streams¶
A stream is a named destination for broadcasts. Mankai::Sockets::Stream.of(*parts) builds one by
joining its parts with :. The following example builds the stream chat:42:admins:
Stream.of raises ArgumentError if any of the following rules is broken:
- Each part is a non-empty
String,Symbol, orInteger, and doesn't contain:. - The full name is at most 255 bytes.
- The name doesn't start with
mankai., which Mankai reserves.
Authentication¶
Authenticator¶
The authenticator decides who a connection belongs to. Mankai calls it once per connection, when
the client sends its hello frame, on an executor thread. It receives the following arguments:
| Argument | Description |
|---|---|
request |
The Rack::Request of the upgrade request. Cookies and request.session work if the app has sessions enabled. |
token_subject |
The verified token subject, a String, or nil if the client sent no token. |
The authenticator returns one of the following values:
- A
Mankai::Sockets::Identity, which accepts the connection. nil, which closes the connection with code 4401, unlessallow_anonymousistrue.
If the authenticator raises an exception, Mankai closes the connection with code 4401 and publishes
the exception as a mankai.sockets.error event.
The browser sends the session cookie with a same-origin WebSocket connection. Session
authentication also needs config.actions.sessions in config/app.rb.
Identities¶
Mankai::Sockets::Identity.new(key:, value: nil) has the following attributes:
| Attribute | Description |
|---|---|
key |
A non-empty String, such as "user:42", that groups one person's connections. Mankai uses it for max_connections_per_identity and disconnect. Keep it stable. |
value |
Any value your app needs, such as a user ID. Mankai never sends it to a client. Channels read it as subscription.identity.value. |
With allow_anonymous = true, each anonymous connection gets the key anonymous:SESSION_ID, where
SESSION_ID is the connection ID, and the value nil. Use anonymous connections only in
development or for public feeds.
Tokens¶
A token is a short-lived, signed subject for clients that can't send the session cookie, such as a
browser that connects to another host. Setting token_secret registers sockets.tokens, a
Mankai::Sockets::Tokens with the following methods:
| Method | Description |
|---|---|
issue(subject, expires_in: 60) |
Returns a signed token for subject that expires after expires_in seconds. Converts subject with to_s. Raises ArgumentError if subject is nil or empty. |
verify(token) |
Returns Success(subject), Failure(:invalid), or Failure(:expired). Mankai calls it for you on hello. |
The client sends the token in its hello frame, at most 2048 bytes. Mankai checks the token only
when the connection opens. An invalid or expired token closes the connection with code 4401. So
does any token if token_secret isn't set.
For the steps to issue tokens from an action, see Authenticate connections.
Allowed origins¶
config.allowed_origins is required. It accepts one of the following values:
:same_origin, which accepts the app's own origin.- An
Arrayof patterns. A pattern is an exact origin, such as"https://example.com", or a subdomain wildcard, such as"https://*.example.com".
Origins match as follows:
- An exact origin matches scheme, host, and port. A missing port means the scheme's default port.
- A wildcard matches subdomains only. To accept the bare domain too, list it separately.
- Mankai has no "allow all" value.
- Mankai refuses a request without an
Originheader.
A refused origin gets an HTTP 403 response before the upgrade and a mankai.sockets.reject event.
Mankai parses the patterns when the provider starts, so an invalid pattern fails at boot.
Browser client¶
The browser client is one ES module, mankai-sockets.js, with no dependencies. The installer
copies it into your app.
Load the browser client¶
Load your page code as a module file, not an inline <script>, because Hanami's default Content
Security Policy (script-src 'self') blocks inline scripts. How you load the client depends on
whether your app uses hanami-assets:
-
With hanami-assets, import the client from your entry point. The asset build bundles it into the script that your layout loads with
javascript_tag "app": -
Without hanami-assets, serve
public/jswithRack::Static, because Hanami doesn't servepublic/on its own. In production, your proxy can serve the directory instead:# config/app.rb require "hanami" require "rack/static" module Bookshelf class App < Hanami::App config.middleware.use Rack::Static, urls: ["/js"], root: File.expand_path("../public", __dir__) end endThen import the client from a module file next to it, and load that file from a template:
Client API¶
The following example creates a consumer, subscribes to a channel, and opens the connection:
const consumer = createConsumer("/sockets", {
reconnect: {minDelay: 500, maxDelay: 30_000},
logger: console,
});
const subscription = consumer.subscriptions.create(
{channel: "chat", params: {room: 42}},
{
connected(data) {},
received(data) {},
rejected(reason) {},
disconnected() {},
},
);
consumer.connect();
createConsumer(url, options) returns a consumer. url is one of the following:
- A path, such as
"/sockets". The scheme follows the page:wss:on anhttps:page, andws:otherwise. - A
ws://orwss://URL. - A function that returns a path or URL. The client calls it before each connection attempt.
Any other URL, including an http:// URL, is logged, and nothing connects.
createConsumer accepts the following options:
| Option | Default | Description |
|---|---|---|
token |
None | A token String, or a function that returns one or a promise of one. The client calls the function before each connection attempt. |
reconnect |
{minDelay: 500, maxDelay: 30_000} |
The bounds of the reconnection delay, in milliseconds. |
logger |
None | An object with debug, info, warn, and error methods, such as console. Logging is off without it. |
A consumer has the following members:
| Member | Description |
|---|---|
connect() |
Opens the connection. Nothing connects before you call it. |
close() |
Closes the connection for good. A closed consumer never reconnects, and connect() does nothing. To connect again, create a new consumer. |
subscriptions.create(params, callbacks) |
Creates a subscription. params is {channel, params}. The client sends it when the connection is ready, and again after each reconnect. |
The callbacks object can have the following functions:
| Callback | When it runs |
|---|---|
connected(data) |
The server accepted the subscription, including after a reconnect. data is the channel's optional data. |
received(data) |
A broadcast arrived on one of the subscription's streams. |
rejected(reason) |
The server refused the subscription with invalid, unauthorized, or internal. The subscription is gone. |
disconnected() |
The connection dropped after the server had accepted this subscription. |
A subscription has the following methods:
| Method | Description |
|---|---|
perform(name, data) |
Sends an action and returns a promise. The promise resolves with the channel's Success(data:) value. It rejects with an Error whose message is a generic reason, or not connected. |
unsubscribe() |
Ends this subscription. |
perform rejects with not connected until the server has accepted the connection, so call it
from connected or from a later user event, not right after connect(). Pending promises reject
when the connection drops.
The client replies to server pings. After a dropped connection, it reconnects after a random delay that grows with each failed attempt (full-jitter backoff) and resets after a successful connection. After a reconnect, it re-sends every subscription except the rejected and unsubscribed ones. It doesn't reconnect after close code 4400, 4401, 4429, or 4430, because the next attempt fails in the same way.
HTTP responses¶
Before the upgrade, the endpoint can refuse a request with HTTP 426, 403, 400, or 501. For the cause of each status, see Handshake responses in the protocol. A 501 response means that the web server doesn't support Rack full hijack; use Puma.
Disconnect an identity¶
To close every connection that belongs to an identity, call disconnect with the identity key:
disconnect publishes a control message through the backend. Each process that receives it closes
that identity's connections with code 4401, and the browser client doesn't reconnect. You can call
disconnect from a process that serves no WebSocket connections, such as a job worker. Only the
SQL backend carries the message to other processes; with the memory backend, it reaches only the
current process.
Each process enforces max_connections_per_identity separately. Behind a load balancer, one
identity can hold that many connections in every process.
Events¶
Mankai publishes events on the app's notifications bus, which the notifications_key setting
names. Events carry IDs, names, and byte counts, but never tokens, params, or message data. The
following table lists each event and its payload:
| Event | Payload |
|---|---|
mankai.sockets.connect |
session_id, identity_key |
mankai.sockets.disconnect |
session_id, identity_key, code |
mankai.sockets.subscribe |
session_id, channel, subscription_id |
mankai.sockets.unsubscribe |
session_id, subscription_id |
mankai.sockets.reject |
session_id, subscription_id, reason for a rejected subscription; origin, reason: :origin for a refused origin |
mankai.sockets.action |
session_id, channel, subscription_id, action, outcome (:success, :failure, or :error) |
mankai.sockets.broadcast |
stream, bytes |
mankai.sockets.error |
exception, plus session_id if the error came from a connection |
The provider registers the events when it starts, so subscribe in an after(:start) hook. The
following example logs every error:
# config/providers/sockets.rb
Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
configure do |config|
# ...
end
after(:start) do
target["notifications"].subscribe(:"mankai.sockets.error") do |event|
target["logger"].error(event[:exception])
end
end
end
Testing¶
require "mankai/sockets/testing" loads helpers for testing channels without a connection. Because
channels are components, a spec can build one with test dependencies and call subscribe and
receive directly.
The following spec tests the chat channel with a recording broadcaster:
# spec/channels/chat_spec.rb
require "mankai/sockets/testing"
RSpec.describe Bookshelf::Channels::Chat do
include Mankai::Sockets::Testing::Channels
include Mankai::Sockets::Testing::Matchers
subject(:channel) { described_class.new(post_message: post_message) }
let(:broadcaster) { Mankai::Sockets::Testing::RecordingBroadcaster.new }
let(:post_message) { Bookshelf::Operations::PostMessage.new(broadcaster: broadcaster) }
let(:subscription) do
subscription_for(params: {room: 1}, identity: Mankai::Sockets::Identity.new(key: "user:7", value: "7"))
end
it "broadcasts what was said" do
result = channel.receive(subscription, message("speak", body: "hi"))
expect(result).to be_success
expect(broadcaster).to have_broadcast(
Mankai::Sockets::Stream.of("chat", 1), a_hash_including(body: "hi", user_id: "7")
)
end
end
Mankai::Sockets::Testing provides the following helpers:
| Helper | Description |
|---|---|
Channels#subscription_for(params: {}, identity:, id: "s1", channel: "test") |
Builds a Subscription. The default identity has the key "test". |
Channels#message(name, data = {}) |
Builds a Message. Keyword arguments also work, such as message("speak", body: "hi"). |
RecordingBroadcaster |
A broadcaster that records each [stream, data] pair in broadcasts instead of sending it. call returns Success with a counter. |
Matchers#have_broadcast(stream, data = nil) |
An RSpec matcher for a recorded broadcast to stream. data is a Hash compared with ==, or a matcher such as a_hash_including. Leave it out to match any data. |
Matchers#assert_broadcast(broadcaster, stream, data = nil) |
The Minitest equivalent. Raises Minitest::Assertion if Minitest is loaded, and RuntimeError otherwise. |
Use the memory backend in the test environment. To test your own backend, use the shared examples
in mankai/sockets/testing/backend_examples; see Backend contract.
Backends¶
A backend carries broadcasts from the broadcaster to the connections that listen to a stream. Mankai has two backends, which differ in which connections a broadcast reaches:
| Backend | Reaches | Use it for |
|---|---|---|
:memory |
Connections in the same process. | Development, tests, and apps with one Puma process. |
Mankai::Sockets::SQL.backend(...) |
Connections in every process that uses the database. | Several Puma workers or servers, a separate WebSocket process, or broadcasts from jobs. See mankai-sockets-sql. |
The memory backend delivers each broadcast synchronously, inside publish, on the caller's thread.
Backend contract¶
config.backend accepts a backend object, or a factory that responds to call(context) and
returns one. A backend has the following methods:
| Method | Description |
|---|---|
publish(stream_name, payload) |
Stores or sends payload, a JSON String, and returns an Integer message ID. Must work before start. |
subscribe(stream_name, listener) |
Calls listener.call(broadcast) for each message on that stream. |
unsubscribe(stream_name, listener) |
Stops calling that listener. |
start |
Starts threads or connections. Mankai calls it when each process accepts its first WebSocket connection. |
stop |
Stops them. Mankai calls it when the provider stops. |
A broadcast is a Mankai::Sockets::Broadcast with stream, id, and payload attributes.
Listeners run on the backend's thread, so they must return quickly and must not block.
The factory's context is a Mankai::Sockets::Context with the following attributes:
container, instrumenter, logger, clock, and executor_threads.
To check a backend against the contract, use the shared examples:
require "mankai/sockets/testing/backend_examples"
RSpec.describe MyBackend do
subject(:backend) { MyBackend.new }
it_behaves_like "a mankai-sockets backend"
end