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,186 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "dry/monads"
5
+ require "dry/schema"
6
+
7
+ module Mankai
8
+ module Sockets
9
+ # Decodes inbound frames and encodes outbound ones. Pure functions: no state, no app code.
10
+ #
11
+ # @api private
12
+ # @since 0.1.0
13
+ module Protocol
14
+ # @api private
15
+ # @since 0.1.0
16
+ SUBPROTOCOL = "mankai.sockets.v1"
17
+
18
+ # @api private
19
+ # @since 0.1.0
20
+ SCHEMAS = {
21
+ "hello" => [
22
+ Dry::Schema.Params do
23
+ optional(:token).filled(:string)
24
+ end,
25
+ Frames::Hello
26
+ ],
27
+ "subscribe" => [
28
+ Dry::Schema.Params do
29
+ required(:id).filled(:string)
30
+ required(:channel).filled(:string)
31
+ optional(:params).value(:hash)
32
+ end,
33
+ Frames::Subscribe
34
+ ],
35
+ "unsubscribe" => [
36
+ Dry::Schema.Params do
37
+ required(:id).filled(:string)
38
+ end,
39
+ Frames::Unsubscribe
40
+ ],
41
+ "action" => [
42
+ Dry::Schema.Params do
43
+ required(:id).filled(:string)
44
+ required(:name).filled(:string)
45
+ optional(:data).value(:hash)
46
+ optional(:ref).filled(:string)
47
+ end,
48
+ Frames::Action
49
+ ],
50
+ "ping" => [Dry::Schema.Params {}, Frames::Ping],
51
+ "pong" => [Dry::Schema.Params {}, Frames::Pong]
52
+ }.freeze
53
+
54
+ # Extra keys are rejected explicitly: dry-schema's key validation would also reject the
55
+ # arbitrary keys an app puts in `params` and `data`.
56
+ #
57
+ # @api private
58
+ # @since 0.1.0
59
+ ALLOWED_KEYS = {
60
+ "hello" => %w[type token],
61
+ "subscribe" => %w[type id channel params],
62
+ "unsubscribe" => %w[type id],
63
+ "action" => %w[type id name data ref],
64
+ "ping" => %w[type],
65
+ "pong" => %w[type]
66
+ }.transform_values(&:freeze).freeze
67
+
68
+ # @api private
69
+ # @since 0.1.0
70
+ HASH_FIELDS = %i[params data].freeze
71
+
72
+ # @api private
73
+ # @since 0.1.0
74
+ OUTBOUND = %w[welcome subscribed rejected message ack error ping pong].freeze
75
+
76
+ module_function
77
+
78
+ # @param text [String] one inbound frame
79
+ # @return [Dry::Monads::Result] Success(frame) or failure(CloseCode::INVALID_FRAME)
80
+ #
81
+ # @api private
82
+ # @since 0.1.0
83
+ def decode(text)
84
+ parsed = parse(text)
85
+ return failure(CloseCode::INVALID_FRAME) unless parsed
86
+
87
+ type = parsed["type"]
88
+ schemas = SCHEMAS[type]
89
+ return failure(CloseCode::INVALID_FRAME) unless schemas && allowed_keys?(type, parsed)
90
+
91
+ attributes, hashes = attributes_for(parsed)
92
+ result = schemas[0].call(attributes)
93
+ return failure(CloseCode::INVALID_FRAME) if result.failure?
94
+
95
+ success(schemas[1].new(**result.to_h, **hashes))
96
+ rescue ArgumentError
97
+ failure(CloseCode::INVALID_FRAME)
98
+ end
99
+
100
+ # @api private
101
+ # @since 0.1.0
102
+ def self.parse(text)
103
+ return nil unless text.is_a?(String) && text.valid_encoding?
104
+
105
+ parsed = JSON.parse(text)
106
+ parsed if parsed.is_a?(Hash)
107
+ rescue JSON::ParserError
108
+ nil
109
+ end
110
+ class << self
111
+ private :parse
112
+ end
113
+
114
+ # @api private
115
+ # @since 0.1.0
116
+ def self.allowed_keys?(type, parsed)
117
+ (parsed.keys - ALLOWED_KEYS.fetch(type)).empty?
118
+ end
119
+ class << self
120
+ private :allowed_keys?
121
+ end
122
+
123
+ # Params and data may hold any keys the app wants, so they are symbolized here instead of
124
+ # going through dry-schema's key validation.
125
+ #
126
+ # @api private
127
+ # @since 0.1.0
128
+ def self.attributes_for(parsed)
129
+ attributes = parsed.except("type")
130
+ hashes = {}
131
+ HASH_FIELDS.each do |field|
132
+ value = attributes.delete(field.to_s)
133
+ raise ArgumentError, "#{field} must be an object" if value && !value.is_a?(Hash)
134
+
135
+ hashes[field] = value.transform_keys(&:to_sym) if value
136
+ end
137
+ [attributes, hashes]
138
+ end
139
+ class << self
140
+ private :attributes_for
141
+ end
142
+
143
+ # @param type [String] an outbound frame type
144
+ # @return [String] JSON
145
+ # @raise [ArgumentError] for an unknown outbound type (a programming error)
146
+ #
147
+ # @api private
148
+ # @since 0.1.0
149
+ def encode(type, **fields)
150
+ raise ArgumentError, "unknown outbound frame type #{type.inspect}" unless OUTBOUND.include?(type)
151
+
152
+ JSON.generate({type: type}.merge(fields))
153
+ end
154
+
155
+ # Builds a message frame by splicing the broadcast's JSON payload after `"data":`, so a
156
+ # broadcast to 1,000 subscribers is generated once rather than parsed and regenerated.
157
+ #
158
+ # @return [String] JSON
159
+ #
160
+ # @api private
161
+ # @since 0.1.0
162
+ def encode_message(id:, stream_id:, payload:)
163
+ head = JSON.generate({type: "message", id: id, stream_id: stream_id})
164
+ "#{head.delete_suffix("}")},\"data\":#{payload}}"
165
+ end
166
+
167
+ # @api private
168
+ # @since 0.1.0
169
+ def self.failure(code)
170
+ Dry::Monads::Result::Failure.new(code)
171
+ end
172
+ class << self
173
+ private :failure
174
+ end
175
+
176
+ # @api private
177
+ # @since 0.1.0
178
+ def self.success(value)
179
+ Dry::Monads::Result::Success.new(value)
180
+ end
181
+ class << self
182
+ private :success
183
+ end
184
+ end
185
+ end
186
+ end
@@ -0,0 +1,224 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/system"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # dry-system provider source that registers the socket components. In a Hanami app:
8
+ #
9
+ # # config/providers/sockets.rb
10
+ # require "mankai/sockets"
11
+ #
12
+ # Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
13
+ # configure do |config|
14
+ # config.backend = :memory
15
+ # config.authenticator = lambda do |request, _token_subject|
16
+ # user_id = request.session[:user_id]
17
+ # user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
18
+ # end
19
+ # config.allowed_origins = :same_origin
20
+ # config.channels = {"chat" => "channels.chat"}
21
+ # end
22
+ # end
23
+ #
24
+ # `start` only builds objects: threads and connections start on the first socket.
25
+ #
26
+ # @api public
27
+ # @since 0.1.0
28
+ class ProviderSource < Dry::System::Provider::Source
29
+ # @api public
30
+ # @since 0.1.0
31
+ setting :backend, default: :memory
32
+
33
+ # @api public
34
+ # @since 0.1.0
35
+ setting :authenticator
36
+
37
+ # @api public
38
+ # @since 0.1.0
39
+ setting :allow_anonymous, default: false
40
+
41
+ # @api public
42
+ # @since 0.1.0
43
+ setting :allowed_origins
44
+
45
+ # @api public
46
+ # @since 0.1.0
47
+ setting :token_secret
48
+
49
+ # @api public
50
+ # @since 0.1.0
51
+ setting :channels, default: {}
52
+
53
+ # @api public
54
+ # @since 0.1.0
55
+ setting :max_frame_size, default: 65_536
56
+ # @api public
57
+ # @since 0.1.0
58
+ setting :max_payload_size, default: 60_000
59
+ # @api public
60
+ # @since 0.1.0
61
+ setting :max_subscriptions, default: 100
62
+ # @api public
63
+ # @since 0.1.0
64
+ setting :max_buffered_bytes, default: 1_048_576
65
+ # @api public
66
+ # @since 0.1.0
67
+ setting :max_connections_per_identity, default: 20
68
+ # @api public
69
+ # @since 0.1.0
70
+ setting :hello_timeout, default: 10
71
+ # @api public
72
+ # @since 0.1.0
73
+ setting :heartbeat_interval, default: 15
74
+ # @api public
75
+ # @since 0.1.0
76
+ setting :executor_threads, default: 4
77
+
78
+ # @api public
79
+ # @since 0.1.0
80
+ setting :logger_key, default: "logger"
81
+ # @api public
82
+ # @since 0.1.0
83
+ setting :notifications_key, default: "notifications"
84
+ # @api public
85
+ # @since 0.1.0
86
+ setting :clock, default: -> { Time.now.utc }
87
+
88
+ # @api private
89
+ # @since 0.1.0
90
+ def start
91
+ validate!
92
+ instrumenter = build_instrumenter
93
+ tokens = build_tokens
94
+ backend = build_backend(instrumenter)
95
+ server = build_server(instrumenter, tokens, backend)
96
+ endpoint = Endpoint.new(
97
+ server: server, origin_policy: OriginPolicy.new(config.allowed_origins), instrumenter: instrumenter
98
+ )
99
+
100
+ @server = server
101
+ register "endpoint", endpoint
102
+ register "server", server
103
+ register "broadcaster", Broadcaster.new(
104
+ backend: backend, max_payload_size: config.max_payload_size, instrumenter: instrumenter
105
+ )
106
+ register "backend", backend
107
+ register "channels", server_channels
108
+ register "tokens", tokens if tokens
109
+ end
110
+
111
+ # @api private
112
+ # @since 0.1.0
113
+ def stop
114
+ @server&.stop
115
+ end
116
+
117
+ private
118
+
119
+ # @api private
120
+ # @since 0.1.0
121
+ def build_server(instrumenter, tokens, backend)
122
+ Server.new(
123
+ backend: backend,
124
+ session_dependencies: SessionDependencies.new(
125
+ authentication: Authentication.new(
126
+ authenticator: config.authenticator,
127
+ tokens: tokens,
128
+ allow_anonymous: config.allow_anonymous
129
+ ),
130
+ channels: server_channels
131
+ ),
132
+ limits: build_limits,
133
+ executor_threads: config.executor_threads,
134
+ logger: component(config.logger_key),
135
+ instrumenter: instrumenter,
136
+ clock: config.clock
137
+ )
138
+ end
139
+
140
+ # @api private
141
+ # @since 0.1.0
142
+ def server_channels
143
+ @server_channels ||= ChannelMap.new(config.channels, container: target)
144
+ end
145
+
146
+ # @api private
147
+ # @since 0.1.0
148
+ def validate!
149
+ if config.allowed_origins.nil?
150
+ raise ConfigurationError,
151
+ "config.allowed_origins is required: use :same_origin or an Array of origin patterns"
152
+ end
153
+ if config.authenticator.nil? && !config.allow_anonymous
154
+ raise ConfigurationError,
155
+ "config.authenticator is required unless config.allow_anonymous is true"
156
+ end
157
+ raise ConfigurationError, "config.channels is required and cannot be empty" if config.channels.empty?
158
+
159
+ return unless config.token_secret && config.token_secret.bytesize < Tokens::MIN_SECRET_BYTES
160
+
161
+ raise ConfigurationError,
162
+ "config.token_secret must be at least #{Tokens::MIN_SECRET_BYTES} bytes"
163
+ end
164
+
165
+ # @api private
166
+ # @since 0.1.0
167
+ def component(key)
168
+ target[key] if target.key?(key)
169
+ end
170
+
171
+ # @api private
172
+ # @since 0.1.0
173
+ def build_instrumenter
174
+ Instrumenter.new(component(config.notifications_key))
175
+ end
176
+
177
+ # @api private
178
+ # @since 0.1.0
179
+ def build_tokens
180
+ return nil unless config.token_secret
181
+
182
+ Tokens.new(secret: config.token_secret, clock: config.clock)
183
+ end
184
+
185
+ # @api private
186
+ # @since 0.1.0
187
+ def build_limits
188
+ Limits.new(
189
+ max_frame_size: config.max_frame_size,
190
+ max_payload_size: config.max_payload_size,
191
+ max_subscriptions: config.max_subscriptions,
192
+ max_buffered_bytes: config.max_buffered_bytes,
193
+ max_connections_per_identity: config.max_connections_per_identity,
194
+ hello_timeout: config.hello_timeout,
195
+ heartbeat_interval: config.heartbeat_interval
196
+ )
197
+ end
198
+
199
+ # @api private
200
+ # @since 0.1.0
201
+ def build_backend(instrumenter)
202
+ return Backends::Memory.new if config.backend == :memory
203
+ return config.backend if config.backend.respond_to?(:publish)
204
+ return config.backend.call(context(instrumenter)) if config.backend.respond_to?(:call)
205
+
206
+ raise ConfigurationError,
207
+ "config.backend must be :memory, a backend object, or a factory such as " \
208
+ "Mankai::Sockets::SQL.backend(...)"
209
+ end
210
+
211
+ # @api private
212
+ # @since 0.1.0
213
+ def context(instrumenter)
214
+ Context.new(
215
+ container: target,
216
+ instrumenter: instrumenter,
217
+ logger: component(config.logger_key),
218
+ clock: config.clock,
219
+ executor_threads: config.executor_threads
220
+ )
221
+ end
222
+ end
223
+ end
224
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # Owns the process's sessions, hub, executor and reactor. Nothing is started until the first
8
+ # connection is adopted, and everything is rebuilt after a fork.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ class Server
13
+ # @api private
14
+ # @since 0.1.0
15
+ SHUTDOWN_TIMEOUT = 5
16
+
17
+ # @api private
18
+ # @since 0.1.0
19
+ def initialize(backend:, session_dependencies:, limits:, executor_threads:, logger:,
20
+ instrumenter:, clock:)
21
+ @backend = backend
22
+ @session_dependencies = session_dependencies
23
+ @limits = limits
24
+ @executor_threads = executor_threads
25
+ @logger = logger
26
+ @instrumenter = instrumenter
27
+ @clock = clock
28
+ @pid = nil
29
+ @mutex = Mutex.new
30
+ end
31
+
32
+ # @api private
33
+ # @since 0.1.0
34
+ def adopt(io, env)
35
+ ensure_started
36
+ @session_factory.call(io, env)
37
+ end
38
+
39
+ # Publishes a control message; works before the server has started, so a job can disconnect
40
+ # someone without serving sockets itself.
41
+ #
42
+ # @api public
43
+ # @since 0.1.0
44
+ def disconnect(identity_key)
45
+ @backend.publish(Hub::CONTROL_STREAM, JSON.generate(disconnect: identity_key))
46
+ end
47
+
48
+ # @api public
49
+ # @since 0.1.0
50
+ def running?
51
+ @mutex.synchronize { !@pid.nil? && @pid == Process.pid }
52
+ end
53
+
54
+ # @api private
55
+ # @since 0.1.0
56
+ def stop
57
+ @mutex.synchronize do
58
+ return if @pid.nil? || @pid != Process.pid
59
+
60
+ @sessions.each { |session| session.close_requested(CloseCode::GOING_AWAY) }
61
+ @executor.shutdown(SHUTDOWN_TIMEOUT)
62
+ @reactor.stop
63
+ @backend.stop
64
+ @pid = nil
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ # @api private
71
+ # @since 0.1.0
72
+ def ensure_started
73
+ @mutex.synchronize do
74
+ next if @pid == Process.pid
75
+
76
+ # Objects inherited from a parent process are dropped, never stopped.
77
+ @sessions = Sessions.new
78
+ @hub = Hub.new(backend: @backend, sessions: @sessions)
79
+ @executor = Executor.new(threads: @executor_threads, on_error: ->(error) { report(error) })
80
+ @reactor = Transport::Reactor.new(
81
+ on_tick: ->(now) { @sessions.each { |session| session.clock_ticked(now) } },
82
+ clock: @clock,
83
+ on_error: ->(error) { report(error) }
84
+ )
85
+ @session_factory = SessionFactory.new(
86
+ executor: @executor, reactor: @reactor,
87
+ authentication: @session_dependencies.authentication,
88
+ channels: @session_dependencies.channels,
89
+ hub: @hub, sessions: @sessions, limits: @limits,
90
+ instrumenter: @instrumenter, clock: @clock
91
+ )
92
+ @backend.start
93
+ @hub.start
94
+ @pid = Process.pid
95
+ @logger&.info("[mankai-sockets] server started (pid #{@pid})")
96
+ end
97
+ end
98
+
99
+ # @api private
100
+ # @since 0.1.0
101
+ def report(error)
102
+ @instrumenter.instrument(:error, exception: error)
103
+ end
104
+ end
105
+ end
106
+ end