cabby-rails 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 (43) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +27 -0
  3. data/LICENSE +21 -0
  4. data/README.md +190 -0
  5. data/lib/action_cable/subscription_adapter/cabby.rb +29 -0
  6. data/lib/cabby/broadcast/http.rb +103 -0
  7. data/lib/cabby/broadcast/nats.rb +45 -0
  8. data/lib/cabby/broadcast/postgres.rb +52 -0
  9. data/lib/cabby/broadcast/redis.rb +25 -0
  10. data/lib/cabby/broadcast/redis_connection.rb +54 -0
  11. data/lib/cabby/broadcast/redisx.rb +25 -0
  12. data/lib/cabby/broadcast.rb +53 -0
  13. data/lib/cabby/config.rb +159 -0
  14. data/lib/cabby/errors.rb +16 -0
  15. data/lib/cabby/rails/helper.rb +10 -0
  16. data/lib/cabby/rails/identifiers.rb +47 -0
  17. data/lib/cabby/rails/railtie.rb +34 -0
  18. data/lib/cabby/rails/remote_connections.rb +34 -0
  19. data/lib/cabby/rails/rpc/channel_streams.rb +19 -0
  20. data/lib/cabby/rails/rpc/command.rb +122 -0
  21. data/lib/cabby/rails/rpc/compat.rb +25 -0
  22. data/lib/cabby/rails/rpc/connect.rb +30 -0
  23. data/lib/cabby/rails/rpc/disconnect.rb +41 -0
  24. data/lib/cabby/rails/rpc/handler.rb +71 -0
  25. data/lib/cabby/rails/rpc/log_tags.rb +27 -0
  26. data/lib/cabby/rails/rpc/metadata.rb +26 -0
  27. data/lib/cabby/rails/rpc/rack_env.rb +73 -0
  28. data/lib/cabby/rails/rpc/server.rb +79 -0
  29. data/lib/cabby/rails/rpc/socket.rb +37 -0
  30. data/lib/cabby/rails/rpc.rb +113 -0
  31. data/lib/cabby/rails/serializer.rb +58 -0
  32. data/lib/cabby/rails/state.rb +70 -0
  33. data/lib/cabby/rails/version.rb +5 -0
  34. data/lib/cabby/rails/wiring.rb +30 -0
  35. data/lib/cabby/rails.rb +30 -0
  36. data/lib/cabby/secrets.rb +18 -0
  37. data/lib/cabby/signed_streams.rb +48 -0
  38. data/lib/cabby-rails.rb +2 -0
  39. data/lib/cabby.rb +57 -0
  40. data/lib/generators/cabby/setup/setup_generator.rb +138 -0
  41. data/lib/generators/cabby/setup/templates/cabby.yml +24 -0
  42. data/lib/generators/cabby/setup/templates/cable.yml +10 -0
  43. metadata +165 -0
