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,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+ require "dry/schema"
5
+
6
+ module Mankai
7
+ module Sockets
8
+ # Base class for app channels. A channel is a stateless container component: it checks its
9
+ # input, chooses the streams to listen on, and returns Results. Business logic belongs in an
10
+ # operation the channel calls.
11
+ #
12
+ # @api public
13
+ # @since 0.1.0
14
+ class Channel
15
+ include Dry::Monads[:result]
16
+
17
+ class << self
18
+ # Declares the schema for subscription params, once, when the class loads. Without it,
19
+ # params must be empty.
20
+ #
21
+ # @api public
22
+ # @since 0.1.0
23
+ def params(&block)
24
+ @params_schema = Dry::Schema.Params(&block)
25
+ end
26
+
27
+ # @api private
28
+ # @since 0.1.0
29
+ def params_schema
30
+ return @params_schema if instance_variable_defined?(:@params_schema) && @params_schema
31
+
32
+ superclass.respond_to?(:params_schema) ? superclass.params_schema : nil
33
+ end
34
+ end
35
+
36
+ # Called when a client subscribes. Must be overridden.
37
+ #
38
+ # @param subscription [Subscription]
39
+ # @return [Dry::Monads::Result] Success(streams: [...], data: optional Hash) or Failure(reason)
40
+ #
41
+ # @api public
42
+ # @since 0.1.0
43
+ def subscribe(subscription)
44
+ raise NotImplementedError, "#{self.class} must implement #subscribe"
45
+ end
46
+
47
+ # Called for each `action` frame. Apps dispatch on `message.name` themselves.
48
+ #
49
+ # @param subscription [Subscription]
50
+ # @param message [Message]
51
+ # @return [Dry::Monads::Result] Success() or Success(data: Hash), or Failure(reason)
52
+ #
53
+ # @api public
54
+ # @since 0.1.0
55
+ def receive(subscription, message)
56
+ Failure(:unknown_action)
57
+ end
58
+
59
+ # Called when a subscription goes away. The return value is ignored.
60
+ #
61
+ # @api public
62
+ # @since 0.1.0
63
+ def unsubscribe(subscription)
64
+ end
65
+
66
+ # Validates params against the declared schema (or requires an empty Hash).
67
+ #
68
+ # @return [Dry::Monads::Result] Success(symbol-keyed Hash) or Failure(:invalid_params)
69
+ #
70
+ # @api private
71
+ # @since 0.1.0
72
+ def validate_params(hash)
73
+ schema = self.class.params_schema
74
+ return Failure(:invalid_params) if !schema && !hash.empty?
75
+ return Success(hash) unless schema
76
+
77
+ result = schema.call(hash)
78
+ result.success? ? Success(result.to_h) : Failure(:invalid_params)
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry/monads"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # Maps the public channel names clients may use to container keys. There is no discovery:
8
+ # every reachable channel is listed in the app's config.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ class ChannelMap
13
+ include Dry::Monads[:result]
14
+
15
+ # @api private
16
+ # @since 0.1.0
17
+ NAME = /\A[a-z0-9_:-]{1,128}\z/
18
+ # @api private
19
+ # @since 0.1.0
20
+ SLICE_KEY = /\A(?:(?<slice>[a-z0-9_]+):)?(?<key>.+)\z/
21
+
22
+ # @param map [Hash{String => String}] public name to container key
23
+ # @param container [Object] the app container
24
+ #
25
+ # @api private
26
+ # @since 0.1.0
27
+ def initialize(map, container:)
28
+ raise ConfigurationError, "config.channels must be a non-empty Hash" if !map.is_a?(Hash) || map.empty?
29
+
30
+ @container = container
31
+ @map = map.to_h do |name, key|
32
+ validate_entry!(name, key)
33
+ [name, key]
34
+ end.freeze
35
+ end
36
+
37
+ # Resolves the component on every call, so code reloading is picked up.
38
+ #
39
+ # @return [Dry::Monads::Result] Success(channel) or Failure(:unknown_channel)
40
+ #
41
+ # @api private
42
+ # @since 0.1.0
43
+ def fetch(name)
44
+ key = @map[name]
45
+ return Failure(:unknown_channel) unless key
46
+
47
+ component = resolve(key)
48
+ return Failure(:unknown_channel) unless component.is_a?(Channel)
49
+
50
+ Success(component)
51
+ rescue StandardError
52
+ Failure(:unknown_channel)
53
+ end
54
+
55
+ private
56
+
57
+ # @api private
58
+ # @since 0.1.0
59
+ def validate_entry!(name, key)
60
+ unless name.is_a?(String) && NAME.match?(name)
61
+ raise ConfigurationError, "channel name #{name.inspect} must match #{NAME.inspect}"
62
+ end
63
+ unless key.is_a?(String) && SLICE_KEY.match?(key)
64
+ raise ConfigurationError, "channel key #{key.inspect} for #{name.inspect} is not a container key"
65
+ end
66
+ return if registered?(key)
67
+
68
+ raise ConfigurationError, "channel key #{key.inspect} for #{name.inspect} is not registered"
69
+ end
70
+
71
+ # Checks a key without building the component where possible: building a channel at boot
72
+ # would also build its dependencies, which may include this provider's own components
73
+ # (a channel that injects an operation that injects "sockets.broadcaster").
74
+ #
75
+ # @api private
76
+ # @since 0.1.0
77
+ def registered?(key)
78
+ match = SLICE_KEY.match(key)
79
+ container = target(match[:slice])
80
+ return true if container.respond_to?(:registered?) && container.registered?(match[:key])
81
+ return true if component_file?(container, match[:key])
82
+
83
+ container.key?(match[:key])
84
+ rescue ConfigurationError
85
+ false
86
+ rescue StandardError => exception
87
+ raise ConfigurationError, "channel key #{key.inspect} could not be loaded: " \
88
+ "#{exception.class}: #{exception.message}"
89
+ end
90
+
91
+ # @api private
92
+ # @since 0.1.0
93
+ def component_file?(container, key)
94
+ container = container.container if !container.respond_to?(:component_dirs) && container.respond_to?(:container)
95
+ return false unless container.respond_to?(:component_dirs)
96
+
97
+ container.component_dirs.any? { |dir| dir.component_for_key(key) }
98
+ end
99
+
100
+ # @api private
101
+ # @since 0.1.0
102
+ def resolve(key)
103
+ match = SLICE_KEY.match(key)
104
+ target(match[:slice])[match[:key]]
105
+ end
106
+
107
+ # @api private
108
+ # @since 0.1.0
109
+ def target(slice)
110
+ return @container unless slice
111
+
112
+ registry = slices
113
+ raise ConfigurationError, "channel key #{slice.inspect} needs a container with slices" unless registry
114
+
115
+ registry[slice.to_sym] || raise(ConfigurationError, "slice #{slice.inspect} is not registered")
116
+ end
117
+
118
+ # A Hanami provider's target is the slice's dry-system container, which has no slices, so
119
+ # fall back to the Hanami app's slice registry.
120
+ #
121
+ # @api private
122
+ # @since 0.1.0
123
+ def slices
124
+ return @container.slices if @container.respond_to?(:slices)
125
+
126
+ ::Hanami.app.slices if defined?(::Hanami) && ::Hanami.respond_to?(:app?) && ::Hanami.app?
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # `hanami sockets ...` commands. Loaded only when the gem is in the Gemfile's :cli group.
8
+ #
9
+ # @api private
10
+ # @since 0.1.0
11
+ module CLI
12
+ # Hanami 3.0 passes `out`; 3.1 passes `stdout`.
13
+ #
14
+ # @api private
15
+ # @since 0.1.0
16
+ module Output
17
+ private
18
+
19
+ # @api private
20
+ # @since 0.1.0
21
+ def output
22
+ return out if respond_to?(:out, true)
23
+ return stdout if respond_to?(:stdout, true)
24
+
25
+ $stdout
26
+ end
27
+ end
28
+
29
+ # Copies the browser client into the app and prints the provider, route and migration
30
+ # steps. With hanami-assets bundled the client goes to app/assets/js, where the asset
31
+ # build picks it up; without it, to public/js, which the app serves with Rack::Static.
32
+ #
33
+ # @api private
34
+ # @since 0.1.0
35
+ class Install < Hanami::CLI::Commands::App::Command
36
+ include Output
37
+
38
+ desc "Install the browser client and print the socket settings"
39
+
40
+ option :backend, default: "sql", values: %w[sql memory],
41
+ desc: "Backend to install (sql needs mankai-sockets-sql in the :cli group)"
42
+
43
+ # @api private
44
+ # @since 0.1.0
45
+ def call(backend:, **)
46
+ assets = Hanami.respond_to?(:bundled?) && Hanami.bundled?("hanami-assets")
47
+ copy_client(assets ? %w[app assets js] : %w[public js])
48
+ output.puts Snippets.provider(backend: backend)
49
+ output.puts(assets ? Snippets::ASSETS : Snippets::STATIC)
50
+ install_migration if backend == "sql"
51
+ end
52
+
53
+ private
54
+
55
+ # @api private
56
+ # @since 0.1.0
57
+ def copy_client(parts)
58
+ source = File.expand_path("../../../js/mankai-sockets.js", __dir__)
59
+ target_dir = File.join(app.root.to_s, *parts)
60
+ FileUtils.mkdir_p(target_dir)
61
+ target = File.join(target_dir, "mankai-sockets.js")
62
+ FileUtils.cp(source, target)
63
+ output.puts "Created #{target}"
64
+ end
65
+
66
+ # @api private
67
+ # @since 0.1.0
68
+ def install_migration
69
+ if defined?(Mankai::Sockets::SQL::Migration)
70
+ Mankai::Sockets::SQL::Migration.install(root: app.root, out: output)
71
+ else
72
+ output.puts <<~TEXT
73
+ mankai-sockets-sql is not loaded, so no migration was written. Add it to the Gemfile
74
+ with group: [:default, :cli], run bundle install, and run this command again.
75
+ TEXT
76
+ end
77
+ end
78
+ end
79
+
80
+ # The text the installer prints. Kept apart from the command so it reads as plain Ruby.
81
+ #
82
+ # @api private
83
+ # @since 0.1.0
84
+ module Snippets
85
+ module_function
86
+
87
+ # @api private
88
+ # @since 0.1.0
89
+ def provider(backend:)
90
+ backend_line =
91
+ if backend == "sql"
92
+ %(config.backend = Mankai::Sockets::SQL.backend(gateway: "db.gateway"))
93
+ else
94
+ "config.backend = :memory"
95
+ end
96
+ sql_require = backend == "sql" ? %(\nrequire "mankai/sockets/sql") : ""
97
+
98
+ <<~TEXT
99
+
100
+ Add a provider, a channel and a route:
101
+
102
+ # config/providers/sockets.rb
103
+ require "mankai/sockets"#{sql_require}
104
+
105
+ Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
106
+ configure do |config|
107
+ #{backend_line}
108
+ config.authenticator = lambda do |request, _token_subject|
109
+ user_id = request.session[:user_id]
110
+ user_id && Mankai::Sockets::Identity.new(key: "user:\#{user_id}", value: user_id)
111
+ end
112
+ config.allowed_origins = :same_origin
113
+ config.channels = {"chat" => "channels.chat"} # app/channels/chat.rb
114
+ end
115
+ end
116
+
117
+ # config/routes.rb
118
+ mount Hanami.app["sockets.endpoint"], at: "/sockets"
119
+
120
+ # config/app.rb: the authenticator reads the session, so enable sessions
121
+ # (rack-session needs a secret of at least 64 bytes)
122
+ config.actions.sessions = :cookie, {secret: settings.session_secret}
123
+ TEXT
124
+ end
125
+
126
+ # @api private
127
+ # @since 0.1.0
128
+ ASSETS = <<~TEXT
129
+
130
+ Import the client from your entry point, e.g. app/assets/js/app.js:
131
+
132
+ import {createConsumer} from "./mankai-sockets.js";
133
+
134
+ TEXT
135
+
136
+ # @api private
137
+ # @since 0.1.0
138
+ STATIC = <<~TEXT
139
+
140
+ Serve public/js and load the client from a module script file:
141
+
142
+ # config/app.rb
143
+ require "rack/static"
144
+ config.middleware.use Rack::Static, urls: ["/js"], root: File.expand_path("../public", __dir__)
145
+
146
+ // public/js/app.js
147
+ import {createConsumer} from "./mankai-sockets.js";
148
+
149
+ TEXT
150
+ end
151
+ end
152
+ end
153
+ end
154
+
155
+ Hanami::CLI.register "sockets" do |prefix|
156
+ prefix.register "install", Mankai::Sockets::CLI::Install
157
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # A websocket close code and the generic reason sent with it. Reasons never carry details
6
+ # about the app or the failure.
7
+ #
8
+ # @api public
9
+ # @since 0.1.0
10
+ CloseCode = Data.define(:code, :reason)
11
+
12
+ # @api public
13
+ # @since 0.1.0
14
+ class CloseCode
15
+ # @api public
16
+ # @since 0.1.0
17
+ INVALID_FRAME = new(4400, "invalid")
18
+ # @api public
19
+ # @since 0.1.0
20
+ UNAUTHORIZED = new(4401, "unauthorized")
21
+ # @api public
22
+ # @since 0.1.0
23
+ HELLO_TIMEOUT = new(4408, "hello timeout")
24
+ # @api public
25
+ # @since 0.1.0
26
+ DUPLICATE_ID = new(4409, "duplicate id")
27
+ # @api public
28
+ # @since 0.1.0
29
+ DUPLICATE_HELLO = new(4410, "duplicate hello")
30
+ # @api public
31
+ # @since 0.1.0
32
+ TOO_MANY_SUBSCRIPTIONS = new(4429, "too many subscriptions")
33
+ # @api public
34
+ # @since 0.1.0
35
+ TOO_MANY_CONNECTIONS = new(4430, "too many connections")
36
+ # @api public
37
+ # @since 0.1.0
38
+ SLOW_CONSUMER = new(4008, "slow consumer")
39
+ # @api public
40
+ # @since 0.1.0
41
+ IDLE = new(4000, "idle")
42
+ # @api public
43
+ # @since 0.1.0
44
+ GOING_AWAY = new(1001, "going away")
45
+
46
+ # @api public
47
+ # @since 0.1.0
48
+ def initialize(code:, reason:)
49
+ raise ArgumentError, "close code must be an Integer" unless code.is_a?(Integer)
50
+ raise ArgumentError, "close reason must be a String" unless reason.is_a?(String)
51
+
52
+ super
53
+ freeze
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # Everything a backend factory may need to build a backend.
6
+ #
7
+ # - container: the dry-system container, or nil outside one
8
+ # - instrumenter: emits mankai.sockets.* events
9
+ # - logger: a Logger-compatible object
10
+ # - clock: callable returning the current UTC Time
11
+ # - executor_threads: how many threads run channel code, for pool-size checks
12
+ #
13
+ # @api public
14
+ # @since 0.1.0
15
+ Context = Data.define(:container, :instrumenter, :logger, :clock, :executor_threads) do
16
+ # @api public
17
+ # @since 0.1.0
18
+ def initialize(clock: -> { Time.now.utc }, executor_threads: 4, **attributes)
19
+ super
20
+ freeze
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack"
4
+ require "websocket/driver"
5
+
6
+ module Mankai
7
+ module Sockets
8
+ # Rack app mounted in the app's routes. It checks the request before handing the hijacked
9
+ # socket to the server.
10
+ #
11
+ # @api public
12
+ # @since 0.1.0
13
+ class Endpoint
14
+ # @api private
15
+ # @since 0.1.0
16
+ def initialize(server:, origin_policy:, instrumenter:)
17
+ @server = server
18
+ @origin_policy = origin_policy
19
+ @instrumenter = instrumenter
20
+ end
21
+
22
+ # @param env [Hash] Rack env
23
+ # @return [Array] Rack response
24
+ #
25
+ # @api public
26
+ # @since 0.1.0
27
+ def call(env)
28
+ return [426, {"upgrade" => "websocket"}, ["Upgrade Required"]] unless WebSocket::Driver.websocket?(env)
29
+
30
+ request = Rack::Request.new(env)
31
+ return forbidden(request) unless @origin_policy.allowed?(request)
32
+ return [400, {}, ["Bad Request"]] unless offered_subprotocol?(request)
33
+
34
+ unless env["rack.hijack?"]
35
+ return [501, {}, ["Not Implemented"]]
36
+ end
37
+
38
+ io = env["rack.hijack"].call
39
+ @server.adopt(io, env)
40
+ [-1, {}, []]
41
+ end
42
+
43
+ private
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ def forbidden(request)
48
+ @instrumenter.instrument(:reject, origin: request.get_header("HTTP_ORIGIN"), reason: :origin)
49
+ [403, {}, ["Forbidden"]]
50
+ end
51
+
52
+ # @api private
53
+ # @since 0.1.0
54
+ def offered_subprotocol?(request)
55
+ offered = request.get_header("HTTP_SEC_WEBSOCKET_PROTOCOL").to_s.split(",").map(&:strip)
56
+ offered.include?(Protocol::SUBPROTOCOL)
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # Base class for the gem's errors.
6
+ #
7
+ # @api public
8
+ # @since 0.1.0
9
+ class Error < StandardError
10
+ end
11
+
12
+ # Raised at boot for a missing or invalid setting. The message says which setting is wrong
13
+ # and how to fix it.
14
+ #
15
+ # @api public
16
+ # @since 0.1.0
17
+ class ConfigurationError < Error
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # A fixed pool of threads that run session commands. Errors are reported to the injected
6
+ # callable and never kill a worker.
7
+ #
8
+ # @api private
9
+ # @since 0.1.0
10
+ class Executor
11
+ # @api private
12
+ # @since 0.1.0
13
+ STOP = Object.new.freeze
14
+
15
+ # @param threads [Integer]
16
+ # @param on_error [#call] receives an exception raised by a job
17
+ #
18
+ # @api private
19
+ # @since 0.1.0
20
+ def initialize(threads:, on_error:)
21
+ @queue = Queue.new
22
+ @threads = Array.new(threads) { Thread.new { work } }
23
+ @on_error = on_error
24
+ end
25
+
26
+ # @api private
27
+ # @since 0.1.0
28
+ def post(&block)
29
+ @queue << block
30
+ end
31
+
32
+ # Drains queued jobs, then joins the workers.
33
+ #
34
+ # @param timeout [Numeric] seconds to wait per thread
35
+ #
36
+ # @api private
37
+ # @since 0.1.0
38
+ def shutdown(timeout)
39
+ @threads.length.times { @queue << STOP }
40
+ @threads.each { |thread| thread.join(timeout) }
41
+ end
42
+
43
+ private
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ def work
48
+ loop do
49
+ job = @queue.pop
50
+ break if job.equal?(STOP)
51
+
52
+ begin
53
+ job.call
54
+ rescue StandardError => exception
55
+ @on_error.call(exception)
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end