cable_room 0.6.2.beta1 → 0.7.0.beta2

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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +122 -0
  3. data/README.md +662 -48
  4. data/cable_room.gemspec +5 -2
  5. data/exe/cable_room +8 -0
  6. data/lib/cable_room/broadcaster.rb +116 -0
  7. data/lib/cable_room/bus.rb +372 -0
  8. data/lib/cable_room/cli.rb +237 -0
  9. data/lib/cable_room/config.rb +112 -0
  10. data/lib/cable_room/host/bus_inbound.rb +36 -0
  11. data/lib/cable_room/host/runner.rb +577 -0
  12. data/lib/cable_room/host/supervisor.rb +275 -0
  13. data/lib/cable_room/host/worker_pool.rb +37 -0
  14. data/lib/cable_room/host.rb +482 -0
  15. data/lib/cable_room/membership_store.rb +105 -0
  16. data/lib/cable_room/migration.rb +586 -0
  17. data/lib/cable_room/periodic_timer.rb +18 -0
  18. data/lib/cable_room/placement.rb +260 -0
  19. data/lib/cable_room/ports.rb +20 -50
  20. data/lib/cable_room/railtie.rb +3 -12
  21. data/lib/cable_room/room/base.rb +45 -39
  22. data/lib/cable_room/room/host_adapter.rb +52 -0
  23. data/lib/cable_room/room/lifecycle.rb +26 -9
  24. data/lib/cable_room/room/port_management.rb +70 -2
  25. data/lib/cable_room/room/reaping.rb +34 -1
  26. data/lib/cable_room/room/snapshotting.rb +82 -0
  27. data/lib/cable_room/room/threading.rb +2 -2
  28. data/lib/cable_room/room/user_management.rb +27 -0
  29. data/lib/cable_room/room.rb +5 -2
  30. data/lib/cable_room/room_harness.rb +168 -0
  31. data/lib/cable_room/room_member.rb +293 -69
  32. data/lib/cable_room/room_proxy_channel.rb +13 -2
  33. data/lib/cable_room/snapshot.rb +136 -0
  34. data/lib/cable_room/version.rb +1 -1
  35. data/lib/cable_room.rb +57 -2
  36. metadata +26 -9
  37. data/lib/cable_room/channel_base.rb +0 -247
  38. data/lib/cable_room/channel_tracker.rb +0 -130
  39. data/lib/cable_room/room/channel_adapter.rb +0 -18