@@ -0,0 +1,73 @@
1
+ require "stringio"
2
+ require "uri"
3
+
4
+ module Cabby
5
+ module Rails
6
+ class RPC
7
+ # The Rack env of the client's WebSocket request, rebuilt from the url and headers the
8
+ # server forwards, so cookies, the session, headers and params read as they would in
9
+ # Action Cable.
10
+ module RackEnv
11
+ # Upgrade headers would make Action Cable set up a real WebSocket.
12
+ SKIPPED_HEADERS = %w[connection upgrade].freeze
13
+
14
+ module_function
15
+
16
+ def build(url, headers)
17
+ uri = parse_url(url)
18
+ env = ::Rails.application.env_config.merge(url_env(uri))
19
+ headers.each do |name, value|
20
+ next if SKIPPED_HEADERS.include?(name.to_s.downcase)
21
+
22
+ env[rack_key(name.to_s)] = value.to_s
23
+ end
24
+ env
25
+ end
26
+
27
+ # Runs the block inside the app's session middleware, so `request.session` and
28
+ # `cookies` behave as in a normal request.
29
+ def with_session(env, &block)
30
+ store = ::Rails.application.config.session_store
31
+ return yield unless store
32
+
33
+ result = nil
34
+ app = lambda do |_env|
35
+ result = block.call
36
+ [200, {}, []]
37
+ end
38
+ store.new(app, ::Rails.application.config.session_options).call(env)
39
+ result
40
+ end
41
+
42
+ def url_env(uri)
43
+ https = %w[wss https].include?(uri.scheme)
44
+ host = uri.host || "localhost"
45
+ default_port = https ? 443 : 80
46
+ port = uri.port || default_port
47
+ {
48
+ "REQUEST_METHOD" => "GET", "SCRIPT_NAME" => "", "PATH_INFO" => uri.path.to_s.empty? ? "/" : uri.path,
49
+ "QUERY_STRING" => uri.query.to_s, "SERVER_NAME" => host, "SERVER_PORT" => port.to_s,
50
+ "SERVER_PROTOCOL" => "HTTP/1.1", "HTTP_HOST" => port == default_port ? host : "#{host}:#{port}",
51
+ "HTTPS" => https ? "on" : "off", "rack.url_scheme" => https ? "https" : "http",
52
+ "rack.input" => StringIO.new(+""), "rack.errors" => $stderr
53
+ }
54
+ end
55
+
56
+ def parse_url(url)
57
+ URI.parse(url.to_s)
58
+ rescue URI::InvalidURIError
59
+ URI.parse("")
60
+ end
61
+
62
+ def rack_key(name)
63
+ case name.downcase
64
+ when "remote_addr" then "REMOTE_ADDR"
65
+ when "content-type" then "CONTENT_TYPE"
66
+ when "content-length" then "CONTENT_LENGTH"
67
+ else "HTTP_#{name.upcase.tr("-", "_")}"
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,79 @@
1
+ module Cabby
2
+ module Rails
3
+ class RPC
4
+ # What connections and channels see as their server during one call: the app's config and
5
+ # logger, with work run at once and subscriptions recorded for the answer.
6
+ class Server
7
+ attr_reader :pubsub, :event_loop, :worker_pool
8
+
9
+ def initialize(app_server = ::ActionCable.server)
10
+ @app_server = app_server
11
+ @pubsub = PubSub.new
12
+ @event_loop = EventLoop.new
13
+ @worker_pool = WorkerPool.new
14
+ end
15
+
16
+ def config = @app_server.config
17
+
18
+ def logger = @app_server.logger
19
+
20
+ def mutex = @app_server.mutex
21
+
22
+ # The server tracks connections; there is nothing to register in the app.
23
+ def add_connection(_connection) = nil
24
+
25
+ def remove_connection(_connection) = nil
26
+
27
+ # Notes streams started and stopped, in order, so the answer reflects where the
28
+ # subscription ends up.
29
+ class PubSub
30
+ attr_reader :streams, :stopped_streams
31
+
32
+ def initialize
33
+ @streams = []
34
+ @stopped_streams = []
35
+ @stop_all = false
36
+ end
37
+
38
+ def subscribe(stream, _handler = nil, success = nil)
39
+ stream = stream.to_s
40
+ @stopped_streams.delete(stream)
41
+ @streams << stream unless @streams.include?(stream)
42
+ success&.call
43
+ end
44
+
45
+ def unsubscribe(stream, _handler = nil)
46
+ stream = stream.to_s
47
+ @streams.delete(stream)
48
+ @stopped_streams << stream unless @stopped_streams.include?(stream)
49
+ end
50
+
51
+ def stop_all
52
+ @stop_all = true
53
+ end
54
+
55
+ def stop_all? = @stop_all
56
+ end
57
+
58
+ class EventLoop
59
+ # Periodic timers need a long-lived process; a timer here never fires.
60
+ module NullTimer
61
+ def self.shutdown = nil
62
+ end
63
+
64
+ def post(task = nil, &block) = (task || block).call
65
+
66
+ def timer(_interval) = NullTimer
67
+ end
68
+
69
+ class WorkerPool
70
+ def async_invoke(receiver, method, *, **, &) = receiver.send(method, *, &)
71
+
72
+ def async_exec(receiver, *, **, &) = receiver.instance_exec(*, &)
73
+
74
+ alias invoke async_invoke
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,37 @@
1
+ module Cabby
2
+ module Rails
3
+ class RPC
4
+ # What a connection writes to: it keeps the transmissions for the answer instead of a
5
+ # WebSocket, and carries the Rack env built from the request's url and headers.
6
+ class Socket
7
+ attr_reader :env, :transmissions
8
+
9
+ def initialize(env)
10
+ @env = env
11
+ @transmissions = []
12
+ @closed = false
13
+ end
14
+
15
+ def possible? = true
16
+
17
+ def alive? = !@closed
18
+
19
+ def closed? = @closed
20
+
21
+ # Like a closed WebSocket, a closed socket drops what is sent after the close.
22
+ def transmit(data)
23
+ @transmissions << data unless @closed
24
+ nil
25
+ end
26
+
27
+ def close(*)
28
+ @closed = true
29
+ end
30
+
31
+ def protocol = Compat::PROTOCOL
32
+
33
+ def rack_response = nil
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,113 @@
1
+ require "json"
2
+ require "active_support/security_utils"
3
+
4
+ module Cabby
5
+ module Rails
6
+ # The Rack app Cabby calls over HTTP: `mount Cabby::Rails::RPC => "/_cabby"`.
7
+ class RPC
8
+ ERROR = 0
9
+ SUCCESS = 1
10
+ FAILURE = 2
11
+
12
+ HANDLERS = { "/connect" => :Connect, "/command" => :Command, "/disconnect" => :Disconnect }.freeze
13
+
14
+ REFUSED_WITHOUT_SECRET = "Cabby: no CABBY_SECRET or CABBY_HTTP_RPC_SECRET is configured, so the RPC " \
15
+ "endpoint refuses every call outside development and test. Give the app and the " \
16
+ "cabby server the same secret.".freeze
17
+
18
+ class << self
19
+ def call(env) = new(Cabby.config).call(env)
20
+
21
+ def check_configuration(logger)
22
+ logger.error(REFUSED_WITHOUT_SECRET) if refuses_everything?(Cabby.config)
23
+ end
24
+
25
+ # Without a secret anyone who reaches the endpoint could act as any user, and a staging
26
+ # or preview environment is as reachable as production.
27
+ def refuses_everything?(config) = config.rpc_bearer.nil? && !::Rails.env.local?
28
+ end
29
+
30
+ def initialize(config)
31
+ @config = config
32
+ end
33
+
34
+ def call(env)
35
+ handler = HANDLERS[env["PATH_INFO"]]
36
+ return plain(404, "Not Found") unless handler
37
+ return plain(405, "Method Not Allowed", "allow" => "POST") unless env["REQUEST_METHOD"] == "POST"
38
+ return plain(401, "Unauthorized") unless authorized?(env)
39
+
40
+ body = read_body(env)
41
+ return plain(413, "Content Too Large") unless body
42
+
43
+ payload = parse(body)
44
+ return plain(400, "Bad Request") unless payload
45
+
46
+ sid = Metadata.new(env).sid
47
+ answer = ActiveSupport::Notifications.instrument("rpc.cabby", call: handler.to_s.downcase, sid: sid) do
48
+ within_app(sid) { RPC.const_get(handler).new(payload).call }
49
+ end
50
+ [200, { "content-type" => "application/json" }, [JSON.generate(answer)]]
51
+ end
52
+
53
+ private
54
+
55
+ def authorized?(env)
56
+ expected = @config.rpc_bearer
57
+ if expected.nil?
58
+ return true if ::Rails.env.local?
59
+
60
+ ::Rails.logger.error(REFUSED_WITHOUT_SECRET)
61
+ return false
62
+ end
63
+
64
+ token = env["HTTP_AUTHORIZATION"].to_s[/\ABearer (.+)\z/, 1]
65
+ !token.nil? && ActiveSupport::SecurityUtils.secure_compare(token, expected)
66
+ end
67
+
68
+ # nil when the body is over the limit; a declared length is checked before reading.
69
+ def read_body(env)
70
+ limit = @config.rpc_max_body_size
71
+ length = env["CONTENT_LENGTH"].to_s
72
+ return if !length.empty? && length.to_i > limit
73
+
74
+ input = env["rack.input"]
75
+ return "" unless input
76
+
77
+ body = input.read(limit + 1) || ""
78
+ body if body.bytesize <= limit
79
+ end
80
+
81
+ def parse(body)
82
+ return {} if body.strip.empty?
83
+
84
+ payload = JSON.parse(body)
85
+ payload if payload.is_a?(Hash)
86
+ rescue JSON::ParserError
87
+ nil
88
+ end
89
+
90
+ def within_app(sid, &block)
91
+ app = ::Rails.application
92
+ wrapper = app.config.reloading_enabled? ? app.reloader : app.executor
93
+ wrapper.wrap { Cabby::Rails.with_sid(sid) { LogTags.with(sid ? ["sid=#{sid}"] : [], &block) } }
94
+ end
95
+
96
+ def plain(status, text, headers = {})
97
+ [status, { "content-type" => "text/plain" }.merge(headers), [text]]
98
+ end
99
+ end
100
+ end
101
+ end
102
+
103
+ require "cabby/rails/rpc/metadata"
104
+ require "cabby/rails/rpc/log_tags"
105
+ require "cabby/rails/rpc/compat"
106
+ require "cabby/rails/rpc/socket"
107
+ require "cabby/rails/rpc/server"
108
+ require "cabby/rails/rpc/rack_env"
109
+ require "cabby/rails/rpc/channel_streams"
110
+ require "cabby/rails/rpc/handler"
111
+ require "cabby/rails/rpc/connect"
112
+ require "cabby/rails/rpc/command"
113
+ require "cabby/rails/rpc/disconnect"
@@ -0,0 +1,58 @@
1
+ require "json"
2
+
3
+ module Cabby
4
+ module Rails
5
+ # One JSON form for identifiers and state: hash keys sorted, so equal values always encode
6
+ # to the same bytes, and records as a one-key object `{"_cabby_gid": "gid://..."}`. Only
7
+ # that tag is looked up: a string, whoever sent it, always reads back as a string.
8
+ module Serializer
9
+ GLOBAL_ID_KEY = "_cabby_gid".freeze
10
+
11
+ module_function
12
+
13
+ def generate(value) = JSON.generate(dump(value))
14
+
15
+ def dump(value)
16
+ case value
17
+ when Hash then dump_hash(value)
18
+ when Array then value.map { |v| dump(v) }
19
+ when String, Integer, Float, true, false, nil then value
20
+ else dump_object(value)
21
+ end
22
+ end
23
+
24
+ def load(value)
25
+ return locate(value[GLOBAL_ID_KEY]) if record?(value)
26
+
27
+ case value
28
+ when Array then value.map { |v| load(v) }
29
+ when Hash then value.transform_values { |v| load(v) }
30
+ else value
31
+ end
32
+ end
33
+
34
+ def record?(value)
35
+ value.is_a?(Hash) && value.size == 1 && value[GLOBAL_ID_KEY].is_a?(String)
36
+ end
37
+
38
+ def locate(global_id) = GlobalID::Locator.locate(global_id)
39
+
40
+ # The tag must only ever come from a record, so a hash may not carry it.
41
+ def dump_hash(hash)
42
+ hash.map do |key, v|
43
+ key = key.to_s
44
+ raise ArgumentError, "#{GLOBAL_ID_KEY} is a reserved key: it marks a record" if key == GLOBAL_ID_KEY
45
+
46
+ [key, dump(v)]
47
+ end.sort_by(&:first).to_h
48
+ end
49
+
50
+ def dump_object(value)
51
+ return { GLOBAL_ID_KEY => value.to_global_id.to_s } if value.respond_to?(:to_global_id)
52
+
53
+ json = value.as_json
54
+ json.equal?(value) ? value.to_s : dump(json)
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,70 @@
1
+ module Cabby
2
+ module Rails
3
+ # A channel or connection instance lasts one RPC call; the server keeps declared values
4
+ # between calls (`istate` for a channel, `cstate` for the connection).
5
+ module State
6
+ extend ActiveSupport::Concern
7
+
8
+ class_methods do
9
+ def state_attr_accessor(*names)
10
+ names.each do |name|
11
+ key = name.to_s
12
+ define_method(name) { cabby_state.read(key) }
13
+ define_method(:"#{name}=") { |value| cabby_state.write(key, value) }
14
+ end
15
+ end
16
+ end
17
+
18
+ def cabby_state
19
+ @cabby_state ||= Store.new
20
+ end
21
+
22
+ def cabby_state=(store)
23
+ @cabby_state = store
24
+ end
25
+
26
+ # Values as the server holds them: a JSON string per key, "" for none.
27
+ class Store
28
+ def initialize(encoded = {})
29
+ @encoded = encoded.is_a?(Hash) ? encoded.to_h { |k, v| [k.to_s, v.to_s] } : {}
30
+ @values = {}
31
+ @read_as = {}
32
+ end
33
+
34
+ def read(key)
35
+ return @values[key] if @values.key?(key)
36
+
37
+ value = decode(@encoded[key])
38
+ # Kept so a value changed in place is noticed.
39
+ @read_as[key] = encode(value)
40
+ @values[key] = value
41
+ end
42
+
43
+ def write(key, value)
44
+ @read_as.delete(key)
45
+ @values[key] = value
46
+ end
47
+
48
+ # Only what differs from what the server sent, so unrelated keys are left alone.
49
+ def changes
50
+ @values.each_with_object({}) do |(key, value), changed|
51
+ encoded = encode(value)
52
+ changed[key] = encoded unless encoded == @read_as.fetch(key) { @encoded.fetch(key, "") }
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def encode(value) = value.nil? ? "" : Serializer.generate(value)
59
+
60
+ def decode(raw)
61
+ return if raw.nil? || raw.empty?
62
+
63
+ Serializer.load(JSON.parse(raw))
64
+ rescue JSON::ParserError
65
+ raw
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,5 @@
1
+ module Cabby
2
+ module Rails
3
+ VERSION = "0.1.0".freeze
4
+ end
5
+ end
@@ -0,0 +1,30 @@
1
+ module Cabby
2
+ module Rails
3
+ # What the Railtie hands Action Cable and Turbo so they point at the server; each leaves a
4
+ # value the app set itself alone.
5
+ module Wiring
6
+ module_function
7
+
8
+ def cabby_adapter?(server_config)
9
+ cable = server_config.cable || {}
10
+ (cable[:adapter] || cable["adapter"]).to_s == "cabby"
11
+ end
12
+
13
+ # `action_cable_meta_tag` (and Turbo, which reads it) then point browsers at the server.
14
+ def action_cable_url(server_config, config)
15
+ return unless cabby_adapter?(server_config) && server_config.url.nil? && config.url
16
+
17
+ server_config.url = config.url
18
+ end
19
+
20
+ # The key the server's --turbo_streams verifies with, so it confirms Turbo subscriptions
21
+ # itself. Set on Turbo's own config before Turbo reads it at boot.
22
+ def turbo_verifier_key(turbo_config, config)
23
+ return unless config.turbo_streams && turbo_config.signed_stream_verifier_key.nil?
24
+
25
+ key = config.turbo_streams_key
26
+ turbo_config.signed_stream_verifier_key = key if key
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,30 @@
1
+ require "rails"
2
+ require "action_cable"
3
+ require "global_id/railtie"
4
+ require "cabby"
5
+ require "cabby/rails/serializer"
6
+ require "cabby/rails/identifiers"
7
+ require "cabby/rails/state"
8
+ require "cabby/rails/rpc"
9
+ require "cabby/rails/remote_connections"
10
+ require "cabby/rails/helper"
11
+ require "cabby/rails/wiring"
12
+ require "cabby/rails/railtie"
13
+
14
+ module Cabby
15
+ module Rails
16
+ SID_KEY = :cabby_rails_sid
17
+
18
+ # The session id of the RPC call being handled (nil outside one), so app code can broadcast
19
+ # to everyone but the client that sent a message.
20
+ def self.current_sid = ActiveSupport::IsolatedExecutionState[SID_KEY]
21
+
22
+ def self.with_sid(sid)
23
+ previous = ActiveSupport::IsolatedExecutionState[SID_KEY]
24
+ ActiveSupport::IsolatedExecutionState[SID_KEY] = sid
25
+ yield
26
+ ensure
27
+ ActiveSupport::IsolatedExecutionState[SID_KEY] = previous
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,18 @@
1
+ require "openssl"
2
+
3
+ module Cabby
4
+ # The server derives its RPC and broadcast bearers from the application secret when they are
5
+ # not set explicitly; the app computes the same values so one secret configures both sides.
6
+ module Secrets
7
+ RPC_PHRASE = "rpc-cable".freeze
8
+ BROADCAST_PHRASE = "broadcast-cable".freeze
9
+
10
+ module_function
11
+
12
+ def rpc_bearer(secret) = sign(secret, RPC_PHRASE)
13
+
14
+ def broadcast_key(secret) = sign(secret, BROADCAST_PHRASE)
15
+
16
+ def sign(secret, phrase) = OpenSSL::HMAC.hexdigest("SHA256", secret, phrase)
17
+ end
18
+ end
@@ -0,0 +1,48 @@
1
+ require "json"
2
+ require "openssl"
3
+ require "active_support/security_utils"
4
+
5
+ module Cabby
6
+ # Stream names signed so the server can let a client subscribe to them without asking the
7
+ # app: Base64(JSON(name)) + "--" + hex(HMAC-SHA256(key, Base64 part)), the message format of
8
+ # ActiveSupport::MessageVerifier with SHA256 and JSON, which the server verifies.
9
+ module SignedStreams
10
+ module_function
11
+
12
+ def sign(name, key)
13
+ data = [JSON.generate(name.to_s)].pack("m0")
14
+ "#{data}--#{digest(data, key)}"
15
+ end
16
+
17
+ # The name, or nil when the signature does not match or the message is not a signed name.
18
+ def verify(signed, key)
19
+ data, digest, *rest = signed.to_s.split("--")
20
+ return unless rest.empty? && data && digest
21
+ return unless ActiveSupport::SecurityUtils.secure_compare(digest, digest(data, key))
22
+
23
+ name = JSON.parse(data.unpack1("m0"))
24
+ name if name.is_a?(String)
25
+ rescue ArgumentError, JSON::ParserError
26
+ nil
27
+ end
28
+
29
+ def digest(data, key) = OpenSSL::HMAC.hexdigest("SHA256", key, data)
30
+ end
31
+
32
+ class << self
33
+ # A stream name the server accepts on its signed streams channel (`$pubsub`) without an
34
+ # RPC call. Signed with streams_secret, or else the application secret, as the server
35
+ # verifies.
36
+ def sign_stream(name) = SignedStreams.sign(name, streams_key!)
37
+
38
+ def verify_stream(signed) = SignedStreams.verify(signed, streams_key!)
39
+
40
+ private
41
+
42
+ def streams_key!
43
+ config.streams_key or
44
+ raise ConfigurationError, "signing stream names needs streams_secret or secret (CABBY_STREAMS_SECRET, " \
45
+ "CABBY_SECRET)"
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,2 @@
1
+ require "cabby"
2
+ require "cabby/rails"
data/lib/cabby.rb ADDED
@@ -0,0 +1,57 @@
1
+ require "cabby/rails/version"
2
+ require "cabby/errors"
3
+ require "cabby/secrets"
4
+ require "cabby/config"
5
+ require "cabby/broadcast"
6
+ require "cabby/signed_streams"
7
+
8
+ module Cabby
9
+ BROADCASTER_LOCK = Mutex.new
10
+
11
+ class << self
12
+ def config
13
+ @config ||= Config.new
14
+ end
15
+
16
+ # A new config gets a new broadcaster, built from it when first used.
17
+ def config=(config)
18
+ previous = @broadcaster
19
+ @broadcaster = nil
20
+ @config = config
21
+ previous.shutdown if previous.respond_to?(:shutdown)
22
+ end
23
+
24
+ def configure
25
+ yield config
26
+ end
27
+
28
+ def broadcaster
29
+ @broadcaster || BROADCASTER_LOCK.synchronize { @broadcaster ||= Broadcast.build(config) }
30
+ end
31
+
32
+ attr_writer :broadcaster
33
+
34
+ # Sends `data` to everyone subscribed to `stream`. Options go into the message's meta:
35
+ # `exclude_socket:` (a session id, such as `Cabby::Rails.current_sid`) skips that client,
36
+ # `transient: true` keeps the message out of the stream's history.
37
+ def broadcast(stream, data, **)
38
+ broadcaster.broadcast(JSON.generate(Broadcast.message(stream, data, **)))
39
+ end
40
+
41
+ # Several messages in one request: each a Hash with :stream, :data and the options above.
42
+ def broadcast_batch(messages)
43
+ return if messages.empty?
44
+
45
+ batch = messages.map do |m|
46
+ m = m.to_h.symbolize_keys
47
+ Broadcast.message(m.delete(:stream), m.delete(:data), **m)
48
+ end
49
+ broadcaster.broadcast(JSON.generate(batch))
50
+ end
51
+
52
+ # Closes the connections whose identifiers string (as /connect answered it) is `identifier`.
53
+ def disconnect(identifier, reconnect: true)
54
+ broadcaster.broadcast(JSON.generate(Broadcast.disconnect_command(identifier, reconnect: reconnect)))
55
+ end
56
+ end
57
+ end