mankai-sockets 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +28 -0
  3. data/LICENSE +20 -0
  4. data/PROTOCOL.md +111 -0
  5. data/README.md +630 -0
  6. data/js/mankai-sockets.js +244 -0
  7. data/js/package.json +4 -0
  8. data/js/test/client.test.js +225 -0
  9. data/lib/mankai/sockets/authentication.rb +72 -0
  10. data/lib/mankai/sockets/backends/memory.rb +69 -0
  11. data/lib/mankai/sockets/broadcast.rb +22 -0
  12. data/lib/mankai/sockets/broadcaster.rb +43 -0
  13. data/lib/mankai/sockets/channel.rb +82 -0
  14. data/lib/mankai/sockets/channel_map.rb +130 -0
  15. data/lib/mankai/sockets/cli.rb +157 -0
  16. data/lib/mankai/sockets/close_code.rb +57 -0
  17. data/lib/mankai/sockets/context.rb +24 -0
  18. data/lib/mankai/sockets/endpoint.rb +60 -0
  19. data/lib/mankai/sockets/errors.rb +20 -0
  20. data/lib/mankai/sockets/executor.rb +61 -0
  21. data/lib/mankai/sockets/frames.rb +131 -0
  22. data/lib/mankai/sockets/hub.rb +85 -0
  23. data/lib/mankai/sockets/identity.rb +21 -0
  24. data/lib/mankai/sockets/instrumenter.rb +65 -0
  25. data/lib/mankai/sockets/limits.rb +37 -0
  26. data/lib/mankai/sockets/mailbox.rb +58 -0
  27. data/lib/mankai/sockets/message.rb +24 -0
  28. data/lib/mankai/sockets/origin_policy.rb +117 -0
  29. data/lib/mankai/sockets/protocol.rb +186 -0
  30. data/lib/mankai/sockets/provider_source.rb +224 -0
  31. data/lib/mankai/sockets/server.rb +106 -0
  32. data/lib/mankai/sockets/session.rb +331 -0
  33. data/lib/mankai/sockets/session_dependencies.rb +19 -0
  34. data/lib/mankai/sockets/session_factory.rb +50 -0
  35. data/lib/mankai/sockets/sessions.rb +49 -0
  36. data/lib/mankai/sockets/stream.rb +70 -0
  37. data/lib/mankai/sockets/subscription.rb +55 -0
  38. data/lib/mankai/sockets/subscriptions.rb +54 -0
  39. data/lib/mankai/sockets/testing/backend_examples.rb +69 -0
  40. data/lib/mankai/sockets/testing.rb +151 -0
  41. data/lib/mankai/sockets/tokens.rb +96 -0
  42. data/lib/mankai/sockets/transport/reactor.rb +152 -0
  43. data/lib/mankai/sockets/transport/socket.rb +150 -0
  44. data/lib/mankai/sockets/version.rb +9 -0
  45. data/lib/mankai/sockets.rb +40 -0
  46. data/lib/mankai-sockets.rb +3 -0
  47. data/mankai-sockets.gemspec +39 -0
  48. metadata +193 -0