@@ -0,0 +1,237 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "etc"
5
+ require "logger"
6
+ require_relative "version"
7
+
8
+ module CableRoom
9
+ # The `cable_room` command. Its one command, `server`, is the "rooms host" role from the
10
+ # distributed-rooms design: boot the Rails app, become a rooms host, run until SIGTERM or SIGINT,
11
+ # then shut every room down cleanly.
12
+ #
13
+ # It only makes sense with `room_host = :remote` and refuses to run otherwise: in :inline the
14
+ # web processes host rooms themselves, so a server here would only race them for locks.
15
+ #
16
+ # Boot works the way sidekiq and good_job do it: `require` the app's `config/environment.rb`
17
+ # from the current directory, or from `--require PATH` (an app directory or a boot file).
18
+ # Bundler is already set up because the command runs under `bundle exec`. Nothing from the gem
19
+ # beyond this file and `version` is loaded before the app boots, so the app's Gemfile decides
20
+ # when the Railtie loads, the same as in a web process.
21
+ #
22
+ # `--workers N` picks the process model. With N = 1 this process hosts rooms itself. With
23
+ # N > 1 (the default is the machine's core count) the app is booted once, here, and then
24
+ # `Host::Supervisor` forks N children that each host rooms; this parent only watches them,
25
+ # replaces one that dies, and relays SIGTERM and SIGINT. The parent never builds a Host, a Bus
26
+ # subscriber, or a Redis connection of its own: those belong to the children, which build them
27
+ # after the fork so no process ever shares a socket or a thread with another.
28
+ #
29
+ # Everything is instance state and `run` returns an exit status, so specs can drive the parsing
30
+ # and the refusals in-process; only the exe calls `exit`.
31
+ class CLI
32
+ STOP_SIGNALS = %w[TERM INT].freeze
33
+
34
+ attr_reader :options, :command
35
+
36
+ def initialize(argv, stdout: $stdout, stderr: $stderr)
37
+ @argv = argv.dup
38
+ @stdout = stdout
39
+ @stderr = stderr
40
+ @options = { workers: nil, require: Dir.pwd }
41
+ end
42
+
43
+ # Parse and run. Returns the process exit status.
44
+ def run
45
+ parse!
46
+ return 0 if @help_shown
47
+
48
+ case command
49
+ when "server" then server
50
+ when nil
51
+ @stderr.puts parser
52
+ 1
53
+ else
54
+ @stderr.puts "Unknown command #{command.inspect}.", parser
55
+ 1
56
+ end
57
+ rescue OptionParser::ParseError => e
58
+ @stderr.puts e.message, parser
59
+ 1
60
+ end
61
+
62
+ # How many worker processes `server` runs: `--workers`, or one per core.
63
+ def workers
64
+ options[:workers] || Etc.nprocessors
65
+ end
66
+
67
+ private
68
+
69
+ def parser
70
+ @parser ||= OptionParser.new do |o|
71
+ o.banner = "Usage: cable_room server [options]"
72
+ o.separator ""
73
+ o.separator "Runs a CableRoom rooms host: boots the Rails app in the current directory and"
74
+ o.separator "hosts rooms until SIGTERM or SIGINT. Needs CableRoom.config.room_host = :remote."
75
+ o.separator ""
76
+ o.on("-r", "--require PATH", "App directory (with config/environment.rb) or a boot file to require") do |path|
77
+ @options[:require] = path
78
+ end
79
+ o.on("-w", "--workers N", Integer,
80
+ "Worker processes to fork (default: one per core, #{Etc.nprocessors} here). 1 runs in this process.") do |n|
81
+ @options[:workers] = n
82
+ end
83
+ o.on("-v", "--version", "Print the version and exit") do
84
+ @stdout.puts CableRoom::VERSION
85
+ @help_shown = true
86
+ end
87
+ o.on("-h", "--help", "Show this help") do
88
+ @stdout.puts o
89
+ @help_shown = true
90
+ end
91
+ end
92
+ end
93
+
94
+ def parse!
95
+ rest = parser.parse(@argv)
96
+ @command = rest.shift
97
+ raise OptionParser::ParseError, "Unexpected arguments: #{rest.join(' ')}" if rest.any?
98
+ end
99
+
100
+ def server
101
+ # Check the cheap things before booting Rails, so a bad flag fails in milliseconds
102
+ unless workers >= 1
103
+ @stderr.puts "cable_room server: --workers must be at least 1 (got #{workers})."
104
+ return 1
105
+ end
106
+
107
+ boot_app!
108
+
109
+ unless CableRoom.config.remote?
110
+ @stderr.puts "cable_room server: CableRoom.config.room_host is #{CableRoom.config.room_host.inspect}, but a " \
111
+ "rooms host only makes sense with :remote (in :inline the web processes host rooms " \
112
+ "themselves). Set CABLE_ROOM_HOST=remote or `c.room_host = :remote` and try again."
113
+ return 1
114
+ end
115
+
116
+ return run_host if workers == 1
117
+
118
+ supervise_workers
119
+ end
120
+
121
+ # Load the app: a directory means its config/environment.rb, anything else is required as-is
122
+ def boot_app!
123
+ path = File.expand_path(options[:require])
124
+ path = File.join(path, "config", "environment.rb") if File.directory?(path)
125
+ require path
126
+ end
127
+
128
+ # Fork `workers` children that each run `run_host`, and watch them until a stop signal has
129
+ # come and gone. This parent hosts nothing itself (see the class comment for why).
130
+ def supervise_workers
131
+ Process.setproctitle("cable_room server: supervisor (#{workers} workers)")
132
+ say "supervising #{workers} workers (pid #{Process.pid}, room_host=#{CableRoom.config.room_host}, " \
133
+ "broadcaster=#{CableRoom.config.broadcaster})"
134
+
135
+ supervisor = CableRoom::Host::Supervisor.new(count: workers, logger: supervisor_logger) do |index|
136
+ run_host(worker: index)
137
+ end
138
+ status = supervisor.run
139
+ say "shut down"
140
+ status
141
+ end
142
+
143
+ # Logs from the supervisor go to the same place as the CLI's own messages, in the same style.
144
+ # Unbuffered, so a "forked worker" line shows up when it happens, not when the process exits.
145
+ def supervisor_logger
146
+ @stdout.sync = true if @stdout.respond_to?(:sync=)
147
+ Logger.new(@stdout).tap do |logger|
148
+ logger.formatter = ->(_severity, _time, _progname, message) { "cable_room server: #{message}\n" }
149
+ end
150
+ end
151
+
152
+ # Host rooms in this process until SIGTERM or SIGINT, then shut them down. This is the whole
153
+ # life of a single-process server and of each forked worker (`worker` is the worker's index,
154
+ # nil when there's no supervisor). Returns the exit status.
155
+ def run_host(worker: nil)
156
+ # Trap before starting the Host, so a signal that lands while rooms are still coming up
157
+ # (the supervisor relaying a SIGTERM that arrived mid-boot, say) is kept, not fatal
158
+ signals = trap_stop_signals
159
+
160
+ if worker
161
+ Process.setproctitle("cable_room server: worker #{worker}")
162
+ tag_logger("cable_room worker #{worker}")
163
+ end
164
+
165
+ host = CableRoom::Host.start!
166
+ say "hosting rooms (pid #{Process.pid}, room_host=#{CableRoom.config.room_host}, " \
167
+ "broadcaster=#{CableRoom.config.broadcaster})", worker: worker
168
+
169
+ signal = wait_for_stop_signal(signals)
170
+ stop_host(host, signal, worker: worker)
171
+ say "shut down", worker: worker
172
+ 0
173
+ ensure
174
+ restore_traps
175
+ end
176
+
177
+ # A stop signal with rooms open is a planned shutdown: hand the rooms to peer hosts before
178
+ # leaving (`Host#drain!`, bounded by `drain_timeout`; a room nobody adopts closes with
179
+ # `room_closed`). With nothing open there is nothing to move, so just shut down. Both are
180
+ # idempotent, so the one SIGTERM a supervisor relays and a later `at_exit` don't collide.
181
+ def stop_host(host, signal, worker: nil)
182
+ rooms = host.rooms.size
183
+ if rooms.zero?
184
+ say "got SIG#{signal}, shutting down 0 room(s)", worker: worker
185
+ host.shutdown!
186
+ return
187
+ end
188
+
189
+ say "got SIG#{signal}, migrating #{rooms} room(s) to peer hosts", worker: worker
190
+ result = host.drain!(reason: "SIG#{signal}")
191
+ say "drained: #{result.migrated.size} room(s) migrated, #{result.closed.size} closed, " \
192
+ "in #{result.duration.round(1)}s", worker: worker
193
+ end
194
+
195
+ # Every room on this Host logs through `ActionCable.server.logger` (Host#logger); give that
196
+ # logger a tag naming the worker, so lines from the N workers sharing one stdout can be told
197
+ # apart. `tagged` without a block returns a logger whose tags apply on every thread, which is
198
+ # what we need: rooms log from the worker pool, not from this thread. A logger without tags
199
+ # (a plain Logger, or Rails' BroadcastLogger fanning out to several) is left as it is.
200
+ def tag_logger(tag)
201
+ logger = ActionCable.server.logger
202
+ return unless logger.respond_to?(:tagged)
203
+
204
+ tagged = logger.tagged(tag)
205
+ ActionCable.server.config.logger = tagged if tagged.respond_to?(:info)
206
+ end
207
+
208
+ def say(message, worker: nil)
209
+ prefix = worker ? "cable_room server (worker #{worker})" : "cable_room server"
210
+ @stdout.puts "#{prefix}: #{message}"
211
+ @stdout.flush
212
+ end
213
+
214
+ # Signal handlers may only do trivial work, so each one just drops the signal's name on a
215
+ # queue for the main thread to pick up. Returns the queue.
216
+ def trap_stop_signals
217
+ signals = Queue.new
218
+ @previous_traps = STOP_SIGNALS.to_h { |sig| [sig, trap(sig) { signals << sig }] }
219
+ signals
220
+ end
221
+
222
+ # Block the main thread until SIGTERM or SIGINT; returns the signal's name. A timed pop, not
223
+ # a plain one: if this were the only thread left (a worker whose rooms have all gone quiet,
224
+ # say), a blocking pop would trip Ruby's deadlock detector, because a trap isn't a thread.
225
+ def wait_for_stop_signal(signals)
226
+ loop do
227
+ signal = signals.pop(timeout: 1)
228
+ return signal if signal
229
+ end
230
+ end
231
+
232
+ def restore_traps
233
+ @previous_traps&.each { |sig, handler| trap(sig, handler) }
234
+ @previous_traps = nil
235
+ end
236
+ end
237
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CableRoom
4
+ # Holds the app-wide settings for CableRoom. Get the current one with `CableRoom.config`
5
+ # and change it with `CableRoom.configure`:
6
+ #
7
+ # CableRoom.configure do |c|
8
+ # c.room_host = :remote # :inline | :remote
9
+ # c.broadcaster = :anycable # :action_cable | :anycable
10
+ # c.provision_delay_ms = 20
11
+ # c.drain_timeout = 10.minutes
12
+ # c.handoff_timeout = 10.seconds
13
+ # end
14
+ #
15
+ # The env vars CABLE_ROOM_HOST and CABLE_ROOM_BROADCASTER override `room_host` and
16
+ # `broadcaster`, even when the configure block sets them. That lets one build run in
17
+ # both modes without a code change. With no configuration at all, every default keeps
18
+ # today's behavior: rooms run inline and broadcast through ActionCable.
19
+ class Config
20
+ class InvalidOption < ArgumentError; end
21
+
22
+ ROOM_HOSTS = %i[inline remote].freeze
23
+ BROADCASTERS = %i[action_cable anycable].freeze
24
+
25
+ ENV_OVERRIDES = {
26
+ room_host: "CABLE_ROOM_HOST",
27
+ broadcaster: "CABLE_ROOM_BROADCASTER",
28
+ }.freeze
29
+
30
+ DEFAULTS = {
31
+ room_host: :inline,
32
+ broadcaster: :action_cable,
33
+ provision_delay_ms: 20,
34
+ drain_timeout: 10.minutes,
35
+ handoff_timeout: 10.seconds,
36
+ }.freeze
37
+
38
+ attr_reader :room_host, :broadcaster
39
+ attr_accessor :provision_delay_ms, :drain_timeout, :handoff_timeout
40
+
41
+ def initialize
42
+ DEFAULTS.each { |name, value| instance_variable_set("@#{name}", value) }
43
+ end
44
+
45
+ # Where rooms run. `:inline` keeps them in the web process; `:remote` moves them to a
46
+ # dedicated host pool. Accepts a Symbol or String; unknown values raise right away.
47
+ def room_host=(value)
48
+ @room_host = validate_choice!(:room_host, value, ROOM_HOSTS)
49
+ end
50
+
51
+ # How a room pushes messages to members. Accepts a Symbol or String; unknown values raise.
52
+ def broadcaster=(value)
53
+ @broadcaster = validate_choice!(:broadcaster, value, BROADCASTERS)
54
+ end
55
+
56
+ # Rooms run inside every process that joins them (the web process in a Rails app).
57
+ def inline?
58
+ room_host == :inline
59
+ end
60
+
61
+ # Rooms run only in `cable_room server` processes; a web process never hosts one.
62
+ def remote?
63
+ room_host == :remote
64
+ end
65
+
66
+ # Copies CABLE_ROOM_HOST and CABLE_ROOM_BROADCASTER onto this config. Blank or missing
67
+ # variables leave the current value alone. `env` is injectable for specs.
68
+ def apply_env_overrides(env = ENV)
69
+ ENV_OVERRIDES.each do |name, var|
70
+ value = env[var]
71
+ next if value.nil? || value.strip.empty?
72
+
73
+ public_send("#{name}=", value)
74
+ end
75
+ self
76
+ end
77
+
78
+ # Checks every knob at once. The choice knobs are already checked by their setters, so
79
+ # this mostly guards the timing knobs, which are plain accessors.
80
+ def validate!
81
+ validate_choice!(:room_host, room_host, ROOM_HOSTS)
82
+ validate_choice!(:broadcaster, broadcaster, BROADCASTERS)
83
+ validate_number!(:provision_delay_ms, provision_delay_ms, min: 0)
84
+ validate_number!(:drain_timeout, drain_timeout, min: 0, exclusive: true)
85
+ validate_number!(:handoff_timeout, handoff_timeout, min: 0, exclusive: true)
86
+ self
87
+ end
88
+
89
+ def to_h
90
+ DEFAULTS.keys.to_h { |name| [name, public_send(name)] }
91
+ end
92
+
93
+ private
94
+
95
+ def validate_choice!(name, value, allowed)
96
+ symbol = value.to_s.to_sym unless value.nil?
97
+ return symbol if allowed.include?(symbol)
98
+
99
+ raise InvalidOption,
100
+ "CableRoom config: #{name} must be one of #{allowed.map(&:inspect).join(', ')} " \
101
+ "(got #{value.inspect})"
102
+ end
103
+
104
+ def validate_number!(name, value, min:, exclusive: false)
105
+ ok = value.is_a?(Numeric) && (exclusive ? value > min : value >= min)
106
+ return value if ok
107
+
108
+ bound = exclusive ? "greater than #{min}" : "at least #{min}"
109
+ raise InvalidOption, "CableRoom config: #{name} must be a number #{bound} (got #{value.inspect})"
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,36 @@
1
+ module CableRoom
2
+ class Host
3
+ # How rooms receive messages: off the process-wide CableRoom::Bus (see `CableRoom.bus`), on
4
+ # the channels `Room::Base.inbound_channel` names. This is the only room-side code that
5
+ # touches the inbound transport, and it's the same in `:inline` and `:remote` mode — the only
6
+ # difference is which process the Host lives in. Anything with these two methods can be handed
7
+ # to `Host.new(inbound:)`.
8
+ #
9
+ # `subscribe` returns a handle that `unsubscribe` needs back. Handlers get the decoded message
10
+ # on the Bus's single subscriber thread, in publish order, so they must be quick and hand the
11
+ # real work off; Host::Runner does that by queueing it on the room. `subscribe` blocks until
12
+ # Redis confirms the subscription, so `on_live` runs on the caller's thread right before it
13
+ # returns, and anything published after that is delivered.
14
+ class BusInbound
15
+ # `bus` defaults to `CableRoom.bus` (looked up lazily so specs can swap it)
16
+ def initialize(bus: nil)
17
+ @bus = bus
18
+ end
19
+
20
+ def subscribe(channel, on_live: nil, &on_message)
21
+ bus.subscribe(channel) { |message, _channel| on_message.call(message) }
22
+ on_live&.call
23
+ on_message
24
+ end
25
+
26
+ def unsubscribe(channel, _handle)
27
+ bus.unsubscribe(channel)
28
+ end
29
+
30
+ # The Bus behind this transport (the process-wide one unless a spec handed us another)
31
+ def bus
32
+ @bus || CableRoom.bus
33
+ end
34
+ end
35
+ end
36
+ end