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,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # Value objects for the frames a client may send. `Protocol` builds them after validation;
6
+ # nothing here accepts an unvalidated Hash.
7
+ #
8
+ # @api private
9
+ # @since 0.1.0
10
+ module Frames
11
+ # @api private
12
+ # @since 0.1.0
13
+ def self.sized_string!(value, name, min:, max:)
14
+ return if value.is_a?(String) && value.bytesize.between?(min, max)
15
+
16
+ raise ArgumentError, "#{name} must be a String of #{min} to #{max} bytes"
17
+ end
18
+
19
+ Hello = Data.define(:token)
20
+
21
+ # @api private
22
+ # @since 0.1.0
23
+ class Hello
24
+ # @api private
25
+ # @since 0.1.0
26
+ MAX_TOKEN_BYTES = 2048
27
+
28
+ # @api private
29
+ # @since 0.1.0
30
+ def initialize(token: nil)
31
+ if token && !token.is_a?(String)
32
+ raise ArgumentError, "token must be a String"
33
+ end
34
+ raise ArgumentError, "token is too long" if token&.bytesize.to_i > MAX_TOKEN_BYTES
35
+
36
+ super
37
+ freeze
38
+ end
39
+ end
40
+
41
+ # @api private
42
+ # @since 0.1.0
43
+ Subscribe = Data.define(:id, :channel, :params)
44
+
45
+ # @api private
46
+ # @since 0.1.0
47
+ class Subscribe
48
+ # @api private
49
+ # @since 0.1.0
50
+ def initialize(id:, channel:, params: {})
51
+ Frames.sized_string!(id, "subscription id", min: 1, max: 64)
52
+ Frames.sized_string!(channel, "channel", min: 1, max: 128)
53
+ raise ArgumentError, "params must be a Hash" unless params.is_a?(Hash)
54
+
55
+ super(id: id, channel: channel, params: params.freeze)
56
+ freeze
57
+ end
58
+ end
59
+
60
+ # @api private
61
+ # @since 0.1.0
62
+ Unsubscribe = Data.define(:id)
63
+
64
+ # @api private
65
+ # @since 0.1.0
66
+ class Unsubscribe
67
+ # @api private
68
+ # @since 0.1.0
69
+ def initialize(id:)
70
+ Frames.sized_string!(id, "subscription id", min: 1, max: 64)
71
+ super
72
+ freeze
73
+ end
74
+ end
75
+
76
+ # @api private
77
+ # @since 0.1.0
78
+ Action = Data.define(:id, :name, :data, :ref)
79
+
80
+ # @api private
81
+ # @since 0.1.0
82
+ class Action
83
+ # @api private
84
+ # @since 0.1.0
85
+ def initialize(id:, name:, data: {}, ref: nil)
86
+ Frames.sized_string!(id, "subscription id", min: 1, max: 64)
87
+ Frames.sized_string!(name, "action name", min: 1, max: 128)
88
+ raise ArgumentError, "action data must be a Hash" unless data.is_a?(Hash)
89
+ if ref && !ref.is_a?(String)
90
+ raise ArgumentError, "ref must be a String"
91
+ end
92
+
93
+ Frames.sized_string!(ref, "ref", min: 1, max: 64) if ref
94
+
95
+ super(id: id, name: name, data: data.freeze, ref: ref)
96
+ freeze
97
+ end
98
+ end
99
+
100
+ # @api private
101
+ # @since 0.1.0
102
+ Ping = Data.define
103
+
104
+ # @api private
105
+ # @since 0.1.0
106
+ class Ping
107
+ # @api private
108
+ # @since 0.1.0
109
+ def initialize
110
+ super
111
+ freeze
112
+ end
113
+ end
114
+
115
+ # @api private
116
+ # @since 0.1.0
117
+ Pong = Data.define
118
+
119
+ # @api private
120
+ # @since 0.1.0
121
+ class Pong
122
+ # @api private
123
+ # @since 0.1.0
124
+ def initialize
125
+ super
126
+ freeze
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # Routes backend broadcasts to the sessions that listen on each stream. It subscribes to the
8
+ # backend once per stream, no matter how many sessions listen on it.
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ class Hub
13
+ # @api private
14
+ # @since 0.1.0
15
+ CONTROL_STREAM = "mankai.sockets.control"
16
+
17
+ # @api private
18
+ # @since 0.1.0
19
+ def initialize(backend:, sessions:)
20
+ @backend = backend
21
+ @sessions = sessions
22
+ @streams = {}
23
+ @mutex = Mutex.new
24
+ @listener = ->(broadcast) { receive(broadcast) }
25
+ end
26
+
27
+ # @api private
28
+ # @since 0.1.0
29
+ def add(session, streams)
30
+ @mutex.synchronize do
31
+ streams.each do |stream|
32
+ first = !@streams.key?(stream.name)
33
+ (@streams[stream.name] ||= Set.new) << session
34
+ @backend.subscribe(stream.name, @listener) if first
35
+ end
36
+ end
37
+ end
38
+
39
+ # @api private
40
+ # @since 0.1.0
41
+ def remove(session)
42
+ @mutex.synchronize do
43
+ @streams.each do |name, sessions|
44
+ sessions.delete(session)
45
+ next unless sessions.empty?
46
+
47
+ @streams.delete(name)
48
+ @backend.unsubscribe(name, @listener)
49
+ end
50
+ end
51
+ end
52
+
53
+ # @api private
54
+ # @since 0.1.0
55
+ def start
56
+ @backend.subscribe(CONTROL_STREAM, @listener)
57
+ end
58
+
59
+ private
60
+
61
+ # @api private
62
+ # @since 0.1.0
63
+ def receive(broadcast)
64
+ return control(broadcast) if broadcast.stream == CONTROL_STREAM
65
+
66
+ listeners = @mutex.synchronize { Array(@streams[broadcast.stream]&.dup) }
67
+ listeners.each { |session| session.broadcast_received(broadcast) }
68
+ end
69
+
70
+ # @api private
71
+ # @since 0.1.0
72
+ def control(broadcast)
73
+ data = JSON.parse(broadcast.payload)
74
+ key = data["disconnect"]
75
+ return unless key.is_a?(String)
76
+
77
+ @sessions.for_identity(key).each do |session|
78
+ session.close_requested(CloseCode::UNAUTHORIZED)
79
+ end
80
+ rescue JSON::ParserError
81
+ warn "[mankai-sockets] ignored an invalid control message"
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # Who a connection belongs to. The key groups a person's connections so they can be found
6
+ # and disconnected together; the value is the app's own identifier (never sent to a client).
7
+ #
8
+ # @api public
9
+ # @since 0.1.0
10
+ Identity = Data.define(:key, :value) do
11
+ # @api public
12
+ # @since 0.1.0
13
+ def initialize(key:, value: nil)
14
+ raise ArgumentError, "identity key must be a non-empty String" unless key.is_a?(String) && !key.empty?
15
+
16
+ super
17
+ freeze
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # Publishes events on a dry-monitor notifications bus. Events are registered up front so
6
+ # apps can subscribe before the first one fires. Payloads never contain tokens, params or
7
+ # message data.
8
+ #
9
+ # @api private
10
+ # @since 0.1.0
11
+ class Instrumenter
12
+ # @api private
13
+ # @since 0.1.0
14
+ PREFIX = "mankai.sockets"
15
+ # @api private
16
+ # @since 0.1.0
17
+ EVENTS = %i[connect disconnect reject subscribe unsubscribe action broadcast error].freeze
18
+ attr_reader :notifications
19
+
20
+ # @api private
21
+ # @since 0.1.0
22
+ def initialize(notifications = nil)
23
+ @notifications = notifications
24
+ @registered = Set.new
25
+ EVENTS.each { |event| register(event) } if notifications
26
+ end
27
+
28
+ # @api private
29
+ # @since 0.1.0
30
+ def instrument(event, payload = {})
31
+ return yield(payload) if block_given? && !notifications
32
+ return unless notifications
33
+
34
+ id = register(event)
35
+ return notifications.instrument(id, payload) unless block_given?
36
+
37
+ result = nil
38
+ begin
39
+ notifications.instrument(id, payload) { result = yield(payload) }
40
+ rescue Exception => exception # rubocop:disable Lint/RescueException
41
+ notifications.instrument(id, payload.merge(exception: exception))
42
+ raise
43
+ end
44
+ result
45
+ end
46
+
47
+ private
48
+
49
+ # @api private
50
+ # @since 0.1.0
51
+ def register(event)
52
+ id = :"#{PREFIX}.#{event}"
53
+ unless @registered.include?(id)
54
+ notifications.register_event(id)
55
+ @registered << id
56
+ end
57
+ id
58
+ end
59
+
60
+ # @api private
61
+ # @since 0.1.0
62
+ NULL = new(nil)
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # The size and timing limits a server enforces. Built once by the provider and passed whole,
6
+ # so no list of numbers travels between components.
7
+ #
8
+ # @api public
9
+ # @since 0.1.0
10
+ Limits = Data.define(
11
+ :max_frame_size, :max_payload_size, :max_subscriptions, :max_buffered_bytes,
12
+ :max_connections_per_identity, :hello_timeout, :heartbeat_interval
13
+ )
14
+
15
+ # @api private
16
+ # @since 0.1.0
17
+ class Limits
18
+ # @api private
19
+ # @since 0.1.0
20
+ NUMBERS = %i[
21
+ max_frame_size max_payload_size max_subscriptions max_buffered_bytes
22
+ max_connections_per_identity hello_timeout heartbeat_interval
23
+ ].freeze
24
+
25
+ # @api public
26
+ # @since 0.1.0
27
+ def initialize(**numbers)
28
+ NUMBERS.each do |name|
29
+ value = numbers.fetch(name)
30
+ raise ArgumentError, "#{name} must be a positive number" unless value.is_a?(Numeric) && value.positive?
31
+ end
32
+ super
33
+ freeze
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # A serial queue for one session. Commands run one at a time, in arrival order, on an
6
+ # executor thread. No thread per session is needed.
7
+ #
8
+ # @api private
9
+ # @since 0.1.0
10
+ class Mailbox
11
+ # @api private
12
+ # @since 0.1.0
13
+ def initialize(executor:)
14
+ @executor = executor
15
+ @queue = []
16
+ @mutex = Mutex.new
17
+ @running = false
18
+ end
19
+
20
+ # @api private
21
+ # @since 0.1.0
22
+ def post(&block)
23
+ start = false
24
+ @mutex.synchronize do
25
+ @queue << block
26
+ unless @running
27
+ @running = true
28
+ start = true
29
+ end
30
+ end
31
+ @executor.post { drain } if start
32
+ end
33
+
34
+ private
35
+
36
+ # @api private
37
+ # @since 0.1.0
38
+ def drain
39
+ loop do
40
+ task = next_task
41
+ break unless task
42
+
43
+ task.call
44
+ end
45
+ end
46
+
47
+ # @api private
48
+ # @since 0.1.0
49
+ def next_task
50
+ @mutex.synchronize do
51
+ task = @queue.shift
52
+ @running = false unless task
53
+ task
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mankai
4
+ module Sockets
5
+ # What a channel's `receive` gets: the action name, its data and an optional reply reference.
6
+ #
7
+ # @api public
8
+ # @since 0.1.0
9
+ Message = Data.define(:name, :data, :ref) do
10
+ # @api public
11
+ # @since 0.1.0
12
+ def initialize(name:, data: {}, ref: nil)
13
+ raise ArgumentError, "message name must be a non-empty String" unless name.is_a?(String) && !name.empty?
14
+ raise ArgumentError, "message data must be a Hash" unless data.is_a?(Hash)
15
+ unless ref.nil? || (ref.is_a?(String) && !ref.empty?)
16
+ raise ArgumentError, "message ref must be a non-empty String or nil"
17
+ end
18
+
19
+ super(name: name, data: data.freeze, ref: ref)
20
+ freeze
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Mankai
6
+ module Sockets
7
+ # Checks the Origin header of an upgrade request. Origins are parsed once, at construction:
8
+ # an exact origin, or a wildcard for subdomains such as "https://*.example.com". There is no
9
+ # "allow all" value and a missing Origin is never allowed.
10
+ #
11
+ # @api private
12
+ # @since 0.1.0
13
+ class OriginPolicy
14
+ # @api private
15
+ # @since 0.1.0
16
+ DEFAULT_PORTS = {"http" => 80, "https" => 443}.freeze
17
+ # @api private
18
+ # @since 0.1.0
19
+ WILDCARD = /\A(?<scheme>https?):\/\/\*\.(?<host>[a-z0-9.-]+)(?::(?<port>\d+))?\z/
20
+
21
+ # @param allowed [:same_origin, Array<String>] from config.allowed_origins
22
+ #
23
+ # @api private
24
+ # @since 0.1.0
25
+ def initialize(allowed)
26
+ @same_origin = allowed == :same_origin
27
+ @origins = if @same_origin
28
+ []
29
+ elsif allowed.is_a?(Array) && allowed.all? { |pattern| pattern.is_a?(String) }
30
+ allowed.map { |pattern| parse_pattern(pattern) }
31
+ else
32
+ raise ConfigurationError,
33
+ "config.allowed_origins must be :same_origin or an Array of origin patterns; " \
34
+ "allowing every origin is not supported"
35
+ end
36
+ end
37
+
38
+ # @param request [Rack::Request] the upgrade request
39
+ # @return [Boolean] whether its Origin is allowed
40
+ #
41
+ # @api private
42
+ # @since 0.1.0
43
+ def allowed?(request)
44
+ origin = parse(request.get_header("HTTP_ORIGIN"))
45
+ return false unless origin
46
+
47
+ if @same_origin
48
+ origin == parse(request.base_url)
49
+ else
50
+ @origins.any? { |pattern| matches?(pattern, origin) }
51
+ end
52
+ end
53
+
54
+ private
55
+
56
+ # @api private
57
+ # @since 0.1.0
58
+ def parse(text)
59
+ uri = URI.parse(text.to_s)
60
+ return nil unless valid_uri?(uri)
61
+
62
+ [uri.scheme, uri.host.downcase, uri.port || DEFAULT_PORTS.fetch(uri.scheme)]
63
+ rescue URI::InvalidURIError
64
+ nil
65
+ end
66
+
67
+ # @api private
68
+ # @since 0.1.0
69
+ def valid_uri?(uri)
70
+ return false unless DEFAULT_PORTS.key?(uri.scheme) && valid_host?(uri)
71
+ return false if uri.path && !uri.path.empty? && uri.path != "/"
72
+
73
+ !uri.query && !uri.fragment && !uri.userinfo
74
+ end
75
+
76
+ # @api private
77
+ # @since 0.1.0
78
+ def valid_host?(uri)
79
+ uri.host.is_a?(String) && !uri.host.empty?
80
+ end
81
+
82
+ # @api private
83
+ # @since 0.1.0
84
+ def parse_pattern(pattern)
85
+ match = WILDCARD.match(pattern)
86
+ if match
87
+ raise ConfigurationError, "invalid origin pattern #{pattern.inspect}" unless match[:host].include?(".")
88
+
89
+ port = match[:port]&.to_i || DEFAULT_PORTS.fetch(match[:scheme])
90
+ return [true, match[:scheme], match[:host].downcase, port]
91
+ end
92
+
93
+ parsed = parse_exact(pattern)
94
+ raise ConfigurationError, "invalid origin pattern #{pattern.inspect}" unless parsed
95
+
96
+ [false, *parsed]
97
+ end
98
+
99
+ # @api private
100
+ # @since 0.1.0
101
+ def parse_exact(pattern)
102
+ return nil if pattern.include?("*")
103
+
104
+ parse(pattern)
105
+ end
106
+
107
+ # @api private
108
+ # @since 0.1.0
109
+ def matches?(pattern, origin)
110
+ wildcard, scheme, host, port = pattern
111
+ return false unless origin[0] == scheme && origin[2] == port
112
+
113
+ wildcard ? origin[1].end_with?(".#{host}") : origin[1] == host
114
+ end
115
+ end
116
+ end
117
+ end