Build channels and broadcast¶
This page shows how to write a channel, choose the streams that each subscriber listens to, and broadcast messages from anywhere in your app. It assumes that mankai-sockets is installed and the provider is registered, as in Add your first WebSocket channel. For the terms channel, subscription, stream, and broadcast, see How WebSockets work.
Create a channel¶
To create a channel that browsers can subscribe to, complete the following steps:
-
Create the channel class in
app/channels/. It inherits from your app's base class,Bookshelf::Channel, and gets its collaborators throughDeps:# 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 endHanami registers the class under the container key
channels.chat. -
In
config/providers/sockets.rb, map a public name to the container key:The browser passes the public name,
"chat", aschannel:. A browser can reach only the channels that you list. For a channel in a slice, prefix the container key with the slice name, for example{"reports" => "admin:channels.reports"}. -
Restart the server. If a container key doesn't exist, the provider raises
Mankai::Sockets::ConfigurationErrorat boot.
At boot, the provider checks that every key exists but doesn't build the channels. A channel can
therefore depend on components that the provider registers, such as an operation that injects
sockets.broadcaster.
Accept a subscription with subscribe¶
subscribe receives a Subscription with the validated params (with Symbol keys), the
connection's identity, and the subscription id. Return one of the following results:
Success(streams: [...])accepts the subscription and attaches it to the streams.Success(streams: [...], data: {...})also sendsdatato this subscriber only. The browser'sconnected(data)callback receives it.Failure(reason)rejects the subscription. The browser'srejectedcallback runs.
If the channel has no params block, the browser must not send params. If the params fail
validation, Mankai rejects the subscription before subscribe runs.
unsubscribe runs when the subscription ends, including when the connection closes. It's
optional; use it, for example, to clean up presence data.
Handle actions with receive¶
receive gets the subscription and a Message with a name and data (with Symbol keys).
Mankai doesn't route actions to methods, so use case message.name to dispatch them. Keep business
logic in an operation or a job. Return one of the following results:
Success(data: {...}): the browser'sperformpromise resolves withdata.Success(), orSuccesswith any other value: theperformpromise resolves withundefined.Failure(reason): theperformpromise rejects.
The reason in your Failure never reaches the browser, so it can't leak details. The browser gets
a generic reason instead: invalid, unauthorized, or internal. For the full mapping, see
Failure reasons sent to the client.
If you need the real reason, log or instrument it in your operation. Mankai publishes exceptions
as mankai.sockets.error events.
Return an operation's result¶
A channel can return an operation's result directly, but watch for one trap. dry-operation wraps
whatever call returns in Success. If call ends with return Failure(...), the channel gets
Success(Failure(...)), and the browser treats the action as successful.
To avoid this, use step, which unwraps a Success and stops at the first Failure. The
following operation validates the message and broadcasts it:
# app/operations/post_message.rb
module Bookshelf
module Operations
class PostMessage < Bookshelf::Operation
include Deps["sockets.broadcaster"]
def call(room:, body:, user_id:)
body = step validate(body)
step broadcaster.call(
Mankai::Sockets::Stream.of("chat", room),
body: body,
user_id: user_id
)
end
private
def validate(body)
text = body.to_s.strip
text.empty? ? Failure(:empty_body) : Success(text)
end
end
end
end
call returns Success(message_id), Failure(:empty_body), or Failure(:too_large), and the
channel can return that result unchanged.
Name streams¶
Build a stream name from parts with Stream.of, which joins them with :. The following examples
build chat:42 and chat:42:admins:
Each part must be a String, Symbol, or Integer and can't contain :. For every rule, see
Streams in the reference.
Broadcast from anywhere¶
To broadcast from an action, a job, or an operation, inject sockets.broadcaster and call it with a
stream and a Hash:
include Deps["sockets.broadcaster"]
broadcaster.call(
Mankai::Sockets::Stream.of("chat", room),
body: "Hello",
user_id: user.id
)
call returns Success(message_id), or Failure(:too_large) if the JSON is larger than
max_payload_size (60,000 bytes by default).
Publishing doesn't need a running WebSocket server, so a job can broadcast on its own. With the memory backend, though, only connections in the same process receive the broadcast, so a job in a worker process reaches nobody. To reach other processes, use the SQL backend; see Broadcast across processes.
Send different messages to different subscribers¶
To send different messages to different subscribers, give each subscriber different streams when you accept the subscription. Mankai has no per-delivery filter; for the reason, see Design choices.
The following subscribe code adds an extra stream for admins:
streams = [Mankai::Sockets::Stream.of("chat", room)]
streams << Mankai::Sockets::Stream.of("chat", room, "admins") if admin?
Success(streams: streams)
Then broadcast admin-only messages to Stream.of("chat", room, "admins"), and messages for
everyone to Stream.of("chat", room).