data/README.md ADDED
@@ -0,0 +1,630 @@
1
+ <img src="../../assets/logo/mankai-logo.svg" alt="Mankai" width="72">
2
+
3
+ # mankai-sockets
4
+
5
+ Websockets for Hanami apps: an endpoint you mount in routes, channels that are container
6
+ components, a validated frame protocol, and a dependency-free browser client.
7
+
8
+ The wire contract is in [PROTOCOL.md](https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-sockets/PROTOCOL.md).
9
+
10
+ ## Setup
11
+
12
+ ```ruby
13
+ # Gemfile: the :cli group adds the `hanami sockets ...` commands
14
+ gem "mankai-sockets", group: [:default, :cli]
15
+ # Optional: broadcasts between processes (see "Backends")
16
+ gem "mankai-sockets-sql", group: [:default, :cli]
17
+ ```
18
+
19
+ ```bash
20
+ bundle install
21
+ bundle exec hanami sockets install # --backend=sql is the default
22
+ bundle exec hanami sockets install --backend=memory # no migration
23
+ ```
24
+
25
+ The installer copies the browser client into the app and prints the provider, route and session
26
+ snippets below. With hanami-assets in the bundle it copies the client to
27
+ `app/assets/js/mankai-sockets.js`; without it, to `public/js/mankai-sockets.js`. With
28
+ `--backend=sql` it also writes the `create_mankai_sockets_messages` migration, but only when
29
+ `mankai-sockets-sql` is in the `:cli` group: `hanami` loads only that group, and without the gem it
30
+ prints a reminder and writes nothing.
31
+
32
+ Add a base class for your channels, like `app/action.rb` is for actions. It requires the gem, so
33
+ channel classes load in specs and the console before the provider starts:
34
+
35
+ ```ruby
36
+ # app/channel.rb
37
+ # auto_register: false
38
+ require "mankai/sockets"
39
+
40
+ module Bookshelf
41
+ class Channel < Mankai::Sockets::Channel
42
+ end
43
+ end
44
+ ```
45
+
46
+ Register the provider:
47
+
48
+ ```ruby
49
+ # config/providers/sockets.rb
50
+ require "mankai/sockets"
51
+
52
+ Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
53
+ configure do |config|
54
+ config.backend = :memory
55
+ config.authenticator = lambda do |request, _token_subject|
56
+ user_id = request.session[:user_id]
57
+ user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
58
+ end
59
+ config.allowed_origins = :same_origin
60
+ config.channels = {"chat" => "channels.chat"}
61
+ end
62
+ end
63
+ ```
64
+
65
+ The authenticator reads `request.session`, so enable sessions. rack-session needs a secret of at
66
+ least 64 bytes:
67
+
68
+ ```ruby
69
+ # config/app.rb
70
+ config.actions.sessions = :cookie, {secret: settings.session_secret}
71
+ ```
72
+
73
+ Mount the endpoint:
74
+
75
+ ```ruby
76
+ # config/routes.rb
77
+ mount Hanami.app["sockets.endpoint"], at: "/sockets"
78
+ ```
79
+
80
+ The endpoint is a plain Rack app inside the app's middleware stack, so sessions, logging and
81
+ security middleware run for the upgrade request. It needs a server with Rack full hijack, such as
82
+ Puma. Then [load the browser client](#loading-the-client).
83
+
84
+ The provider registers these components:
85
+
86
+ | Key | What it is |
87
+ |---|---|
88
+ | `sockets.endpoint` | The Rack app to mount |
89
+ | `sockets.broadcaster` | Publishes to a stream; inject it where you broadcast |
90
+ | `sockets.server` | Owns this process's connections; `disconnect` lives here |
91
+ | `sockets.backend` | The configured backend |
92
+ | `sockets.channels` | The channel map built from `config.channels` |
93
+ | `sockets.tokens` | Issues and verifies tokens; only registered when `token_secret` is set |
94
+
95
+ The provider validates its settings when it starts, so mistakes fail at boot with
96
+ `Mankai::Sockets::ConfigurationError`. Starting it builds objects only: threads and database
97
+ connections start with the first websocket.
98
+
99
+ ### Provider settings
100
+
101
+ | Setting | Default | Description |
102
+ |---|---|---|
103
+ | `backend` | `:memory` | `:memory`, a backend object, or a factory such as `Mankai::Sockets::SQL.backend(...)` |
104
+ | `authenticator` | `nil` | `->(request, token_subject) { Identity or nil }`. Required unless `allow_anonymous` |
105
+ | `allow_anonymous` | `false` | Accept clients the authenticator returns `nil` for, each with its own anonymous identity |
106
+ | `allowed_origins` | `nil` | Required. `:same_origin` or an Array of origins; see [Allowed origins](#allowed-origins) |
107
+ | `token_secret` | `nil` | At least 32 bytes. Enables [tokens](#tokens) and registers `sockets.tokens` |
108
+ | `channels` | `{}` | Required. Public channel name => container key, such as `{"chat" => "channels.chat"}` |
109
+ | `max_frame_size` | `65_536` | Largest inbound frame in bytes; larger ones close the connection with 1009 |
110
+ | `max_payload_size` | `60_000` | Largest broadcast, and largest `data` in a `subscribed` frame, in bytes of JSON |
111
+ | `max_subscriptions` | `100` | Subscriptions per connection; one more closes it with 4429 |
112
+ | `max_buffered_bytes` | `1_048_576` | Unsent bytes per connection before it's closed as a slow consumer (4008) |
113
+ | `max_connections_per_identity` | `20` | Connections per identity key, per process; one more closes with 4430 |
114
+ | `hello_timeout` | `10` | Seconds a client has to send `hello` (4408) |
115
+ | `heartbeat_interval` | `15` | Seconds between server pings; silent connections close after twice this (4000) |
116
+ | `executor_threads` | `4` | Threads that run the authenticator and channel code |
117
+ | `logger_key` | `"logger"` | Container key of the logger, if registered |
118
+ | `notifications_key` | `"notifications"` | Container key of the dry-monitor bus for [events](#events) |
119
+ | `clock` | `-> { Time.now.utc }` | Current UTC time; replace it in tests |
120
+
121
+ Channel code runs on the executor threads, so a database pool needs at least `executor_threads`
122
+ connections for channels that query, plus one for the SQL backend's listener.
123
+
124
+ ## Channels
125
+
126
+ Channels are stateless container components. Declare their params, choose streams in `subscribe`,
127
+ and dispatch actions in `receive` yourself. Put business logic in an operation and inject it:
128
+
129
+ ```ruby
130
+ # app/channels/chat.rb
131
+ module Bookshelf
132
+ module Channels
133
+ class Chat < Bookshelf::Channel
134
+ include Deps["operations.post_message"]
135
+
136
+ params do
137
+ required(:room).filled(:integer)
138
+ end
139
+
140
+ def subscribe(subscription)
141
+ room = subscription.params[:room]
142
+ return Failure(:not_allowed) unless room > 0
143
+
144
+ Success(streams: [Mankai::Sockets::Stream.of("chat", room)], data: {room: room})
145
+ end
146
+
147
+ def receive(subscription, message)
148
+ case message.name
149
+ when "speak"
150
+ post_message.call(
151
+ room: subscription.params[:room],
152
+ body: message.data[:body],
153
+ user_id: subscription.identity.value
154
+ )
155
+ else
156
+ Failure(:unknown_action)
157
+ end
158
+ end
159
+
160
+ def unsubscribe(subscription)
161
+ end
162
+ end
163
+ end
164
+ end
165
+ ```
166
+
167
+ `config.channels` lists every channel a client can reach; there is no discovery. Keys are container
168
+ keys: `"channels.chat"` for `app/channels/chat.rb`, or `"admin:channels.reports"` for a channel in
169
+ the `admin` slice. The provider checks each key at boot without building the channel, so a channel
170
+ may inject components the provider registers, such as `sockets.broadcaster`.
171
+
172
+ Params and action data are symbol-keyed hashes. Without a `params` block, a subscription must
173
+ send no params.
174
+
175
+ ### What the client receives
176
+
177
+ `subscribe` returns:
178
+
179
+ - `Success(streams: [...])`: required. The streams this subscription listens to. The client gets
180
+ `subscribed` and its `connected(data)` callback runs.
181
+ - `Success(streams: [...], data: {...})`: `data` goes only to this subscriber, in its `subscribed`
182
+ frame.
183
+ - `Failure(reason)`: the client gets `rejected` and its `rejected(reason)` callback runs.
184
+
185
+ `receive` returns:
186
+
187
+ - `Success(data: {...})`: the client's `perform` promise resolves with `data`.
188
+ - `Success()` or `Success` with any other value: `perform` resolves with `undefined`.
189
+ - `Failure(reason)`: `perform` rejects.
190
+
191
+ Your reason never reaches the client. The wire carries a generic reason instead:
192
+
193
+ | Situation | Frame | Reason |
194
+ |---|---|---|
195
+ | `subscribe` returned `Failure`, or raised | `rejected` | `unauthorized` |
196
+ | Unknown channel, invalid params, or `streams:` isn't an Array of `Stream`s | `rejected` | `invalid` |
197
+ | `subscribed` data over `max_payload_size` | `rejected` | `internal` |
198
+ | `receive` returned `Failure` | `error` | `unauthorized` |
199
+ | `receive` raised | `error` | `internal` |
200
+ | An action for a subscription that doesn't exist | `error` | `invalid` |
201
+
202
+ `error` is only sent when the client's action carried a `ref`; the browser client always sends
203
+ one. Exceptions go to the `mankai.sockets.error` event.
204
+
205
+ `unsubscribe` runs when the subscription ends, including when the connection closes. Its return
206
+ value is ignored.
207
+
208
+ ### Returning an operation's result
209
+
210
+ A dry-operation's `call` wraps its return value in `Success`, so a method that ends with
211
+ `return Failure(...)` produces `Success(Failure(...))` and the client gets an ack. Use `step`,
212
+ which stops at the first `Failure`:
213
+
214
+ ```ruby
215
+ # app/operations/post_message.rb
216
+ module Bookshelf
217
+ module Operations
218
+ class PostMessage < Bookshelf::Operation
219
+ include Deps["sockets.broadcaster"]
220
+
221
+ def call(room:, body:, user_id:)
222
+ body = step validate(body)
223
+ step broadcaster.call(Mankai::Sockets::Stream.of("chat", room), body: body, user_id: user_id)
224
+ end
225
+
226
+ private
227
+
228
+ def validate(body)
229
+ text = body.to_s.strip
230
+ text.empty? ? Failure(:empty_body) : Success(text)
231
+ end
232
+ end
233
+ end
234
+ end
235
+ ```
236
+
237
+ `call` now returns `Success(message id)` or `Failure(:empty_body)`, which the channel can return as
238
+ is.
239
+
240
+ ## Broadcasting
241
+
242
+ ```ruby
243
+ # In an action, job or operation:
244
+ include Deps["sockets.broadcaster"]
245
+
246
+ broadcaster.call(Mankai::Sockets::Stream.of("chat", room), body: "Hello", user_id: user.id)
247
+ ```
248
+
249
+ `call` returns `Success(message id)`, or `Failure(:too_large)` when the JSON is over
250
+ `max_payload_size`. It raises `ArgumentError` when the stream isn't a `Stream` or the data isn't a
251
+ Hash. Every subscription whose channel selected that stream receives the data in a `message` frame.
252
+
253
+ `Stream.of` joins its parts with `":"`. Parts are Strings, Symbols or Integers and can't contain
254
+ `":"`. A stream name is at most 255 bytes, and names starting with `mankai.` are reserved.
255
+
256
+ With the memory backend, a broadcast reaches connections in the same process only; a job running
257
+ in a worker process reaches nobody. Use the [SQL backend](#backends) to cross processes.
258
+
259
+ ## Different messages for different subscribers
260
+
261
+ There is no per-delivery filter: running app code for every recipient would hide work and make
262
+ reloading unsafe. Choose the audience when the subscription is accepted instead:
263
+
264
+ ```ruby
265
+ streams = [Mankai::Sockets::Stream.of("chat", room)]
266
+ streams << Mankai::Sockets::Stream.of("chat", room, "admins") if admin?
267
+ Success(streams: streams)
268
+ ```
269
+
270
+ Then broadcast to the audience stream that should receive the message.
271
+
272
+ ## Authentication
273
+
274
+ The authenticator is called once per connection, on `hello`, on an executor thread. It receives
275
+ the `Rack::Request` of the upgrade request, so cookies and `request.session` work, and the verified
276
+ token subject or `nil`. Return a `Mankai::Sockets::Identity` to accept the connection, or `nil` to
277
+ close it with 4401. An exception also closes with 4401 and is reported as an `error` event.
278
+
279
+ `Identity.new(key:, value:)`: the key is a non-empty String that groups a person's connections for
280
+ `max_connections_per_identity` and `disconnect`, such as `"user:42"`. The value is yours, never sent
281
+ to a client, and available as `subscription.identity.value`.
282
+
283
+ Session authentication needs `config.actions.sessions` in `config/app.rb`, and the browser must
284
+ send the session cookie, which it does for a same-origin websocket.
285
+
286
+ `config.allow_anonymous = true` accepts clients the authenticator returns `nil` for. Each gets its
287
+ own `anonymous:<session id>` identity. Use it in development or for public feeds only.
288
+
289
+ ### Tokens
290
+
291
+ Tokens are for clients that can't send the session cookie, such as a socket on another host. A
292
+ token is a short-lived signed subject. Add a setting for the secret:
293
+
294
+ ```ruby
295
+ # config/settings.rb
296
+ module Bookshelf
297
+ class Settings < Hanami::Settings
298
+ setting :session_secret, constructor: Types::String.constrained(min_size: 64)
299
+ setting :sockets_token_secret, constructor: Types::String.constrained(min_size: 32)
300
+ end
301
+ end
302
+ ```
303
+
304
+ Pass it to the provider, and use the subject in the authenticator. The subject is always a String:
305
+
306
+ ```ruby
307
+ # config/providers/sockets.rb
308
+ configure do |config|
309
+ config.token_secret = Hanami.app.settings.sockets_token_secret
310
+ config.authenticator = lambda do |request, token_subject|
311
+ user_id = token_subject || request.session[:user_id]
312
+ user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
313
+ end
314
+ # ...
315
+ end
316
+ ```
317
+
318
+ Issue tokens from an action:
319
+
320
+ ```ruby
321
+ # config/routes.rb
322
+ get "/sockets/token", to: "sockets.token"
323
+ mount Hanami.app["sockets.endpoint"], at: "/sockets"
324
+ ```
325
+
326
+ ```ruby
327
+ # app/actions/sockets/token.rb
328
+ module Bookshelf
329
+ module Actions
330
+ module Sockets
331
+ class Token < Bookshelf::Action
332
+ include Deps["sockets.tokens"]
333
+
334
+ def handle(request, response)
335
+ user_id = request.session[:user_id]
336
+ halt 401 unless user_id
337
+
338
+ response.headers["Cache-Control"] = "no-store"
339
+ response.format = :txt
340
+ response.body = tokens.issue(user_id, expires_in: 60)
341
+ end
342
+ end
343
+ end
344
+ end
345
+ end
346
+ ```
347
+
348
+ `issue(subject, expires_in: 60)` converts the subject with `to_s`, so `issue(current_user.id)`
349
+ works; a `nil` or empty subject raises `ArgumentError`. Give the client a function, so it fetches a
350
+ fresh token before every connect and reconnect:
351
+
352
+ ```js
353
+ const consumer = createConsumer("/sockets", {
354
+ token: async () => {
355
+ const response = await fetch("/sockets/token", {credentials: "same-origin"});
356
+ if (!response.ok) throw new Error(`token request failed (${response.status})`);
357
+ return response.text();
358
+ },
359
+ });
360
+ ```
361
+
362
+ Tokens are at most 2048 bytes. An invalid or expired token closes the connection with 4401, and so
363
+ does any token when `token_secret` isn't set.
364
+
365
+ ## Allowed origins
366
+
367
+ `config.allowed_origins` is required. Use `:same_origin`, an exact origin such as
368
+ `"https://example.com"`, or a subdomain wildcard such as `"https://*.example.com"` (the bare
369
+ domain must be listed separately). An exact origin matches scheme, host and port. There is no
370
+ "allow all" value and a missing `Origin` is refused. Patterns are parsed when the provider starts;
371
+ invalid ones fail at boot.
372
+
373
+ ## Browser client
374
+
375
+ ### Loading the client
376
+
377
+ The client is a single ES module with no dependencies. Load your page code as a module file, not
378
+ an inline `<script>`: Hanami's default Content Security Policy (`script-src 'self'`) blocks inline
379
+ scripts.
380
+
381
+ Without hanami-assets, the installer puts the client in `public/js`. Hanami doesn't serve
382
+ `public/` on its own, so add `Rack::Static` for that directory (in production, your proxy can
383
+ serve it instead):
384
+
385
+ ```ruby
386
+ # config/app.rb
387
+ require "hanami"
388
+ require "rack/static"
389
+
390
+ module Bookshelf
391
+ class App < Hanami::App
392
+ config.middleware.use Rack::Static, urls: ["/js"], root: File.expand_path("../public", __dir__)
393
+ end
394
+ end
395
+ ```
396
+
397
+ ```js
398
+ // public/js/chat.js
399
+ import {createConsumer} from "./mankai-sockets.js";
400
+ ```
401
+
402
+ ```erb
403
+ <%# app/templates/chat/show.html.erb %>
404
+ <script type="module" src="/js/chat.js"></script>
405
+ ```
406
+
407
+ With hanami-assets, the installer puts the client in `app/assets/js`. Import it from your entry
408
+ point, and the asset build bundles it into the script your layout's `javascript_tag "app"` loads:
409
+
410
+ ```js
411
+ // app/assets/js/app.js
412
+ import {createConsumer} from "./mankai-sockets.js";
413
+ ```
414
+
415
+ Run the installer again after upgrading the gem to copy the new client.
416
+
417
+ ### Using the client
418
+
419
+ ```js
420
+ const consumer = createConsumer("/sockets", {
421
+ token: async () => (await fetch("/sockets/token", {credentials: "same-origin"})).text(), // optional
422
+ reconnect: {minDelay: 500, maxDelay: 30_000},
423
+ logger: console, // optional; off by default
424
+ });
425
+
426
+ const subscription = consumer.subscriptions.create(
427
+ {channel: "chat", params: {room: 42}},
428
+ {
429
+ connected(data) {}, // subscribed; data is the channel's optional data
430
+ received(data) {}, // a broadcast
431
+ rejected(reason) {}, // "invalid", "unauthorized" or "internal"; the subscription is gone
432
+ disconnected() {}, // the connection dropped after this subscription was accepted
433
+ },
434
+ );
435
+
436
+ consumer.connect(); // nothing opens before this call
437
+ ```
438
+
439
+ `perform(name, data)` sends an action and returns a promise. It rejects with `not connected` until
440
+ the server has welcomed the connection, so call it from `connected` or a later user event, not
441
+ right after `connect()`:
442
+
443
+ ```js
444
+ {
445
+ async connected() {
446
+ await subscription.perform("speak", {body: "hi"});
447
+ },
448
+ }
449
+ ```
450
+
451
+ The promise resolves with the channel's `Success(data:)`, or rejects with an `Error` whose message
452
+ is the generic reason. Pending promises reject when the connection drops.
453
+
454
+ `subscription.unsubscribe()` ends one subscription. `consumer.close()` closes the connection for
455
+ good: a closed consumer never reconnects, and `connect()` does nothing; create a new consumer
456
+ instead.
457
+
458
+ The URL is a path such as `"/sockets"` (the scheme follows the page: `wss:` on `https:`) or a
459
+ `ws://` or `wss://` URL. Anything else, including `http://`, is logged and nothing connects. The URL
460
+ may also be a function, called on every connect.
461
+
462
+ The client answers `ping` with `pong`, reconnects with full-jitter backoff (reset after each
463
+ successful connection), and re-sends its subscriptions after a reconnect, except ones that were
464
+ rejected or unsubscribed. It does not reconnect after close codes 4400, 4401, 4429 or 4430, since
465
+ the next attempt would fail the same way.
466
+
467
+ ## HTTP responses
468
+
469
+ Before the upgrade, the endpoint answers:
470
+
471
+ | Status | When |
472
+ |---|---|
473
+ | 426 Upgrade Required | A plain HTTP request, not a websocket upgrade |
474
+ | 403 Forbidden | The `Origin` isn't allowed (also a `mankai.sockets.reject` event) |
475
+ | 400 Bad Request | The client didn't offer the `mankai.sockets.v1` subprotocol |
476
+ | 501 Not Implemented | The server doesn't support Rack full hijack |
477
+
478
+ ## Disconnecting people
479
+
480
+ ```ruby
481
+ Hanami.app["sockets.server"].disconnect("user:42")
482
+ ```
483
+
484
+ `disconnect` publishes a control message through the backend, and every process that receives it
485
+ closes that identity's sessions with 4401. It works from a process that serves no sockets, such as
486
+ a job worker, but only the SQL backend carries it to other processes: with `:memory` it reaches
487
+ this process only.
488
+
489
+ `max_connections_per_identity` is enforced per process; behind a load balancer each process applies
490
+ it separately.
491
+
492
+ ## Limits and close codes
493
+
494
+ The limits are the provider settings above. The server pings every `heartbeat_interval`, sends a
495
+ WebSocket ping for proxies, and closes connections it hasn't heard from in twice that interval.
496
+ Close codes and their generic reasons are listed in
497
+ [PROTOCOL.md](https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-sockets/PROTOCOL.md#close-codes).
498
+
499
+ ## Events
500
+
501
+ Events go on the app's `notifications` bus (the `notifications_key` setting). They carry ids,
502
+ names and byte counts, never tokens, params or message data:
503
+
504
+ | Event | Payload |
505
+ |---|---|
506
+ | `mankai.sockets.connect` | `session_id`, `identity_key` |
507
+ | `mankai.sockets.disconnect` | `session_id`, `identity_key`, `code` |
508
+ | `mankai.sockets.subscribe` | `session_id`, `channel`, `subscription_id` |
509
+ | `mankai.sockets.unsubscribe` | `session_id`, `subscription_id` |
510
+ | `mankai.sockets.reject` | `session_id`, `subscription_id`, `reason`; or `origin`, `reason: :origin` from the endpoint |
511
+ | `mankai.sockets.action` | `session_id`, `channel`, `subscription_id`, `action`, `outcome` (`:success`, `:failure` or `:error`) |
512
+ | `mankai.sockets.broadcast` | `stream`, `bytes` |
513
+ | `mankai.sockets.error` | `exception`, and `session_id` when it came from a connection |
514
+
515
+ The events are registered when the provider starts, so subscribe in an `after(:start)` hook:
516
+
517
+ ```ruby
518
+ # config/providers/sockets.rb
519
+ Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
520
+ configure do |config|
521
+ # ...
522
+ end
523
+
524
+ after(:start) do
525
+ target["notifications"].subscribe(:"mankai.sockets.error") do |event|
526
+ target["logger"].error(event[:exception])
527
+ end
528
+ end
529
+ end
530
+ ```
531
+
532
+ ## Testing
533
+
534
+ Channels are components, so build one with its dependencies and call `subscribe` and `receive`
535
+ directly. `RecordingBroadcaster` records broadcasts instead of sending them:
536
+
537
+ ```ruby
538
+ # spec/channels/chat_spec.rb
539
+ require "mankai/sockets/testing"
540
+
541
+ RSpec.describe Bookshelf::Channels::Chat do
542
+ include Mankai::Sockets::Testing::Channels
543
+ include Mankai::Sockets::Testing::Matchers
544
+
545
+ subject(:channel) { described_class.new(post_message: post_message) }
546
+
547
+ let(:broadcaster) { Mankai::Sockets::Testing::RecordingBroadcaster.new }
548
+ let(:post_message) { Bookshelf::Operations::PostMessage.new(broadcaster: broadcaster) }
549
+ let(:subscription) do
550
+ subscription_for(params: {room: 1}, identity: Mankai::Sockets::Identity.new(key: "user:7", value: "7"))
551
+ end
552
+
553
+ it "broadcasts what was said" do
554
+ result = channel.receive(subscription, message("speak", body: "hi"))
555
+
556
+ expect(result).to be_success
557
+ expect(broadcaster).to have_broadcast(
558
+ Mankai::Sockets::Stream.of("chat", 1), a_hash_including(body: "hi", user_id: "7")
559
+ )
560
+ end
561
+
562
+ it "fails on an empty message" do
563
+ result = channel.receive(subscription, message("speak", body: " "))
564
+
565
+ expect(result).to be_failure
566
+ expect(broadcaster.broadcasts).to be_empty
567
+ end
568
+ end
569
+ ```
570
+
571
+ - `subscription_for(params:, identity:, id:, channel:)` and `message(name, data)` build the inputs.
572
+ - `have_broadcast(stream, data = nil)` matches a recorded broadcast to that stream. `data` is a Hash
573
+ compared with `==`, or a matcher such as `a_hash_including`; leave it out to match any data.
574
+ - `assert_broadcast(broadcaster, stream, data = nil)` is the Minitest equivalent. It raises
575
+ `Minitest::Assertion` when Minitest is loaded, and `RuntimeError` otherwise.
576
+
577
+ Use the `:memory` backend in the test environment. Backend authors can use the shared examples in
578
+ `mankai/sockets/testing/backend_examples`.
579
+
580
+ ## Backends
581
+
582
+ | Backend | Reaches | Use |
583
+ |---|---|---|
584
+ | `:memory` | Connections in the same process | Development, tests, a single Puma process |
585
+ | `Mankai::Sockets::SQL.backend(...)` | Every process using the database | Several Puma workers or servers, broadcasts from jobs ([mankai-sockets-sql](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-sockets-sql)) |
586
+
587
+ The memory backend delivers synchronously, inside `publish`, on the caller's thread.
588
+
589
+ A backend is an object with these methods; `config.backend` accepts it directly, or a factory that
590
+ responds to `call(context)` and returns one:
591
+
592
+ | Method | Contract |
593
+ |---|---|
594
+ | `publish(stream_name, payload)` | Store or send the JSON String `payload`; return an Integer id. Must work before `start` |
595
+ | `subscribe(stream_name, listener)` | Call `listener.call(broadcast)` for each message on that stream |
596
+ | `unsubscribe(stream_name, listener)` | Stop calling that listener |
597
+ | `start` | Start threads or connections; called with the first websocket in each process |
598
+ | `stop` | Stop them; called when the provider stops |
599
+
600
+ A `broadcast` is a `Mankai::Sockets::Broadcast` with `stream`, `id` and `payload`. Listeners must
601
+ not block, because they run on the backend's thread. The factory's `context` is a
602
+ `Mankai::Sockets::Context` with `container`, `instrumenter`, `logger`, `clock` and
603
+ `executor_threads`.
604
+
605
+ ## Running sockets in a separate process
606
+
607
+ Sockets run inside your web process by default. To move them to their own process, start a second
608
+ Puma with the same `config.ru` and route `/sockets` to it at your proxy. It runs the whole
609
+ middleware stack, so session authentication keeps working.
610
+
611
+ If you authenticate with tokens only, the second process can serve the endpoint alone:
612
+
613
+ ```ruby
614
+ # sockets.ru
615
+ require "hanami/boot"
616
+
617
+ run Hanami.app["sockets.endpoint"]
618
+ ```
619
+
620
+ ```bash
621
+ bundle exec puma sockets.ru -p 2301
622
+ ```
623
+
624
+ This file skips the app's middleware, so `request.session` is empty there. With either setup,
625
+ broadcasts from the web process and from jobs reach the sockets process only through the SQL
626
+ backend.
627
+
628
+ ## Requirements
629
+
630
+ Puma (or another server with Rack full hijack), Rack 3 and Ruby 3.3+.