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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +27 -0
- data/LICENSE +21 -0
- data/README.md +190 -0
- data/lib/action_cable/subscription_adapter/cabby.rb +29 -0
- data/lib/cabby/broadcast/http.rb +103 -0
- data/lib/cabby/broadcast/nats.rb +45 -0
- data/lib/cabby/broadcast/postgres.rb +52 -0
- data/lib/cabby/broadcast/redis.rb +25 -0
- data/lib/cabby/broadcast/redis_connection.rb +54 -0
- data/lib/cabby/broadcast/redisx.rb +25 -0
- data/lib/cabby/broadcast.rb +53 -0
- data/lib/cabby/config.rb +159 -0
- data/lib/cabby/errors.rb +16 -0
- data/lib/cabby/rails/helper.rb +10 -0
- data/lib/cabby/rails/identifiers.rb +47 -0
- data/lib/cabby/rails/railtie.rb +34 -0
- data/lib/cabby/rails/remote_connections.rb +34 -0
- data/lib/cabby/rails/rpc/channel_streams.rb +19 -0
- data/lib/cabby/rails/rpc/command.rb +122 -0
- data/lib/cabby/rails/rpc/compat.rb +25 -0
- data/lib/cabby/rails/rpc/connect.rb +30 -0
- data/lib/cabby/rails/rpc/disconnect.rb +41 -0
- data/lib/cabby/rails/rpc/handler.rb +71 -0
- data/lib/cabby/rails/rpc/log_tags.rb +27 -0
- data/lib/cabby/rails/rpc/metadata.rb +26 -0
- data/lib/cabby/rails/rpc/rack_env.rb +73 -0
- data/lib/cabby/rails/rpc/server.rb +79 -0
- data/lib/cabby/rails/rpc/socket.rb +37 -0
- data/lib/cabby/rails/rpc.rb +113 -0
- data/lib/cabby/rails/serializer.rb +58 -0
- data/lib/cabby/rails/state.rb +70 -0
- data/lib/cabby/rails/version.rb +5 -0
- data/lib/cabby/rails/wiring.rb +30 -0
- data/lib/cabby/rails.rb +30 -0
- data/lib/cabby/secrets.rb +18 -0
- data/lib/cabby/signed_streams.rb +48 -0
- data/lib/cabby-rails.rb +2 -0
- data/lib/cabby.rb +57 -0
- data/lib/generators/cabby/setup/setup_generator.rb +138 -0
- data/lib/generators/cabby/setup/templates/cabby.yml +24 -0
- data/lib/generators/cabby/setup/templates/cable.yml +10 -0
- metadata +165 -0
data/lib/cabby/config.rb
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
require "active_support/configuration_file"
|
|
2
|
+
|
|
3
|
+
module Cabby
|
|
4
|
+
# Settings come from config/cabby.yml, then CABBY_* variables, then assignments in code
|
|
5
|
+
# (Cabby.configure), each layer over the one before. Where the server reads the same variable,
|
|
6
|
+
# the gem reads it too and defaults to the server's own default, so one environment
|
|
7
|
+
# configures both sides.
|
|
8
|
+
class Config
|
|
9
|
+
# The server's default stream, channel and subject name for broadcasts.
|
|
10
|
+
SERVER_BROADCAST_NAME = "__anycable__".freeze
|
|
11
|
+
|
|
12
|
+
# The server caps an RPC answer at 16 MiB by default; requests get the same bound.
|
|
13
|
+
DEFAULT_RPC_MAX_BODY_SIZE = 16 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
# name => [environment variables in order, default, kind]
|
|
16
|
+
SETTINGS = {
|
|
17
|
+
secret: [%w[CABBY_SECRET], nil, :secret],
|
|
18
|
+
http_rpc_secret: [%w[CABBY_HTTP_RPC_SECRET], nil, :secret],
|
|
19
|
+
broadcast_key: [%w[CABBY_BROADCAST_KEY], nil, :secret],
|
|
20
|
+
streams_secret: [%w[CABBY_STREAMS_SECRET], nil, :secret],
|
|
21
|
+
turbo_streams_secret: [%w[CABBY_TURBO_STREAMS_SECRET], nil, :secret],
|
|
22
|
+
turbo_streams: [%w[CABBY_TURBO_STREAMS], true, :boolean],
|
|
23
|
+
url: [%w[CABBY_URL], nil, :string],
|
|
24
|
+
broadcast_adapter: [%w[CABBY_BROADCAST_ADAPTER], "http", :adapter],
|
|
25
|
+
broadcast_url: [%w[CABBY_BROADCAST_URL], nil, :string],
|
|
26
|
+
broadcast_open_timeout: [%w[CABBY_BROADCAST_OPEN_TIMEOUT], 2.0, :float],
|
|
27
|
+
broadcast_read_timeout: [%w[CABBY_BROADCAST_READ_TIMEOUT], 5.0, :float],
|
|
28
|
+
postgres_schema: [%w[CABBY_POSTGRES_SCHEMA], "public", :string],
|
|
29
|
+
postgres_table_prefix: [%w[CABBY_POSTGRES_TABLE_PREFIX], "cabby_", :may_be_empty],
|
|
30
|
+
redis_url: [%w[CABBY_REDIS_URL REDIS_URL], "redis://localhost:6379", :string],
|
|
31
|
+
redisx_stream: [%w[CABBY_REDISX_STREAM], SERVER_BROADCAST_NAME, :string],
|
|
32
|
+
redis_channel: [%w[CABBY_REDIS_CHANNEL], SERVER_BROADCAST_NAME, :string],
|
|
33
|
+
nats_servers: [%w[CABBY_NATS_SERVERS], "nats://127.0.0.1:4222", :string],
|
|
34
|
+
nats_channel: [%w[CABBY_NATS_CHANNEL], SERVER_BROADCAST_NAME, :string],
|
|
35
|
+
rpc_max_body_size: [%w[CABBY_RPC_MAX_BODY_SIZE], DEFAULT_RPC_MAX_BODY_SIZE, :integer]
|
|
36
|
+
}.freeze
|
|
37
|
+
|
|
38
|
+
# The value the server reads as "turned off".
|
|
39
|
+
NONE = "none".freeze
|
|
40
|
+
TRUE_WORDS = %w[1 true yes on].freeze
|
|
41
|
+
FALSE_WORDS = %w[0 false no off].freeze
|
|
42
|
+
|
|
43
|
+
def initialize(env = ENV)
|
|
44
|
+
@env = env
|
|
45
|
+
@assigned = {}
|
|
46
|
+
@file = {}
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
SETTINGS.each_key do |name|
|
|
50
|
+
define_method(name) { setting(name) }
|
|
51
|
+
define_method(:"#{name}=") { |value| @assigned[name] = value }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Reads the section of `environment` from a YAML file (ERB evaluated, aliases allowed, a
|
|
55
|
+
# `shared` section merged in, as Rails' config_for does). A missing file is fine; an unknown
|
|
56
|
+
# key is an error, so a mistyped secret name does not pass silently.
|
|
57
|
+
def load_file(path, environment)
|
|
58
|
+
return self unless File.exist?(path)
|
|
59
|
+
|
|
60
|
+
sections = ActiveSupport::ConfigurationFile.parse(path)
|
|
61
|
+
raise ConfigurationError, "#{path}: expected a mapping of environments" unless sections.is_a?(Hash)
|
|
62
|
+
|
|
63
|
+
section = merged_section(path, sections, environment.to_s)
|
|
64
|
+
unknown = section.keys.map(&:to_s) - SETTINGS.keys.map(&:to_s)
|
|
65
|
+
unless unknown.empty?
|
|
66
|
+
raise ConfigurationError, "#{path}: unknown setting #{unknown.join(", ")} " \
|
|
67
|
+
"(known settings: #{SETTINGS.keys.join(", ")})"
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
@file = section.to_h { |key, value| [key.to_sym, value] }
|
|
71
|
+
self
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The bearer Cabby sends on RPC calls: the explicit RPC secret, or the one derived from the
|
|
75
|
+
# application secret, as the server does. An explicit "none" turns it off on both sides.
|
|
76
|
+
def rpc_bearer = bearer(:http_rpc_secret) { |secret| Secrets.rpc_bearer(secret) }
|
|
77
|
+
|
|
78
|
+
# The bearer the server expects on broadcasts, derived the same way.
|
|
79
|
+
def broadcast_bearer = bearer(:broadcast_key) { |secret| Secrets.broadcast_key(secret) }
|
|
80
|
+
|
|
81
|
+
# The server serves broadcasts on its main port when they are authenticated, and on 8090
|
|
82
|
+
# when they are not.
|
|
83
|
+
def broadcast_url
|
|
84
|
+
setting(:broadcast_url) ||
|
|
85
|
+
(broadcast_bearer ? "http://localhost:8080/_broadcast" : "http://localhost:8090/_broadcast")
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# The keys the server verifies signed stream names with: --streams_secret, else the
|
|
89
|
+
# application secret; Turbo's: --turbo_streams_secret, else that same key.
|
|
90
|
+
def streams_key = streams_secret || secret
|
|
91
|
+
|
|
92
|
+
def turbo_streams_key = turbo_streams_secret || streams_key
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def merged_section(path, sections, environment)
|
|
97
|
+
[sections["shared"], sections[environment]].compact.each_with_object({}) do |part, merged|
|
|
98
|
+
raise ConfigurationError, "#{path}: the #{environment} section must be a mapping" unless part.is_a?(Hash)
|
|
99
|
+
|
|
100
|
+
merged.merge!(part)
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def bearer(explicit)
|
|
105
|
+
return setting(explicit) if setting(explicit)
|
|
106
|
+
return if raw(explicit).to_s.strip == NONE
|
|
107
|
+
|
|
108
|
+
yield secret if secret
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def setting(name)
|
|
112
|
+
_, default, kind = SETTINGS.fetch(name)
|
|
113
|
+
value = raw(name)
|
|
114
|
+
return default if value.nil?
|
|
115
|
+
|
|
116
|
+
normalized = normalize(name, value, kind)
|
|
117
|
+
normalized.nil? ? default : normalized
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# A blank variable counts as unset (except where an empty value means something), so the
|
|
121
|
+
# file below it still applies.
|
|
122
|
+
def raw(name)
|
|
123
|
+
@assigned.fetch(name) do
|
|
124
|
+
variables, _, kind = SETTINGS.fetch(name)
|
|
125
|
+
from_env = variables.lazy.map { |variable| @env[variable] }.find do |value|
|
|
126
|
+
!value.nil? && (kind == :may_be_empty || !value.strip.empty?)
|
|
127
|
+
end
|
|
128
|
+
from_env.nil? ? @file[name] : from_env
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def normalize(name, value, kind)
|
|
133
|
+
case kind
|
|
134
|
+
when :float then Float(value)
|
|
135
|
+
when :integer then Integer(value)
|
|
136
|
+
when :boolean then boolean(name, value)
|
|
137
|
+
when :may_be_empty then value.to_s.strip
|
|
138
|
+
when :adapter then value.to_s.split(",").map { |a| a.strip.downcase }.reject(&:empty?).first
|
|
139
|
+
else text(value, kind)
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def text(value, kind)
|
|
144
|
+
text = value.to_s.strip
|
|
145
|
+
text unless text.empty? || (kind == :secret && text == NONE)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def boolean(name, value)
|
|
149
|
+
return value if [true, false].include?(value)
|
|
150
|
+
|
|
151
|
+
word = value.to_s.strip.downcase
|
|
152
|
+
return true if TRUE_WORDS.include?(word)
|
|
153
|
+
return false if FALSE_WORDS.include?(word)
|
|
154
|
+
return if word.empty?
|
|
155
|
+
|
|
156
|
+
raise ConfigurationError, "#{name} must be true or false, not #{value.inspect}"
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
data/lib/cabby/errors.rb
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
class Error < StandardError; end
|
|
3
|
+
|
|
4
|
+
# A setting is missing, unknown or invalid, or a broadcaster's client library is not there.
|
|
5
|
+
class ConfigurationError < Error; end
|
|
6
|
+
|
|
7
|
+
# The server did not take a broadcast. `status` is the HTTP status when there was one.
|
|
8
|
+
class BroadcastError < Error
|
|
9
|
+
attr_reader :status
|
|
10
|
+
|
|
11
|
+
def initialize(message, status: nil)
|
|
12
|
+
super(message)
|
|
13
|
+
@status = status
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
# View helpers, included in Action View.
|
|
4
|
+
module Helper
|
|
5
|
+
# A signed name for the server's `$pubsub` channel, for a client to subscribe with
|
|
6
|
+
# `{ channel: "$pubsub", signed_stream_name: ... }`.
|
|
7
|
+
def cabby_signed_stream_name(name) = Cabby.sign_stream(name)
|
|
8
|
+
end
|
|
9
|
+
end
|
|
10
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
# The server keeps the identifiers string a connection answered and matches it byte for byte
|
|
4
|
+
# (remote disconnects send the same string), so it must be the same for the same identifiers
|
|
5
|
+
# whatever order they were declared or assigned in.
|
|
6
|
+
module Identifiers
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def dump(connection)
|
|
10
|
+
encode(connection.identifiers.to_h { |name| [name, connection.public_send(name)] })
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def encode(values)
|
|
14
|
+
Serializer.generate(values.compact)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def restore(connection, string)
|
|
18
|
+
names = connection.identifiers.map(&:to_s)
|
|
19
|
+
parse(string).each do |name, value|
|
|
20
|
+
next unless names.include?(name)
|
|
21
|
+
|
|
22
|
+
if Serializer.record?(value)
|
|
23
|
+
restore_lazily(connection, name, value[Serializer::GLOBAL_ID_KEY])
|
|
24
|
+
else
|
|
25
|
+
connection.public_send(:"#{name}=", Serializer.load(value))
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def parse(string)
|
|
31
|
+
values = JSON.parse(string.to_s)
|
|
32
|
+
values.is_a?(Hash) ? values : {}
|
|
33
|
+
rescue JSON::ParserError
|
|
34
|
+
{}
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Commands that never read a record should not pay for loading it.
|
|
38
|
+
def restore_lazily(connection, name, global_id)
|
|
39
|
+
ivar = :"@#{name}"
|
|
40
|
+
connection.define_singleton_method(name) do
|
|
41
|
+
instance_variable_set(ivar, Serializer.locate(global_id)) unless instance_variable_defined?(ivar)
|
|
42
|
+
instance_variable_get(ivar)
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class Railtie < ::Rails::Railtie
|
|
4
|
+
# Before the app's initializers, so a Cabby.configure block there sits over the file.
|
|
5
|
+
initializer "cabby.config_file", before: :load_config_initializers do |app|
|
|
6
|
+
Cabby.config.load_file(app.root.join("config/cabby.yml").to_s, ::Rails.env)
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
initializer "cabby.state_attr_accessor" do
|
|
10
|
+
ActiveSupport.on_load(:action_cable_connection) { include Cabby::Rails::State }
|
|
11
|
+
ActiveSupport.on_load(:action_cable_channel) { include Cabby::Rails::State }
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
initializer "cabby.helper" do
|
|
15
|
+
ActiveSupport.on_load(:action_view) { include Cabby::Rails::Helper }
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Registered when the gem loads, so it runs before Turbo's own after_initialize, which
|
|
19
|
+
# reads config.turbo.signed_stream_verifier_key; the app's initializers have run by then.
|
|
20
|
+
config.after_initialize do |app|
|
|
21
|
+
Cabby::Rails::RPC.check_configuration(::Rails.logger)
|
|
22
|
+
Cabby::Rails::Wiring.turbo_verifier_key(app.config.turbo, Cabby.config) if app.config.respond_to?(:turbo)
|
|
23
|
+
|
|
24
|
+
server = ::ActionCable.server
|
|
25
|
+
if Cabby::Rails::Wiring.cabby_adapter?(server.config)
|
|
26
|
+
Cabby::Rails::Wiring.action_cable_url(server.config, Cabby.config)
|
|
27
|
+
# Remote disconnects do not go through the adapter's broadcast, so they are wired
|
|
28
|
+
# before the adapter is first used.
|
|
29
|
+
Cabby::Rails::RemoteConnections.install(server)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
# `ActionCable.server.remote_connections.where(...).disconnect` as the server's disconnect
|
|
4
|
+
# command. The server matches the identifiers string byte for byte, so it is built with
|
|
5
|
+
# `Identifiers.encode`, as /connect built it.
|
|
6
|
+
class RemoteConnections < ::ActionCable::RemoteConnections
|
|
7
|
+
def self.install(server)
|
|
8
|
+
server.extend(ServerExtension) unless server.is_a?(ServerExtension)
|
|
9
|
+
end
|
|
10
|
+
|
|
11
|
+
# Given to the app's Action Cable server, whose `remote_connections` and `disconnect`
|
|
12
|
+
# then reach Cabby.
|
|
13
|
+
module ServerExtension
|
|
14
|
+
# Not @remote_connections: that one holds the server's own object.
|
|
15
|
+
def remote_connections
|
|
16
|
+
@cabby_remote_connections ||= Cabby::Rails::RemoteConnections.new(self) # rubocop:disable Naming/MemoizedInstanceVariableName
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def where(identifiers)
|
|
21
|
+
RemoteConnection.new(server, identifiers)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Action Cable's own checks apply: every declared identifier must be given (nil
|
|
25
|
+
# explicitly), as a string the server has no session for would disconnect nobody.
|
|
26
|
+
class RemoteConnection < ::ActionCable::RemoteConnections::RemoteConnection
|
|
27
|
+
def disconnect(reconnect: true)
|
|
28
|
+
values = identifiers.to_h { |name| [name, instance_variable_get(:"@#{name}")] }
|
|
29
|
+
::Cabby.disconnect(Identifiers.encode(values), reconnect: reconnect)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# A channel built for one call does not know the streams it started in earlier calls, so
|
|
5
|
+
# stopping them is recorded here for the server, which does know them.
|
|
6
|
+
module ChannelStreams
|
|
7
|
+
def stop_stream_from(broadcasting)
|
|
8
|
+
super
|
|
9
|
+
connection.server.pubsub.unsubscribe(broadcasting)
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
def stop_all_streams
|
|
13
|
+
super
|
|
14
|
+
connection.server.pubsub.stop_all
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# POST /command: subscribe, unsubscribe or message, for one channel of the connection.
|
|
5
|
+
class Command < Handler
|
|
6
|
+
# Warned once per class and process, not per call.
|
|
7
|
+
PERIODIC_WARNINGS = Concurrent::Map.new
|
|
8
|
+
|
|
9
|
+
private
|
|
10
|
+
|
|
11
|
+
def perform
|
|
12
|
+
@identifier = @payload["identifier"].to_s
|
|
13
|
+
Identifiers.restore(connection, @payload["connection_identifiers"])
|
|
14
|
+
|
|
15
|
+
case @payload["command"]
|
|
16
|
+
when "subscribe" then subscribe
|
|
17
|
+
when "unsubscribe" then unsubscribe
|
|
18
|
+
when "message" then message
|
|
19
|
+
else error("unknown command: #{@payload["command"].inspect}")
|
|
20
|
+
end
|
|
21
|
+
rescue StandardError => e
|
|
22
|
+
report(e)
|
|
23
|
+
error(e.message)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def subscribe
|
|
27
|
+
channel = build_channel(@identifier, @istate)
|
|
28
|
+
return unknown_channel unless channel
|
|
29
|
+
|
|
30
|
+
warn_about_periodic_timers(channel.class)
|
|
31
|
+
outcome = run { channel.subscribe_to_channel }
|
|
32
|
+
return error(outcome.message) if outcome.is_a?(Exception)
|
|
33
|
+
|
|
34
|
+
# A rejected subscription starts no streams, whatever the channel did before `reject`;
|
|
35
|
+
# neither does one whose `subscribed` raised, even when a handler dealt with it.
|
|
36
|
+
if outcome == :handled || Compat.rejected?(channel)
|
|
37
|
+
return answer(FAILURE, streams: [], stopped_streams: [], stop_streams: true)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
answer(SUCCESS, channel: channel)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def unsubscribe
|
|
44
|
+
channel = build_channel(@identifier, @istate)
|
|
45
|
+
outcome = channel && run { channel.unsubscribe_from_channel }
|
|
46
|
+
return error(outcome.message) if outcome.is_a?(Exception)
|
|
47
|
+
|
|
48
|
+
answer(SUCCESS, stop_streams: true)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def message
|
|
52
|
+
channel = build_channel(@identifier, @istate)
|
|
53
|
+
return answer(FAILURE, error_msg: not_found_message) unless channel
|
|
54
|
+
|
|
55
|
+
data = ActiveSupport::JSON.decode(@payload["data"].to_s)
|
|
56
|
+
return error("message data must be a JSON object") unless data.is_a?(Hash)
|
|
57
|
+
|
|
58
|
+
action = (data["action"].presence || "receive").to_s
|
|
59
|
+
return unknown_action(channel, action) unless channel.class.action_methods.include?(action)
|
|
60
|
+
|
|
61
|
+
outcome = run { channel.perform_action(data) }
|
|
62
|
+
outcome.is_a?(Exception) ? error(outcome.message) : answer(SUCCESS, channel: channel)
|
|
63
|
+
rescue JSON::ParserError
|
|
64
|
+
error("message data must be a JSON object")
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Runs app code as Action Cable runs a command: inside the connection's command
|
|
68
|
+
# callbacks, with its rescue_from handlers. Returns nil when the code ran, :handled when
|
|
69
|
+
# a handler dealt with what it raised (the command is complete), or the exception.
|
|
70
|
+
def run(&)
|
|
71
|
+
connection.run_callbacks(:command, &)
|
|
72
|
+
nil
|
|
73
|
+
rescue StandardError => e
|
|
74
|
+
return :handled if connection.rescue_with_handler(e)
|
|
75
|
+
|
|
76
|
+
report(e)
|
|
77
|
+
e
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def unknown_channel
|
|
81
|
+
logger.error(not_found_message)
|
|
82
|
+
connection.transmit(identifier: @identifier, type: Compat::REJECTION)
|
|
83
|
+
answer(FAILURE, error_msg: not_found_message, streams: [], stop_streams: true)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def not_found_message
|
|
87
|
+
params = channel_params(@identifier)
|
|
88
|
+
"Subscription class not found: #{(params && params[:channel]).inspect}"
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def unknown_action(channel, action)
|
|
92
|
+
message = "Unable to process #{channel.class.name}##{action}"
|
|
93
|
+
logger.error(message)
|
|
94
|
+
answer(FAILURE, error_msg: message, transmissions: [])
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def warn_about_periodic_timers(channel_class)
|
|
98
|
+
return unless Compat.periodic_timers?(channel_class)
|
|
99
|
+
return unless PERIODIC_WARNINGS.put_if_absent(channel_class.name, true).nil?
|
|
100
|
+
|
|
101
|
+
logger.warn("Cabby: #{channel_class.name} declares periodically timers, which are not run: " \
|
|
102
|
+
"a channel instance lasts one RPC call.")
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def answer(status, channel: nil, **fields)
|
|
106
|
+
pubsub = server.pubsub
|
|
107
|
+
{
|
|
108
|
+
status: status, disconnect: socket.closed?, stop_streams: pubsub.stop_all?,
|
|
109
|
+
streams: pubsub.streams, stopped_streams: pubsub.stopped_streams,
|
|
110
|
+
transmissions: socket.transmissions, error_msg: "",
|
|
111
|
+
env: { cstate: connection.cabby_state.changes, istate: channel ? channel.cabby_state.changes : {} }
|
|
112
|
+
}.merge(fields)
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def error(message)
|
|
116
|
+
{ status: ERROR, disconnect: false, stop_streams: false, streams: [], stopped_streams: [],
|
|
117
|
+
transmissions: [], error_msg: message, env: { cstate: {}, istate: {} } }
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# Every Action Cable internal the bridge relies on, in one place. Rails 8.0 and 8.1
|
|
5
|
+
# agree on all of them.
|
|
6
|
+
module Compat
|
|
7
|
+
WELCOME = ::ActionCable::INTERNAL[:message_types][:welcome]
|
|
8
|
+
REJECTION = ::ActionCable::INTERNAL[:message_types][:rejection]
|
|
9
|
+
UNAUTHORIZED = ::ActionCable::INTERNAL[:disconnect_reasons][:unauthorized]
|
|
10
|
+
PROTOCOL = ::ActionCable::INTERNAL[:protocols].first
|
|
11
|
+
|
|
12
|
+
module_function
|
|
13
|
+
|
|
14
|
+
# Connection::Base wraps its socket in @websocket and sends every transmission through it.
|
|
15
|
+
def attach_socket(connection, socket)
|
|
16
|
+
connection.instance_variable_set(:@websocket, socket)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def rejected?(channel) = channel.send(:subscription_rejected?) ? true : false
|
|
20
|
+
|
|
21
|
+
def periodic_timers?(channel_class) = channel_class.periodic_timers.any?
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# POST /connect: runs the connection's `connect`.
|
|
5
|
+
class Connect < Handler
|
|
6
|
+
private
|
|
7
|
+
|
|
8
|
+
def perform
|
|
9
|
+
begin
|
|
10
|
+
connection.connect if connection.respond_to?(:connect)
|
|
11
|
+
rescue ::ActionCable::Connection::Authorization::UnauthorizedError
|
|
12
|
+
connection.close(reason: Compat::UNAUTHORIZED, reconnect: false)
|
|
13
|
+
end
|
|
14
|
+
return answer(FAILURE) if socket.closed?
|
|
15
|
+
|
|
16
|
+
connection.transmit(type: Compat::WELCOME)
|
|
17
|
+
answer(SUCCESS, identifiers: Identifiers.dump(connection), cstate: connection.cabby_state.changes)
|
|
18
|
+
rescue StandardError => e
|
|
19
|
+
report(e)
|
|
20
|
+
answer(ERROR, error_msg: e.message, transmissions: [])
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
def answer(status, identifiers: "", error_msg: "", cstate: {}, transmissions: socket.transmissions)
|
|
24
|
+
{ status: status, identifiers: identifiers, transmissions: transmissions, error_msg: error_msg,
|
|
25
|
+
env: { cstate: cstate } }
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
end
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# POST /disconnect: each subscription's `unsubscribed`, then the connection's `disconnect`.
|
|
5
|
+
class Disconnect < Handler
|
|
6
|
+
private
|
|
7
|
+
|
|
8
|
+
def perform
|
|
9
|
+
Identifiers.restore(connection, @payload["identifiers"])
|
|
10
|
+
errors = []
|
|
11
|
+
Array(@payload["subscriptions"]).each do |identifier|
|
|
12
|
+
channel = build_channel(identifier.to_s, channel_state(identifier))
|
|
13
|
+
capture(errors) { channel.unsubscribe_from_channel } if channel
|
|
14
|
+
end
|
|
15
|
+
capture(errors) { connection.disconnect if connection.respond_to?(:disconnect) }
|
|
16
|
+
|
|
17
|
+
errors.empty? ? { status: SUCCESS, error_msg: "" } : { status: ERROR, error_msg: errors.first.message }
|
|
18
|
+
rescue StandardError => e
|
|
19
|
+
report(e)
|
|
20
|
+
{ status: ERROR, error_msg: e.message }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# One callback failing must not keep the others from running.
|
|
24
|
+
def capture(errors)
|
|
25
|
+
yield
|
|
26
|
+
rescue StandardError => e
|
|
27
|
+
report(e)
|
|
28
|
+
errors << e
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The server sends each subscription's state as the JSON of its map.
|
|
32
|
+
def channel_state(identifier)
|
|
33
|
+
state = JSON.parse(@istate[identifier].to_s)
|
|
34
|
+
state.is_a?(Hash) ? state : {}
|
|
35
|
+
rescue JSON::ParserError
|
|
36
|
+
{}
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
require "concurrent/map"
|
|
2
|
+
|
|
3
|
+
module Cabby
|
|
4
|
+
module Rails
|
|
5
|
+
class RPC
|
|
6
|
+
# One RPC call: builds the app's connection for the request's env and answers with what
|
|
7
|
+
# the app's code did.
|
|
8
|
+
class Handler
|
|
9
|
+
def initialize(payload)
|
|
10
|
+
@payload = payload
|
|
11
|
+
env = hash(payload["env"])
|
|
12
|
+
@url = env["url"].to_s
|
|
13
|
+
@headers = hash(env["headers"])
|
|
14
|
+
@cstate = hash(env["cstate"])
|
|
15
|
+
@istate = hash(env["istate"])
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def call
|
|
19
|
+
@rack_env = RackEnv.build(@url, @headers)
|
|
20
|
+
RackEnv.with_session(@rack_env) { perform }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
def connection
|
|
26
|
+
@connection ||= begin
|
|
27
|
+
@socket = Socket.new(@rack_env)
|
|
28
|
+
connection = ::ActionCable.server.config.connection_class.call.new(server, @rack_env)
|
|
29
|
+
Compat.attach_socket(connection, @socket)
|
|
30
|
+
connection.cabby_state = State::Store.new(@cstate)
|
|
31
|
+
connection
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def socket
|
|
36
|
+
connection
|
|
37
|
+
@socket
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def server = @server ||= Server.new
|
|
41
|
+
|
|
42
|
+
def build_channel(identifier, istate)
|
|
43
|
+
params = channel_params(identifier)
|
|
44
|
+
channel_class = params && params[:channel].to_s.safe_constantize
|
|
45
|
+
return unless channel_class.is_a?(Class) && channel_class < ::ActionCable::Channel::Base
|
|
46
|
+
|
|
47
|
+
channel_class.new(connection, identifier, params).tap do |channel|
|
|
48
|
+
channel.extend(ChannelStreams)
|
|
49
|
+
channel.cabby_state = State::Store.new(istate)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def channel_params(identifier)
|
|
54
|
+
params = ActiveSupport::JSON.decode(identifier.to_s)
|
|
55
|
+
params.with_indifferent_access if params.is_a?(Hash)
|
|
56
|
+
rescue JSON::ParserError
|
|
57
|
+
nil
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def report(error)
|
|
61
|
+
logger.error("Cabby RPC: #{error.class}: #{error.message}")
|
|
62
|
+
::Rails.error.report(error, handled: false, source: "cabby.rpc")
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def logger = ::Rails.logger
|
|
66
|
+
|
|
67
|
+
def hash(value) = value.is_a?(Hash) ? value : {}
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# Tags pushed on each logger of a broadcast rather than with `tagged { }`, whose block a
|
|
5
|
+
# broadcast logger runs once per destination.
|
|
6
|
+
module LogTags
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def with(tags)
|
|
10
|
+
return yield if tags.empty?
|
|
11
|
+
|
|
12
|
+
loggers = targets(::Rails.logger).select { |logger| logger.respond_to?(:push_tags) }
|
|
13
|
+
loggers.each { |logger| logger.push_tags(*tags) }
|
|
14
|
+
begin
|
|
15
|
+
yield
|
|
16
|
+
ensure
|
|
17
|
+
loggers.each { |logger| logger.pop_tags(tags.size) }
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def targets(logger)
|
|
22
|
+
logger.respond_to?(:broadcasts) ? logger.broadcasts : [logger]
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
module Cabby
|
|
2
|
+
module Rails
|
|
3
|
+
class RPC
|
|
4
|
+
# Metadata pairs arrive as headers; x-cabby-meta-<key> is preferred, and the server sends
|
|
5
|
+
# x-anycable-meta-<key>.
|
|
6
|
+
class Metadata
|
|
7
|
+
PREFIXES = %w[HTTP_X_CABBY_META_ HTTP_X_ANYCABLE_META_].freeze
|
|
8
|
+
|
|
9
|
+
def initialize(env)
|
|
10
|
+
@env = env
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def [](key)
|
|
14
|
+
name = key.to_s.upcase.tr("-", "_")
|
|
15
|
+
PREFIXES.each do |prefix|
|
|
16
|
+
value = @env["#{prefix}#{name}"].to_s
|
|
17
|
+
return value unless value.empty?
|
|
18
|
+
end
|
|
19
|
+
nil
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def sid = self["sid"]
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|