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
@@ -0,0 +1,244 @@
1
+ // Dependency-free browser client for mankai-sockets. See PROTOCOL.md for the wire contract.
2
+
3
+ const PROTOCOL = "mankai.sockets.v1";
4
+ // Reconnecting would fail the same way: an invalid frame, failed authentication, too many
5
+ // subscriptions (re-sent on every reconnect) or too many connections.
6
+ const NO_RECONNECT = [4400, 4401, 4429, 4430];
7
+
8
+ function buildUrl(url) {
9
+ const value = typeof url === "function" ? url() : url;
10
+ if (typeof value !== "string" || value.length === 0) {
11
+ throw new Error("socket url must be a non-empty string or a function returning one");
12
+ }
13
+ if (value.startsWith("ws://") || value.startsWith("wss://")) return value;
14
+ if (value.startsWith("/") && typeof location !== "undefined") {
15
+ const scheme = location.protocol === "https:" ? "wss:" : "ws:";
16
+ return `${scheme}//${location.host}${value}`;
17
+ }
18
+ throw new Error("socket url must be a path or a ws:// or wss:// URL");
19
+ }
20
+
21
+ function delayFor(attempt, minDelay, maxDelay) {
22
+ const ceiling = Math.min(maxDelay, minDelay * 2 ** attempt);
23
+ return Math.random() * ceiling;
24
+ }
25
+
26
+ export function createConsumer(url, options = {}) {
27
+ const reconnect = {minDelay: 500, maxDelay: 30_000, ...(options.reconnect || {})};
28
+ const logger = options.logger || null;
29
+ const SocketImpl = options.WebSocket || (typeof WebSocket !== "undefined" ? WebSocket : null);
30
+
31
+ let socket = null;
32
+ let welcomeReceived = false;
33
+ let stopped = false;
34
+ let connecting = false;
35
+ let attempts = 0;
36
+ let subscriptionNumber = 0;
37
+ let refNumber = 0;
38
+ const subscriptions = [];
39
+ const pending = new Map();
40
+
41
+ function log(level, message) {
42
+ if (logger && typeof logger[level] === "function") logger[level](`[mankai-sockets] ${message}`);
43
+ }
44
+
45
+ function send(frame) {
46
+ if (!socket || socket.readyState !== 1) return false;
47
+ socket.send(JSON.stringify(frame));
48
+ return true;
49
+ }
50
+
51
+ function settlePending(reason) {
52
+ for (const {reject} of pending.values()) reject(new Error(reason));
53
+ pending.clear();
54
+ }
55
+
56
+ function rejectSubscription(subscription, reason) {
57
+ const index = subscriptions.indexOf(subscription);
58
+ if (index !== -1) subscriptions.splice(index, 1);
59
+ subscription.active = false;
60
+ if (typeof subscription.callbacks.rejected === "function") {
61
+ subscription.callbacks.rejected(reason);
62
+ }
63
+ }
64
+
65
+ function handle(frame) {
66
+ switch (frame.type) {
67
+ case "welcome":
68
+ welcomeReceived = true;
69
+ attempts = 0;
70
+ for (const subscription of subscriptions.slice()) {
71
+ send({type: "subscribe", id: subscription.id, channel: subscription.params.channel,
72
+ params: subscription.params.params || {}});
73
+ }
74
+ break;
75
+ case "subscribed": {
76
+ const subscription = subscriptions.find((item) => item.id === frame.id);
77
+ if (!subscription) break;
78
+ subscription.active = true;
79
+ if (typeof subscription.callbacks.connected === "function") {
80
+ subscription.callbacks.connected(frame.data);
81
+ }
82
+ break;
83
+ }
84
+ case "rejected": {
85
+ const subscription = subscriptions.find((item) => item.id === frame.id);
86
+ if (subscription) rejectSubscription(subscription, frame.reason);
87
+ break;
88
+ }
89
+ case "message": {
90
+ const subscription = subscriptions.find((item) => item.id === frame.id);
91
+ if (!subscription) break;
92
+ subscription.lastStreamId = frame.stream_id;
93
+ if (typeof subscription.callbacks.received === "function") {
94
+ subscription.callbacks.received(frame.data);
95
+ }
96
+ break;
97
+ }
98
+ case "ack": {
99
+ const entry = pending.get(frame.ref);
100
+ if (entry) {
101
+ pending.delete(frame.ref);
102
+ entry.resolve(frame.data);
103
+ }
104
+ break;
105
+ }
106
+ case "error": {
107
+ const entry = pending.get(frame.ref);
108
+ if (entry) {
109
+ pending.delete(frame.ref);
110
+ entry.reject(new Error(frame.reason || "error"));
111
+ }
112
+ break;
113
+ }
114
+ case "ping":
115
+ send({type: "pong"});
116
+ break;
117
+ case "pong":
118
+ break;
119
+ default:
120
+ log("warn", `unknown frame type ${String(frame.type)}`);
121
+ }
122
+ }
123
+
124
+ function onClose(event) {
125
+ welcomeReceived = false;
126
+ connecting = false;
127
+ socket = null;
128
+ settlePending("not connected");
129
+ // Only subscriptions the server accepted hear about the disconnect; rejected and
130
+ // unsubscribed ones are gone.
131
+ for (const subscription of subscriptions.slice()) {
132
+ if (!subscription.active) continue;
133
+ subscription.active = false;
134
+ if (typeof subscription.callbacks.disconnected === "function") {
135
+ subscription.callbacks.disconnected();
136
+ }
137
+ }
138
+ if (event && typeof event.code === "number") log("info", `closed (${event.code})`);
139
+ const code = event && event.code;
140
+ if (stopped || NO_RECONNECT.includes(code)) return;
141
+
142
+ const wait = delayFor(attempts, reconnect.minDelay, reconnect.maxDelay);
143
+ attempts += 1;
144
+ log("info", `reconnecting in ${Math.round(wait)}ms`);
145
+ setTimeout(() => {
146
+ if (!stopped) connect();
147
+ }, wait);
148
+ }
149
+
150
+ async function tokenFor() {
151
+ if (options.token === undefined || options.token === null) return null;
152
+ const value = typeof options.token === "function" ? await options.token() : options.token;
153
+ if (typeof value !== "string") throw new Error("token must be a string");
154
+ return value;
155
+ }
156
+
157
+ async function onOpen(current) {
158
+ try {
159
+ const token = await tokenFor();
160
+ if (socket !== current || stopped) return;
161
+ const frame = {type: "hello"};
162
+ if (token) frame.token = token;
163
+ send(frame);
164
+ } catch (error) {
165
+ log("warn", "could not get a token");
166
+ if (socket === current) current.close();
167
+ }
168
+ }
169
+
170
+ function connect() {
171
+ if (stopped || connecting || (socket && (socket.readyState === 0 || socket.readyState === 1))) return;
172
+ if (!SocketImpl) throw new Error("no WebSocket implementation available; pass {WebSocket: Impl}");
173
+ let address;
174
+ try {
175
+ address = buildUrl(url);
176
+ } catch (error) {
177
+ log("error", error.message);
178
+ return;
179
+ }
180
+ connecting = true;
181
+ log("debug", `connecting to ${address}`);
182
+ const current = new SocketImpl(address, PROTOCOL);
183
+ socket = current;
184
+ current.onopen = () => onOpen(current);
185
+ current.onmessage = (event) => {
186
+ try {
187
+ handle(JSON.parse(event.data));
188
+ } catch (error) {
189
+ log("warn", "invalid frame received");
190
+ }
191
+ };
192
+ current.onclose = onClose;
193
+ current.onerror = () => log("warn", "socket error");
194
+ }
195
+
196
+ function create(subscriptionParams, callbacks = {}) {
197
+ subscriptionNumber += 1;
198
+ const subscription = {
199
+ id: `s${subscriptionNumber}`,
200
+ params: subscriptionParams || {},
201
+ callbacks,
202
+ active: false,
203
+ lastStreamId: null,
204
+ perform(name, data = {}) {
205
+ if (!welcomeReceived) return Promise.reject(new Error("not connected"));
206
+ refNumber += 1;
207
+ const ref = `r${refNumber}`;
208
+ return new Promise((resolve, reject) => {
209
+ pending.set(ref, {resolve, reject});
210
+ const sent = send({type: "action", id: this.id, name, data, ref});
211
+ if (!sent) {
212
+ pending.delete(ref);
213
+ reject(new Error("not connected"));
214
+ }
215
+ });
216
+ },
217
+ unsubscribe() {
218
+ const index = subscriptions.indexOf(this);
219
+ if (index !== -1) subscriptions.splice(index, 1);
220
+ this.active = false;
221
+ if (welcomeReceived) send({type: "unsubscribe", id: this.id});
222
+ },
223
+ };
224
+ subscriptions.push(subscription);
225
+ if (welcomeReceived) {
226
+ send({type: "subscribe", id: subscription.id, channel: subscription.params.channel,
227
+ params: subscription.params.params || {}});
228
+ }
229
+ return subscription;
230
+ }
231
+
232
+ return {
233
+ connect,
234
+ close() {
235
+ stopped = true;
236
+ connecting = false;
237
+ settlePending("closed");
238
+ if (socket) socket.close(1000, "closed");
239
+ socket = null;
240
+ welcomeReceived = false;
241
+ },
242
+ subscriptions: {create},
243
+ };
244
+ }
data/js/package.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "type": "module",
3
+ "private": true
4
+ }
@@ -0,0 +1,225 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {createConsumer} from "../mankai-sockets.js";
4
+
5
+ class FakeSocket {
6
+ static instances = [];
7
+
8
+ constructor(url, protocol) {
9
+ this.url = url;
10
+ this.protocol = protocol;
11
+ this.readyState = 0;
12
+ this.sent = [];
13
+ FakeSocket.instances.push(this);
14
+ }
15
+
16
+ open() {
17
+ this.readyState = 1;
18
+ this.onopen && this.onopen();
19
+ }
20
+
21
+ send(data) {
22
+ this.sent.push(JSON.parse(data));
23
+ }
24
+
25
+ receive(frame) {
26
+ this.onmessage && this.onmessage({data: JSON.stringify(frame)});
27
+ }
28
+
29
+ close(code = 1000) {
30
+ this.readyState = 3;
31
+ this.onclose && this.onclose({code});
32
+ }
33
+
34
+ frames(type) {
35
+ return this.sent.filter((frame) => frame.type === type);
36
+ }
37
+ }
38
+
39
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
40
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
41
+
42
+ function connectedConsumer(options = {}) {
43
+ const consumer = createConsumer("ws://example.test/sockets", {WebSocket: FakeSocket, ...options});
44
+ consumer.connect();
45
+ const socket = FakeSocket.instances.at(-1);
46
+ socket.open();
47
+ return {consumer, socket};
48
+ }
49
+
50
+ test("builds ws URLs from paths and rejects other schemes", () => {
51
+ globalThis.location = {protocol: "https:", host: "example.test"};
52
+ const consumer = createConsumer("/sockets", {WebSocket: FakeSocket});
53
+ consumer.connect();
54
+ assert.equal(FakeSocket.instances.at(-1).url, "wss://example.test/sockets");
55
+ assert.equal(FakeSocket.instances.at(-1).protocol, "mankai.sockets.v1");
56
+ const bad = createConsumer("http://example.test", {WebSocket: FakeSocket});
57
+ bad.connect();
58
+ delete globalThis.location;
59
+ });
60
+
61
+ test("opens nothing before connect and ignores a second connect", () => {
62
+ const before = FakeSocket.instances.length;
63
+ const consumer = createConsumer("ws://example.test/sockets", {WebSocket: FakeSocket});
64
+ consumer.subscriptions.create({channel: "chat"});
65
+ assert.equal(FakeSocket.instances.length, before);
66
+ consumer.connect();
67
+ consumer.connect();
68
+ assert.equal(FakeSocket.instances.length, before + 1);
69
+ });
70
+
71
+ test("sends hello, then subscriptions after welcome", async () => {
72
+ const {consumer, socket} = connectedConsumer({token: "abc"});
73
+ await flush();
74
+ assert.deepEqual(socket.frames("hello"), [{type: "hello", token: "abc"}]);
75
+ consumer.subscriptions.create({channel: "chat", params: {room: 1}});
76
+ assert.equal(socket.frames("subscribe").length, 0);
77
+ socket.receive({type: "welcome", session_id: "s"});
78
+ assert.deepEqual(socket.frames("subscribe"), [
79
+ {type: "subscribe", id: "s1", channel: "chat", params: {room: 1}},
80
+ ]);
81
+ });
82
+
83
+ test("calls a token function on every connect", async () => {
84
+ let calls = 0;
85
+ const {consumer, socket} = connectedConsumer({token: () => `t${++calls}`, reconnect: {minDelay: 1, maxDelay: 2}});
86
+ await flush();
87
+ assert.deepEqual(socket.frames("hello"), [{type: "hello", token: "t1"}]);
88
+ socket.close(3000);
89
+ await wait(30);
90
+ const next = FakeSocket.instances.at(-1);
91
+ next.open();
92
+ await flush();
93
+ assert.equal(next.frames("hello")[0].token, "t2");
94
+ consumer.close();
95
+ });
96
+
97
+ test("resolves perform on ack and rejects on error", async () => {
98
+ const {consumer, socket} = connectedConsumer();
99
+ await flush();
100
+ socket.receive({type: "welcome"});
101
+ const subscription = consumer.subscriptions.create({channel: "chat"});
102
+ const promise = subscription.perform("speak", {body: "hi"});
103
+ assert.equal(socket.frames("action")[0].name, "speak");
104
+ socket.receive({type: "ack", ref: "r1"});
105
+ assert.equal(await promise, undefined);
106
+ const failing = subscription.perform("speak", {});
107
+ socket.receive({type: "error", ref: "r2", reason: "unauthorized"});
108
+ await assert.rejects(failing, /unauthorized/);
109
+ });
110
+
111
+ test("hands callbacks data and tracks the last stream", async () => {
112
+ const {consumer, socket} = connectedConsumer();
113
+ await flush();
114
+ socket.receive({type: "welcome"});
115
+ const seen = [];
116
+ const subscription = consumer.subscriptions.create({channel: "chat"}, {
117
+ connected: (data) => seen.push(["connected", data]),
118
+ received: (data) => seen.push(["received", data]),
119
+ rejected: (reason) => seen.push(["rejected", reason]),
120
+ disconnected: () => seen.push(["disconnected"]),
121
+ });
122
+ socket.receive({type: "subscribed", id: "s1", data: {room: 1}});
123
+ socket.receive({type: "message", id: "s1", stream_id: "chat:1", data: {body: "hi"}});
124
+ assert.equal(subscription.lastStreamId, "chat:1");
125
+ assert.deepEqual(seen, [["connected", {room: 1}], ["received", {body: "hi"}]]);
126
+ socket.receive({type: "rejected", id: "s1", reason: "invalid"});
127
+ assert.deepEqual(seen.at(-1), ["rejected", "invalid"]);
128
+ socket.receive({type: "message", id: "s1", stream_id: "chat:1", data: {body: "ignored"}});
129
+ assert.equal(seen.length, 3);
130
+ socket.close(1001);
131
+ assert.equal(seen.length, 3, "a rejected subscription does not hear about the disconnect");
132
+ consumer.close();
133
+ });
134
+
135
+ test("answers ping with pong and does not log secrets", async () => {
136
+ const lines = [];
137
+ const logger = {debug: (m) => lines.push(m), info: (m) => lines.push(m), warn: (m) => lines.push(m)};
138
+ const {socket} = connectedConsumer({token: "secret-token", logger});
139
+ await flush();
140
+ socket.receive({type: "ping"});
141
+ assert.deepEqual(socket.frames("pong"), [{type: "pong"}]);
142
+ assert.ok(lines.length > 0);
143
+ assert.ok(lines.every((line) => !line.includes("secret")));
144
+ });
145
+
146
+ test("does not reconnect after a fatal code or close", async () => {
147
+ const {socket} = connectedConsumer({reconnect: {minDelay: 1, maxDelay: 2}});
148
+ const count = FakeSocket.instances.length;
149
+ socket.close(4401);
150
+ await wait(20);
151
+ assert.equal(FakeSocket.instances.length, count);
152
+ const other = connectedConsumer({reconnect: {minDelay: 1, maxDelay: 2}});
153
+ const before = FakeSocket.instances.length;
154
+ other.consumer.close();
155
+ other.socket.close(1000);
156
+ await wait(20);
157
+ assert.equal(FakeSocket.instances.length, before);
158
+ });
159
+
160
+ test("unsubscribes and rejects pending performs on close", async () => {
161
+ const {consumer, socket} = connectedConsumer();
162
+ await flush();
163
+ socket.receive({type: "welcome"});
164
+ const first = consumer.subscriptions.create({channel: "chat"});
165
+ const second = consumer.subscriptions.create({channel: "chat"});
166
+ first.unsubscribe();
167
+ assert.deepEqual(socket.frames("unsubscribe"), [{type: "unsubscribe", id: "s1"}]);
168
+ const pending = second.perform("speak", {});
169
+ consumer.close();
170
+ await assert.rejects(pending, /closed/);
171
+ await assert.rejects(consumer.subscriptions.create({channel: "chat"}).perform("speak", {}), /not connected/);
172
+ });
173
+
174
+ test("calls disconnected only for subscriptions the server accepted", async () => {
175
+ const {consumer, socket} = connectedConsumer({reconnect: {minDelay: 1, maxDelay: 2}});
176
+ await flush();
177
+ socket.receive({type: "welcome"});
178
+ const seen = [];
179
+ const callbacks = (name) => ({
180
+ disconnected: () => seen.push(name),
181
+ });
182
+ consumer.subscriptions.create({channel: "chat"}, callbacks("accepted"));
183
+ consumer.subscriptions.create({channel: "chat"}, callbacks("rejected"));
184
+ const left = consumer.subscriptions.create({channel: "chat"}, callbacks("unsubscribed"));
185
+ consumer.subscriptions.create({channel: "chat"}, callbacks("pending"));
186
+ socket.receive({type: "subscribed", id: "s1"});
187
+ socket.receive({type: "rejected", id: "s2", reason: "invalid"});
188
+ socket.receive({type: "subscribed", id: "s3"});
189
+ left.unsubscribe();
190
+ socket.close(1001);
191
+ assert.deepEqual(seen, ["accepted"]);
192
+ consumer.close();
193
+ });
194
+
195
+ test("resets the reconnect backoff after a successful connection", async (t) => {
196
+ t.mock.method(Math, "random", () => 1);
197
+ const lines = [];
198
+ const logger = {info: (m) => lines.push(m), debug: () => {}, warn: () => {}};
199
+ const delays = () => lines.filter((line) => line.includes("reconnecting")).map((line) => Number(line.match(/(\d+)ms/)[1]));
200
+ const consumer = createConsumer("ws://example.test/sockets", {
201
+ WebSocket: FakeSocket, logger, reconnect: {minDelay: 5, maxDelay: 1000},
202
+ });
203
+ consumer.connect();
204
+ for (let i = 0; i < 3; i += 1) {
205
+ FakeSocket.instances.at(-1).close(3000);
206
+ await wait(delays().at(-1) + 15);
207
+ }
208
+ assert.deepEqual(delays(), [5, 10, 20]);
209
+ const socket = FakeSocket.instances.at(-1);
210
+ socket.open();
211
+ await flush();
212
+ socket.receive({type: "welcome"});
213
+ socket.close(3000);
214
+ assert.equal(delays().at(-1), 5);
215
+ consumer.close();
216
+ });
217
+
218
+ test("does not reconnect after too many subscriptions (4429)", async () => {
219
+ const {consumer, socket} = connectedConsumer({reconnect: {minDelay: 1, maxDelay: 2}});
220
+ const count = FakeSocket.instances.length;
221
+ socket.close(4429);
222
+ await wait(20);
223
+ assert.equal(FakeSocket.instances.length, count);
224
+ consumer.close();
225
+ });
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # Turns a handshake and an optional token into an Identity. Authentication happens once,
8
+ # on `hello`, on an executor thread; the app's authenticator may use the request's cookies
9
+ # and session.
10
+ #
11
+ # @api private
12
+ # @since 0.1.0
13
+ class Authentication
14
+ include Dry::Monads[:result]
15
+
16
+ # @param authenticator [#call, nil] called with (request, token_subject); nil only with
17
+ # allow_anonymous
18
+ # @param tokens [Tokens, nil] nil when no token_secret is configured
19
+ # @param allow_anonymous [Boolean]
20
+ #
21
+ # @api private
22
+ # @since 0.1.0
23
+ def initialize(authenticator:, tokens:, allow_anonymous:)
24
+ @authenticator = authenticator
25
+ @tokens = tokens
26
+ @allow_anonymous = allow_anonymous
27
+ end
28
+
29
+ # @param request [Rack::Request] the upgrade request
30
+ # @param token [String, nil] the token from `hello`
31
+ # @param session_id [String] used to name anonymous identities
32
+ # @yield [exception] called with an authenticator exception, if any
33
+ # @return [Dry::Monads::Result] Success(Identity) or Failure(CloseCode)
34
+ #
35
+ # @api private
36
+ # @since 0.1.0
37
+ def call(request, token, session_id)
38
+ subject = token_subject(token)
39
+ return Failure(CloseCode::UNAUTHORIZED) if token && !subject
40
+
41
+ identity = begin
42
+ @authenticator&.call(request, subject)
43
+ rescue StandardError => exception
44
+ yield exception if block_given?
45
+ return Failure(CloseCode::UNAUTHORIZED)
46
+ end
47
+ identity ? Success(identity) : anonymous(session_id)
48
+ end
49
+
50
+ private
51
+
52
+ # @api private
53
+ # @since 0.1.0
54
+ def anonymous(session_id)
55
+ return Failure(CloseCode::UNAUTHORIZED) unless @allow_anonymous
56
+
57
+ Success(Identity.new(key: "anonymous:#{session_id}", value: nil))
58
+ end
59
+
60
+ # @api private
61
+ # @since 0.1.0
62
+ def token_subject(token)
63
+ return nil unless token
64
+
65
+ return nil unless @tokens
66
+
67
+ result = @tokens.verify(token)
68
+ result.success? ? result.value! : nil
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ module Backends
8
+ # An in-process backend for development and tests. Broadcasts reach every listener in this
9
+ # process only. The contract is documented here and checked by the shared backend examples.
10
+ #
11
+ # Backends implement: publish(stream_name, payload) -> Integer, subscribe(stream_name,
12
+ # listener), unsubscribe(stream_name, listener), start, stop. Listeners must not block.
13
+ #
14
+ # @api public
15
+ # @since 0.1.0
16
+ class Memory
17
+ # @api private
18
+ # @since 0.1.0
19
+ def initialize
20
+ @mutex = Mutex.new
21
+ @last_id = 0
22
+ @listeners = {}
23
+ end
24
+
25
+ # @api public
26
+ # @since 0.1.0
27
+ def publish(stream_name, payload)
28
+ # Listeners run outside the lock: the hub takes its own lock to deliver, and also calls
29
+ # #subscribe while holding it, so holding ours here could deadlock.
30
+ id, listeners = @mutex.synchronize do
31
+ @last_id += 1
32
+ [@last_id, @listeners.fetch(stream_name, {}).keys]
33
+ end
34
+ message = Broadcast.new(stream: stream_name, id: id, payload: payload)
35
+ listeners.each { |listener| listener.call(message) }
36
+ id
37
+ end
38
+
39
+ # @api public
40
+ # @since 0.1.0
41
+ def subscribe(stream_name, listener)
42
+ @mutex.synchronize { (@listeners[stream_name] ||= {})[listener] = true }
43
+ end
44
+
45
+ # @api public
46
+ # @since 0.1.0
47
+ def unsubscribe(stream_name, listener)
48
+ @mutex.synchronize do
49
+ listeners = @listeners[stream_name]
50
+ return unless listeners
51
+
52
+ listeners.delete(listener)
53
+ @listeners.delete(stream_name) if listeners.empty?
54
+ end
55
+ end
56
+
57
+ # @api public
58
+ # @since 0.1.0
59
+ def start
60
+ end
61
+
62
+ # @api public
63
+ # @since 0.1.0
64
+ def stop
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # What a backend delivers to the hub: a stream name, a monotonic id and the payload as JSON.
6
+ #
7
+ # @api public
8
+ # @since 0.1.0
9
+ Broadcast = Data.define(:stream, :id, :payload) do
10
+ # @api public
11
+ # @since 0.1.0
12
+ def initialize(stream:, id:, payload:)
13
+ raise ArgumentError, "broadcast stream must be a non-empty String" unless stream.is_a?(String) && !stream.empty?
14
+ raise ArgumentError, "broadcast id must be an Integer" unless id.is_a?(Integer)
15
+ raise ArgumentError, "broadcast payload must be a String" unless payload.is_a?(String)
16
+
17
+ super
18
+ freeze
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "dry/monads"
5
+
6
+ module Mankai
7
+ module Sockets
8
+ # The component apps call to publish a broadcast. The stream must be a Stream, not a raw
9
+ # string, so reserved names cannot be published by accident.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ class Broadcaster
14
+ include Dry::Monads[:result]
15
+
16
+ # @api private
17
+ # @since 0.1.0
18
+ def initialize(backend:, max_payload_size:, instrumenter:)
19
+ @backend = backend
20
+ @max_payload_size = max_payload_size
21
+ @instrumenter = instrumenter
22
+ end
23
+
24
+ # @param stream [Stream]
25
+ # @param data [Hash] JSON-serializable payload
26
+ # @return [Dry::Monads::Result] Success(message id) or Failure(:too_large)
27
+ #
28
+ # @api public
29
+ # @since 0.1.0
30
+ def call(stream, data)
31
+ raise ArgumentError, "stream must be a Stream" unless stream.is_a?(Stream)
32
+ raise ArgumentError, "broadcast data must be a Hash" unless data.is_a?(Hash)
33
+
34
+ payload = JSON.generate(data)
35
+ return Failure(:too_large) if payload.bytesize > @max_payload_size
36
+
37
+ id = @backend.publish(stream.name, payload)
38
+ @instrumenter.instrument(:broadcast, stream: stream.name, bytes: payload.bytesize)
39
+ Success(id)
40
+ end
41
+ end
42
+ end
43
+ end