diff options
Diffstat (limited to 'actioncable')
91 files changed, 568 insertions, 392 deletions
diff --git a/actioncable/.gitignore b/actioncable/.gitignore index 0a04b29786..f514e58c16 100644 --- a/actioncable/.gitignore +++ b/actioncable/.gitignore @@ -1,2 +1,2 @@ -/lib/assets/compiled -/tmp +/lib/assets/compiled/ +/tmp/ diff --git a/actioncable/CHANGELOG.md b/actioncable/CHANGELOG.md index d5bd58cfdb..959943016f 100644 --- a/actioncable/CHANGELOG.md +++ b/actioncable/CHANGELOG.md @@ -1 +1,6 @@ -Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/actioncable/CHANGELOG.md) for previous changes. +* Rails 6 requires Ruby 2.4.1 or newer. + + *Jeremy Daer* + + +Please check [5-2-stable](https://github.com/rails/rails/blob/5-2-stable/actioncable/CHANGELOG.md) for previous changes. diff --git a/actioncable/MIT-LICENSE b/actioncable/MIT-LICENSE index 1a0e653b69..a42759f024 100644 --- a/actioncable/MIT-LICENSE +++ b/actioncable/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2015-2017 Basecamp, LLC +Copyright (c) 2015-2018 Basecamp, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/actioncable/README.md b/actioncable/README.md index e044f54b45..a05ef1dd20 100644 --- a/actioncable/README.md +++ b/actioncable/README.md @@ -53,7 +53,7 @@ module ApplicationCable private def find_verified_user - if verified_user = User.find_by(id: cookies.signed[:user_id]) + if verified_user = User.find_by(id: cookies.encrypted[:user_id]) verified_user else reject_unauthorized_connection @@ -409,7 +409,7 @@ application. The recommended basic setup is as follows: ```ruby # cable/config.ru -require ::File.expand_path('../../config/environment', __FILE__) +require_relative '../config/environment' Rails.application.eager_load! run ActionCable.server @@ -446,7 +446,7 @@ The WebSocket server doesn't have access to the session, but it has access to th ## Dependencies -Action Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, evented Redis, and non-evented Redis adapters are included. The default adapter in new Rails applications is the asynchronous (`async`) adapter. To create your own adapter, you can look at `ActionCable::SubscriptionAdapter::Base` for all methods that must be implemented, and any of the adapters included within Action Cable as example implementations. +Action Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, and Redis adapters are included. The default adapter in new Rails applications is the asynchronous (`async`) adapter. To create your own adapter, you can look at `ActionCable::SubscriptionAdapter::Base` for all methods that must be implemented, and any of the adapters included within Action Cable as example implementations. The Ruby side of things is built on top of [websocket-driver](https://github.com/faye/websocket-driver-ruby), [nio4r](https://github.com/celluloid/nio4r), and [concurrent-ruby](https://github.com/ruby-concurrency/concurrent-ruby). @@ -454,9 +454,9 @@ The Ruby side of things is built on top of [websocket-driver](https://github.com ## Deployment Action Cable is powered by a combination of WebSockets and threads. All of the -connection management is handled internally by utilizing Ruby’s native thread +connection management is handled internally by utilizing Ruby's native thread support, which means you can use all your regular Rails models with no problems -as long as you haven’t committed any thread-safety sins. +as long as you haven't committed any thread-safety sins. The Action Cable server does _not_ need to be a multi-threaded application server. This is because Action Cable uses the [Rack socket hijacking API](http://www.rubydoc.info/github/rack/rack/file/SPEC#Hijacking) @@ -549,7 +549,7 @@ Source code can be downloaded as part of the Rails project on GitHub Action Cable is released under the MIT license: -* http://www.opensource.org/licenses/MIT +* https://opensource.org/licenses/MIT ## Support @@ -558,7 +558,7 @@ API documentation is at: * http://api.rubyonrails.org -Bug reports can be filed for the Ruby on Rails project here: +Bug reports for the Ruby on Rails project can be filed here: * https://github.com/rails/rails/issues diff --git a/actioncable/Rakefile b/actioncable/Rakefile index bda8c7b6c8..226d171104 100644 --- a/actioncable/Rakefile +++ b/actioncable/Rakefile @@ -1,17 +1,17 @@ +# frozen_string_literal: true + require "rake/testtask" require "pathname" require "open3" require "action_cable" -dir = File.dirname(__FILE__) - task default: :test task package: %w( assets:compile assets:verify ) Rake::TestTask.new do |t| t.libs << "test" - t.test_files = Dir.glob("#{dir}/test/**/*_test.rb") + t.test_files = Dir.glob("#{__dir__}/test/**/*_test.rb") t.warning = true t.verbose = true t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) @@ -46,7 +46,7 @@ namespace :assets do desc "Verify compiled Action Cable assets" task :verify do file = "lib/assets/compiled/action_cable.js" - pathname = Pathname.new("#{dir}/#{file}") + pathname = Pathname.new("#{__dir__}/#{file}") print "[verify] #{file} exists " if pathname.exist? @@ -64,8 +64,8 @@ namespace :assets do fail end - print "[verify] #{dir} can be required as a module " - stdout, stderr, status = Open3.capture3("node", "--print", "window = {}; require('#{dir}');") + print "[verify] #{__dir__} can be required as a module " + _, stderr, status = Open3.capture3("node", "--print", "window = {}; require('#{__dir__}');") if status.success? puts "[OK]" else diff --git a/actioncable/actioncable.gemspec b/actioncable/actioncable.gemspec index 6d95f022fa..d946d0797f 100644 --- a/actioncable/actioncable.gemspec +++ b/actioncable/actioncable.gemspec @@ -1,4 +1,6 @@ -version = File.read(File.expand_path("../../RAILS_VERSION", __FILE__)).strip +# frozen_string_literal: true + +version = File.read(File.expand_path("../RAILS_VERSION", __dir__)).strip Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY @@ -7,7 +9,7 @@ Gem::Specification.new do |s| s.summary = "WebSocket framework for Rails." s.description = "Structure many real-time application concerns into channels over a single WebSocket connection." - s.required_ruby_version = ">= 2.2.2" + s.required_ruby_version = ">= 2.4.1" s.license = "MIT" @@ -18,8 +20,13 @@ Gem::Specification.new do |s| s.files = Dir["CHANGELOG.md", "MIT-LICENSE", "README.md", "lib/**/*"] s.require_path = "lib" + s.metadata = { + "source_code_uri" => "https://github.com/rails/rails/tree/v#{version}/actioncable", + "changelog_uri" => "https://github.com/rails/rails/blob/v#{version}/actioncable/CHANGELOG.md" + } + s.add_dependency "actionpack", version s.add_dependency "nio4r", "~> 2.0" - s.add_dependency "websocket-driver", "~> 0.6.1" + s.add_dependency "websocket-driver", ">= 0.6.1" end diff --git a/actioncable/bin/test b/actioncable/bin/test index a7beb14b27..c53377cc97 100755 --- a/actioncable/bin/test +++ b/actioncable/bin/test @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# frozen_string_literal: true COMPONENT_ROOT = File.expand_path("..", __dir__) -require File.expand_path("../tools/test", COMPONENT_ROOT) +require_relative "../../tools/test" diff --git a/actioncable/lib/action_cable.rb b/actioncable/lib/action_cable.rb index c2d3550acb..e7456e3c1b 100644 --- a/actioncable/lib/action_cable.rb +++ b/actioncable/lib/action_cable.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + #-- -# Copyright (c) 2015-2017 Basecamp, LLC +# Copyright (c) 2015-2018 Basecamp, LLC # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/actioncable/lib/action_cable/channel.rb b/actioncable/lib/action_cable/channel.rb index 7ae262ce5f..d2f6fbbbc7 100644 --- a/actioncable/lib/action_cable/channel.rb +++ b/actioncable/lib/action_cable/channel.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Channel extend ActiveSupport::Autoload diff --git a/actioncable/lib/action_cable/channel/base.rb b/actioncable/lib/action_cable/channel/base.rb index 718f630f58..c5ad749bfe 100644 --- a/actioncable/lib/action_cable/channel/base.rb +++ b/actioncable/lib/action_cable/channel/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "set" module ActionCable @@ -205,7 +207,9 @@ module ActionCable # Transmit a hash of data to the subscriber. The hash will automatically be wrapped in a JSON envelope with # the proper channel identifier marked as the recipient. def transmit(data, via: nil) # :doc: - logger.debug "#{self.class.name} transmitting #{data.inspect.truncate(300)}".tap { |m| m << " (via #{via})" if via } + status = "#{self.class.name} transmitting #{data.inspect.truncate(300)}" + status += " (via #{via})" if via + logger.debug(status) payload = { channel_class: self.class.name, data: data, via: via } ActiveSupport::Notifications.instrument("transmit.action_cable", payload) do @@ -266,7 +270,7 @@ module ActionCable end def action_signature(action, data) - "#{self.class.name}##{action}".tap do |signature| + "#{self.class.name}##{action}".dup.tap do |signature| if (arguments = data.except("action")).any? signature << "(#{arguments.inspect})" end diff --git a/actioncable/lib/action_cable/channel/broadcasting.rb b/actioncable/lib/action_cable/channel/broadcasting.rb index 23ed4ec943..9a96720f4a 100644 --- a/actioncable/lib/action_cable/channel/broadcasting.rb +++ b/actioncable/lib/action_cable/channel/broadcasting.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/core_ext/object/to_param" module ActionCable @@ -7,7 +9,7 @@ module ActionCable delegate :broadcasting_for, to: :class - class_methods do + module ClassMethods # Broadcast a hash to a unique broadcasting for this <tt>model</tt> in this channel. def broadcast_to(model, message) ActionCable.server.broadcast(broadcasting_for([ channel_name, model ]), message) diff --git a/actioncable/lib/action_cable/channel/callbacks.rb b/actioncable/lib/action_cable/channel/callbacks.rb index c740132c94..e4cb19b26a 100644 --- a/actioncable/lib/action_cable/channel/callbacks.rb +++ b/actioncable/lib/action_cable/channel/callbacks.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/callbacks" module ActionCable @@ -11,7 +13,7 @@ module ActionCable define_callbacks :unsubscribe end - class_methods do + module ClassMethods def before_subscribe(*methods, &block) set_callback(:subscribe, :before, *methods, &block) end diff --git a/actioncable/lib/action_cable/channel/naming.rb b/actioncable/lib/action_cable/channel/naming.rb index b565cb3cac..9c324a2a53 100644 --- a/actioncable/lib/action_cable/channel/naming.rb +++ b/actioncable/lib/action_cable/channel/naming.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + module ActionCable module Channel module Naming extend ActiveSupport::Concern - class_methods do + module ClassMethods # Returns the name of the channel, underscored, without the <tt>Channel</tt> ending. # If the channel is in a namespace, then the namespaces are represented by single # colon separators in the channel name. diff --git a/actioncable/lib/action_cable/channel/periodic_timers.rb b/actioncable/lib/action_cable/channel/periodic_timers.rb index c9daa0bcd3..830b3efa3c 100644 --- a/actioncable/lib/action_cable/channel/periodic_timers.rb +++ b/actioncable/lib/action_cable/channel/periodic_timers.rb @@ -1,11 +1,12 @@ +# frozen_string_literal: true + module ActionCable module Channel module PeriodicTimers extend ActiveSupport::Concern included do - class_attribute :periodic_timers, instance_reader: false - self.periodic_timers = [] + class_attribute :periodic_timers, instance_reader: false, default: [] after_subscribe :start_periodic_timers after_unsubscribe :stop_periodic_timers diff --git a/actioncable/lib/action_cable/channel/streams.rb b/actioncable/lib/action_cable/channel/streams.rb index dbba333353..81c2c38064 100644 --- a/actioncable/lib/action_cable/channel/streams.rb +++ b/actioncable/lib/action_cable/channel/streams.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Channel # Streams allow channels to route broadcastings to the subscriber. A broadcasting is, as discussed elsewhere, a pubsub queue where any data diff --git a/actioncable/lib/action_cable/connection.rb b/actioncable/lib/action_cable/connection.rb index 902efb07e2..804b89a707 100644 --- a/actioncable/lib/action_cable/connection.rb +++ b/actioncable/lib/action_cable/connection.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Connection extend ActiveSupport::Autoload diff --git a/actioncable/lib/action_cable/connection/authorization.rb b/actioncable/lib/action_cable/connection/authorization.rb index 989a67d6df..a22179d988 100644 --- a/actioncable/lib/action_cable/connection/authorization.rb +++ b/actioncable/lib/action_cable/connection/authorization.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Connection module Authorization diff --git a/actioncable/lib/action_cable/connection/base.rb b/actioncable/lib/action_cable/connection/base.rb index 0a517a532d..11a1f1a5e8 100644 --- a/actioncable/lib/action_cable/connection/base.rb +++ b/actioncable/lib/action_cable/connection/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "action_dispatch" module ActionCable @@ -24,7 +26,7 @@ module ActionCable # # private # def find_verified_user - # User.find_by_identity(cookies.signed[:identity_id]) || + # User.find_by_identity(cookies.encrypted[:identity_id]) || # reject_unauthorized_connection # end # end @@ -126,20 +128,18 @@ module ActionCable end def on_error(message) # :nodoc: - # ignore + # log errors to make diagnosing socket errors easier + logger.error "WebSocket error occurred: #{message}" end def on_close(reason, code) # :nodoc: send_async :handle_close end - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected + private attr_reader :websocket attr_reader :message_buffer - private # The request that initiated the WebSocket connection is available here. This gives access to the environment, cookies, etc. def request # :doc: @request ||= begin diff --git a/actioncable/lib/action_cable/connection/client_socket.rb b/actioncable/lib/action_cable/connection/client_socket.rb index c7e30e78c8..4b1964c4ae 100644 --- a/actioncable/lib/action_cable/connection/client_socket.rb +++ b/actioncable/lib/action_cable/connection/client_socket.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "websocket/driver" module ActionCable @@ -19,7 +21,7 @@ module ActionCable return true if env["HTTP_X_FORWARDED_PROTO"] == "https" return true if env["rack.url_scheme"] == "https" - return false + false end CONNECTING = 0 @@ -81,7 +83,7 @@ module ActionCable when Numeric then @driver.text(message.to_s) when String then @driver.text(message) when Array then @driver.binary(message) - else false + else false end end diff --git a/actioncable/lib/action_cable/connection/identification.rb b/actioncable/lib/action_cable/connection/identification.rb index c91a1d1fd7..cc544685dd 100644 --- a/actioncable/lib/action_cable/connection/identification.rb +++ b/actioncable/lib/action_cable/connection/identification.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "set" module ActionCable @@ -6,11 +8,10 @@ module ActionCable extend ActiveSupport::Concern included do - class_attribute :identifiers - self.identifiers = Set.new + class_attribute :identifiers, default: Set.new end - class_methods do + module ClassMethods # Mark a key as being a connection identifier index that can then be used to find the specific connection again later. # Common identifiers are current_user and current_account, but could be anything, really. # diff --git a/actioncable/lib/action_cable/connection/internal_channel.rb b/actioncable/lib/action_cable/connection/internal_channel.rb index 8f0ec766c3..f03904137b 100644 --- a/actioncable/lib/action_cable/connection/internal_channel.rb +++ b/actioncable/lib/action_cable/connection/internal_channel.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Connection # Makes it possible for the RemoteConnection to disconnect a specific connection. diff --git a/actioncable/lib/action_cable/connection/message_buffer.rb b/actioncable/lib/action_cable/connection/message_buffer.rb index 4ccd322644..965841b67e 100644 --- a/actioncable/lib/action_cable/connection/message_buffer.rb +++ b/actioncable/lib/action_cable/connection/message_buffer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Connection # Allows us to buffer messages received from the WebSocket before the Connection has been fully initialized, and is ready to receive them. @@ -28,13 +30,10 @@ module ActionCable receive_buffered_messages end - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected + private attr_reader :connection attr_reader :buffered_messages - private def valid?(message) message.is_a?(String) end diff --git a/actioncable/lib/action_cable/connection/stream.rb b/actioncable/lib/action_cable/connection/stream.rb index e620b93845..4873026b71 100644 --- a/actioncable/lib/action_cable/connection/stream.rb +++ b/actioncable/lib/action_cable/connection/stream.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "thread" module ActionCable diff --git a/actioncable/lib/action_cable/connection/stream_event_loop.rb b/actioncable/lib/action_cable/connection/stream_event_loop.rb index 2d1af0ff9f..d95afc50ba 100644 --- a/actioncable/lib/action_cable/connection/stream_event_loop.rb +++ b/actioncable/lib/action_cable/connection/stream_event_loop.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "nio" require "thread" diff --git a/actioncable/lib/action_cable/connection/subscriptions.rb b/actioncable/lib/action_cable/connection/subscriptions.rb index 44bce1e195..1ad8d05107 100644 --- a/actioncable/lib/action_cable/connection/subscriptions.rb +++ b/actioncable/lib/action_cable/connection/subscriptions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/core_ext/hash/indifferent_access" module ActionCable @@ -41,7 +43,7 @@ module ActionCable def remove(data) logger.info "Unsubscribing from channel: #{data['identifier']}" - remove_subscription subscriptions[data["identifier"]] + remove_subscription find(data) end def remove_subscription(subscription) @@ -61,12 +63,8 @@ module ActionCable subscriptions.each { |id, channel| remove_subscription(channel) } end - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :connection, :subscriptions - private + attr_reader :connection, :subscriptions delegate :logger, to: :connection def find(data) diff --git a/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb index aef549aa86..85831806a9 100644 --- a/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb +++ b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Connection # Allows the use of per-connection tags against the server logger. This wouldn't work using the traditional diff --git a/actioncable/lib/action_cable/connection/web_socket.rb b/actioncable/lib/action_cable/connection/web_socket.rb index 03eb6e2ea8..31f29fdd2f 100644 --- a/actioncable/lib/action_cable/connection/web_socket.rb +++ b/actioncable/lib/action_cable/connection/web_socket.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require "websocket/driver" module ActionCable module Connection # Wrap the real socket to minimize the externally-presented API - class WebSocket + class WebSocket # :nodoc: def initialize(env, event_target, event_loop, protocols: ActionCable::INTERNAL[:protocols]) @websocket = ::WebSocket::Driver.websocket?(env) ? ClientSocket.new(env, event_target, event_loop, protocols) : nil end @@ -32,9 +34,7 @@ module ActionCable websocket.rack_response end - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected + private attr_reader :websocket end end diff --git a/actioncable/lib/action_cable/engine.rb b/actioncable/lib/action_cable/engine.rb index 63a26636a0..53cbb597cd 100644 --- a/actioncable/lib/action_cable/engine.rb +++ b/actioncable/lib/action_cable/engine.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "rails" require "action_cable" require "action_cable/helpers/action_cable_helper" diff --git a/actioncable/lib/action_cable/gem_version.rb b/actioncable/lib/action_cable/gem_version.rb index 5d6f9af0bb..cd1d9bccef 100644 --- a/actioncable/lib/action_cable/gem_version.rb +++ b/actioncable/lib/action_cable/gem_version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable # Returns the version of the currently loaded Action Cable as a <tt>Gem::Version</tt>. def self.gem_version @@ -5,8 +7,8 @@ module ActionCable end module VERSION - MAJOR = 5 - MINOR = 2 + MAJOR = 6 + MINOR = 0 TINY = 0 PRE = "alpha" diff --git a/actioncable/lib/action_cable/helpers/action_cable_helper.rb b/actioncable/lib/action_cable/helpers/action_cable_helper.rb index f53be0bc31..df16c02e83 100644 --- a/actioncable/lib/action_cable/helpers/action_cable_helper.rb +++ b/actioncable/lib/action_cable/helpers/action_cable_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Helpers module ActionCableHelper diff --git a/actioncable/lib/action_cable/remote_connections.rb b/actioncable/lib/action_cable/remote_connections.rb index d2856bc6ae..283400d9e7 100644 --- a/actioncable/lib/action_cable/remote_connections.rb +++ b/actioncable/lib/action_cable/remote_connections.rb @@ -1,3 +1,7 @@ +# frozen_string_literal: true + +require "active_support/core_ext/module/redefine_method" + module ActionCable # If you need to disconnect a given connection, you can go through the # RemoteConnections. You can find the connections you're looking for by @@ -45,13 +49,14 @@ module ActionCable end # Returns all the identifiers that were applied to this connection. - def identifiers + redefine_method :identifiers do server.connection_identifiers end - private + protected attr_reader :server + private def set_identifier_instance_vars(ids) raise InvalidIdentifiersError unless valid_identifiers?(ids) ids.each { |k, v| instance_variable_set("@#{k}", v) } diff --git a/actioncable/lib/action_cable/server.rb b/actioncable/lib/action_cable/server.rb index 22f9353825..8d485a44f6 100644 --- a/actioncable/lib/action_cable/server.rb +++ b/actioncable/lib/action_cable/server.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Server extend ActiveSupport::Autoload diff --git a/actioncable/lib/action_cable/server/base.rb b/actioncable/lib/action_cable/server/base.rb index 419eccd73c..1ee03f6dfc 100644 --- a/actioncable/lib/action_cable/server/base.rb +++ b/actioncable/lib/action_cable/server/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "monitor" module ActionCable @@ -10,7 +12,7 @@ module ActionCable include ActionCable::Server::Broadcasting include ActionCable::Server::Connections - cattr_accessor(:config, instance_accessor: true) { ActionCable::Server::Configuration.new } + cattr_accessor :config, instance_accessor: true, default: ActionCable::Server::Configuration.new def self.logger; config.logger; end delegate :logger, to: :config @@ -28,7 +30,7 @@ module ActionCable config.connection_class.call.new(self, env).process end - # Disconnect all the connections identified by `identifiers` on this server or any others via RemoteConnections. + # Disconnect all the connections identified by +identifiers+ on this server or any others via RemoteConnections. def disconnect(identifiers) remote_connections.where(identifiers).disconnect end diff --git a/actioncable/lib/action_cable/server/broadcasting.rb b/actioncable/lib/action_cable/server/broadcasting.rb index 7fcd6c6587..bc54d784b3 100644 --- a/actioncable/lib/action_cable/server/broadcasting.rb +++ b/actioncable/lib/action_cable/server/broadcasting.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Server # Broadcasting is how other parts of your application can send messages to a channel's subscribers. As explained in Channel, most of the time, these diff --git a/actioncable/lib/action_cable/server/configuration.rb b/actioncable/lib/action_cable/server/configuration.rb index 17e0dee064..26209537df 100644 --- a/actioncable/lib/action_cable/server/configuration.rb +++ b/actioncable/lib/action_cable/server/configuration.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Server # An instance of this configuration object is available via ActionCable.server.config, which allows you to tweak Action Cable configuration @@ -23,13 +25,26 @@ module ActionCable # Also makes sure proper dependencies are required. def pubsub_adapter adapter = (cable.fetch("adapter") { "redis" }) + + # Require the adapter itself and give useful feedback about + # 1. Missing adapter gems and + # 2. Adapter gems' missing dependencies. path_to_adapter = "action_cable/subscription_adapter/#{adapter}" begin require path_to_adapter - rescue Gem::LoadError => e - raise Gem::LoadError, "Specified '#{adapter}' for Action Cable pubsub adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by Action Cable)." rescue LoadError => e - raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/cable.yml is valid. If you use an adapter other than 'postgresql' or 'redis' add the necessary adapter gem to the Gemfile.", e.backtrace + # We couldn't require the adapter itself. Raise an exception that + # points out config typos and missing gems. + if e.path == path_to_adapter + # We can assume that a non-builtin adapter was specified, so it's + # either misspelled or missing from Gemfile. + raise e.class, "Could not load the '#{adapter}' Action Cable pubsub adapter. Ensure that the adapter is spelled correctly in config/cable.yml and that you've added the necessary adapter gem to your Gemfile.", e.backtrace + + # Bubbled up from the adapter require. Prefix the exception message + # with some guidance about how to address it and reraise. + else + raise e.class, "Error loading the '#{adapter}' Action Cable pubsub adapter. Missing a gem it depends on? #{e.message}", e.backtrace + end end adapter = adapter.camelize diff --git a/actioncable/lib/action_cable/server/connections.rb b/actioncable/lib/action_cable/server/connections.rb index 5e61b4e335..39557d63a7 100644 --- a/actioncable/lib/action_cable/server/connections.rb +++ b/actioncable/lib/action_cable/server/connections.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Server # Collection class for all the connections that have been established on this specific server. Remember, usually you'll run many Action Cable servers, so diff --git a/actioncable/lib/action_cable/server/worker.rb b/actioncable/lib/action_cable/server/worker.rb index 43639c27af..c69cc4ac31 100644 --- a/actioncable/lib/action_cable/server/worker.rb +++ b/actioncable/lib/action_cable/server/worker.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "active_support/callbacks" require "active_support/core_ext/module/attribute_accessors_per_thread" require "concurrent" diff --git a/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb index c1e4aa8103..2e378d4bf3 100644 --- a/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb +++ b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module Server class Worker diff --git a/actioncable/lib/action_cable/subscription_adapter.rb b/actioncable/lib/action_cable/subscription_adapter.rb index 596269ab9b..bcece8d33b 100644 --- a/actioncable/lib/action_cable/subscription_adapter.rb +++ b/actioncable/lib/action_cable/subscription_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module SubscriptionAdapter extend ActiveSupport::Autoload diff --git a/actioncable/lib/action_cable/subscription_adapter/async.rb b/actioncable/lib/action_cable/subscription_adapter/async.rb index 46819dbfec..c9930299c7 100644 --- a/actioncable/lib/action_cable/subscription_adapter/async.rb +++ b/actioncable/lib/action_cable/subscription_adapter/async.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "action_cable/subscription_adapter/inline" module ActionCable diff --git a/actioncable/lib/action_cable/subscription_adapter/base.rb b/actioncable/lib/action_cable/subscription_adapter/base.rb index 796db5ffa3..34077707fd 100644 --- a/actioncable/lib/action_cable/subscription_adapter/base.rb +++ b/actioncable/lib/action_cable/subscription_adapter/base.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module SubscriptionAdapter class Base diff --git a/actioncable/lib/action_cable/subscription_adapter/channel_prefix.rb b/actioncable/lib/action_cable/subscription_adapter/channel_prefix.rb index 8b293cc785..df0aa040f5 100644 --- a/actioncable/lib/action_cable/subscription_adapter/channel_prefix.rb +++ b/actioncable/lib/action_cable/subscription_adapter/channel_prefix.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module SubscriptionAdapter module ChannelPrefix # :nodoc: diff --git a/actioncable/lib/action_cable/subscription_adapter/evented_redis.rb b/actioncable/lib/action_cable/subscription_adapter/evented_redis.rb deleted file mode 100644 index ed8f315791..0000000000 --- a/actioncable/lib/action_cable/subscription_adapter/evented_redis.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "thread" - -gem "em-hiredis", "~> 0.3.0" -gem "redis", "~> 3.0" -require "em-hiredis" -require "redis" - -EventMachine.epoll if EventMachine.epoll? -EventMachine.kqueue if EventMachine.kqueue? - -module ActionCable - module SubscriptionAdapter - class EventedRedis < Base # :nodoc: - prepend ChannelPrefix - - @@mutex = Mutex.new - - # Overwrite this factory method for EventMachine Redis connections if you want to use a different Redis connection library than EM::Hiredis. - # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:em_redis_connector) { ->(config) { EM::Hiredis.connect(config[:url]) } } - - # Overwrite this factory method for Redis connections if you want to use a different Redis connection library than Redis. - # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } } - - def initialize(*) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - The "evented_redis" subscription adapter is deprecated and - will be removed in Rails 5.2. Please use the "redis" adapter - instead. - MSG - - super - @redis_connection_for_broadcasts = @redis_connection_for_subscriptions = nil - end - - def broadcast(channel, payload) - redis_connection_for_broadcasts.publish(channel, payload) - end - - def subscribe(channel, message_callback, success_callback = nil) - redis_connection_for_subscriptions.pubsub.subscribe(channel, &message_callback).tap do |result| - result.callback { |reply| success_callback.call } if success_callback - end - end - - def unsubscribe(channel, message_callback) - redis_connection_for_subscriptions.pubsub.unsubscribe_proc(channel, message_callback) - end - - def shutdown - redis_connection_for_subscriptions.pubsub.close_connection - @redis_connection_for_subscriptions = nil - end - - private - def redis_connection_for_subscriptions - ensure_reactor_running - @redis_connection_for_subscriptions || @server.mutex.synchronize do - @redis_connection_for_subscriptions ||= self.class.em_redis_connector.call(@server.config.cable).tap do |redis| - redis.on(:reconnect_failed) do - @logger.error "[ActionCable] Redis reconnect failed." - end - - redis.on(:failed) do - @logger.error "[ActionCable] Redis connection has failed." - end - end - end - end - - def redis_connection_for_broadcasts - @redis_connection_for_broadcasts || @server.mutex.synchronize do - @redis_connection_for_broadcasts ||= self.class.redis_connector.call(@server.config.cable) - end - end - - def ensure_reactor_running - return if EventMachine.reactor_running? && EventMachine.reactor_thread - @@mutex.synchronize do - Thread.new { EventMachine.run } unless EventMachine.reactor_running? - Thread.pass until EventMachine.reactor_running? && EventMachine.reactor_thread - end - end - end - end -end diff --git a/actioncable/lib/action_cable/subscription_adapter/inline.rb b/actioncable/lib/action_cable/subscription_adapter/inline.rb index 81357faead..d2c85c1c8d 100644 --- a/actioncable/lib/action_cable/subscription_adapter/inline.rb +++ b/actioncable/lib/action_cable/subscription_adapter/inline.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module SubscriptionAdapter class Inline < Base # :nodoc: diff --git a/actioncable/lib/action_cable/subscription_adapter/postgresql.rb b/actioncable/lib/action_cable/subscription_adapter/postgresql.rb index e7be4c606e..50ec438c3a 100644 --- a/actioncable/lib/action_cable/subscription_adapter/postgresql.rb +++ b/actioncable/lib/action_cable/subscription_adapter/postgresql.rb @@ -1,6 +1,9 @@ -gem "pg", "~> 0.18" +# frozen_string_literal: true + +gem "pg", ">= 0.18", "< 2.0" require "pg" require "thread" +require "digest/sha1" module ActionCable module SubscriptionAdapter @@ -12,16 +15,16 @@ module ActionCable def broadcast(channel, payload) with_broadcast_connection do |pg_conn| - pg_conn.exec("NOTIFY #{pg_conn.escape_identifier(channel)}, '#{pg_conn.escape_string(payload)}'") + pg_conn.exec("NOTIFY #{pg_conn.escape_identifier(channel_identifier(channel))}, '#{pg_conn.escape_string(payload)}'") end end def subscribe(channel, callback, success_callback = nil) - listener.add_subscriber(channel, callback, success_callback) + listener.add_subscriber(channel_identifier(channel), callback, success_callback) end def unsubscribe(channel, callback) - listener.remove_subscriber(channel, callback) + listener.remove_subscriber(channel_identifier(channel), callback) end def shutdown @@ -51,6 +54,10 @@ module ActionCable end private + def channel_identifier(channel) + channel.size > 63 ? Digest::SHA1.hexdigest(channel) : channel + end + def listener @listener || @server.mutex.synchronize { @listener ||= Listener.new(self, @server.event_loop) } end diff --git a/actioncable/lib/action_cable/subscription_adapter/redis.rb b/actioncable/lib/action_cable/subscription_adapter/redis.rb index 41a6e55822..c28951608f 100644 --- a/actioncable/lib/action_cable/subscription_adapter/redis.rb +++ b/actioncable/lib/action_cable/subscription_adapter/redis.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require "thread" -gem "redis", "~> 3.0" +gem "redis", ">= 3", "< 5" require "redis" module ActionCable @@ -8,9 +10,11 @@ module ActionCable class Redis < Base # :nodoc: prepend ChannelPrefix - # Overwrite this factory method for redis connections if you want to use a different Redis library than Redis. + # Overwrite this factory method for Redis connections if you want to use a different Redis library than the redis gem. # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } } + cattr_accessor :redis_connector, default: ->(config) do + ::Redis.new(config.slice(:url, :host, :port, :db, :password)) + end def initialize(*) super @@ -72,7 +76,7 @@ module ActionCable def listen(conn) conn.without_reconnect do - original_client = conn.client + original_client = conn.respond_to?(:_client) ? conn._client : conn.client conn.subscribe("_action_cable_internal") do |on| on.subscribe do |chan, count| diff --git a/actioncable/lib/action_cable/subscription_adapter/subscriber_map.rb b/actioncable/lib/action_cable/subscription_adapter/subscriber_map.rb index 4cce86dcca..01cdc2dfa1 100644 --- a/actioncable/lib/action_cable/subscription_adapter/subscriber_map.rb +++ b/actioncable/lib/action_cable/subscription_adapter/subscriber_map.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActionCable module SubscriptionAdapter class SubscriberMap diff --git a/actioncable/lib/action_cable/version.rb b/actioncable/lib/action_cable/version.rb index d6081409f0..86115c6065 100644 --- a/actioncable/lib/action_cable/version.rb +++ b/actioncable/lib/action_cable/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative "gem_version" module ActionCable diff --git a/actioncable/lib/rails/generators/channel/channel_generator.rb b/actioncable/lib/rails/generators/channel/channel_generator.rb index 984b78bc9c..427eef1f55 100644 --- a/actioncable/lib/rails/generators/channel/channel_generator.rb +++ b/actioncable/lib/rails/generators/channel/channel_generator.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Rails module Generators class ChannelGenerator < NamedBase - source_root File.expand_path("../templates", __FILE__) + source_root File.expand_path("templates", __dir__) argument :actions, type: :array, default: [], banner: "method method" @@ -25,7 +27,7 @@ module Rails private def file_name - @_file_name ||= super.gsub(/_channel/i, "") + @_file_name ||= super.sub(/_channel\z/i, "") end # FIXME: Change these files to symlinks once RubyGems 2.5.0 is required. diff --git a/actioncable/lib/rails/generators/channel/templates/application_cable/channel.rb b/actioncable/lib/rails/generators/channel/templates/application_cable/channel.rb.tt index d672697283..d672697283 100644 --- a/actioncable/lib/rails/generators/channel/templates/application_cable/channel.rb +++ b/actioncable/lib/rails/generators/channel/templates/application_cable/channel.rb.tt diff --git a/actioncable/lib/rails/generators/channel/templates/application_cable/connection.rb b/actioncable/lib/rails/generators/channel/templates/application_cable/connection.rb.tt index 0ff5442f47..0ff5442f47 100644 --- a/actioncable/lib/rails/generators/channel/templates/application_cable/connection.rb +++ b/actioncable/lib/rails/generators/channel/templates/application_cable/connection.rb.tt diff --git a/actioncable/lib/rails/generators/channel/templates/assets/cable.js b/actioncable/lib/rails/generators/channel/templates/assets/cable.js.tt index 739aa5f022..739aa5f022 100644 --- a/actioncable/lib/rails/generators/channel/templates/assets/cable.js +++ b/actioncable/lib/rails/generators/channel/templates/assets/cable.js.tt diff --git a/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee b/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee.tt index 5467811aba..5467811aba 100644 --- a/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee +++ b/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee.tt diff --git a/actioncable/lib/rails/generators/channel/templates/assets/channel.js b/actioncable/lib/rails/generators/channel/templates/assets/channel.js.tt index ab0e68b11a..ab0e68b11a 100644 --- a/actioncable/lib/rails/generators/channel/templates/assets/channel.js +++ b/actioncable/lib/rails/generators/channel/templates/assets/channel.js.tt diff --git a/actioncable/lib/rails/generators/channel/templates/channel.rb b/actioncable/lib/rails/generators/channel/templates/channel.rb.tt index 4bcfb2be4d..4bcfb2be4d 100644 --- a/actioncable/lib/rails/generators/channel/templates/channel.rb +++ b/actioncable/lib/rails/generators/channel/templates/channel.rb.tt diff --git a/actioncable/package.json b/actioncable/package.json index acec1e2e9c..d9df46043d 100644 --- a/actioncable/package.json +++ b/actioncable/package.json @@ -1,6 +1,6 @@ { "name": "actioncable", - "version": "5.2.0-alpha", + "version": "6.0.0-alpha", "description": "WebSocket framework for Ruby on Rails.", "main": "lib/assets/compiled/action_cable.js", "files": [ diff --git a/actioncable/test/channel/base_test.rb b/actioncable/test/channel/base_test.rb index 9a3a3581e6..d368794f73 100644 --- a/actioncable/test/channel/base_test.rb +++ b/actioncable/test/channel/base_test.rb @@ -1,4 +1,7 @@ +# frozen_string_literal: true + require "test_helper" +require "minitest/mock" require "stubs/test_connection" require "stubs/room" @@ -95,12 +98,12 @@ class ActionCable::Channel::BaseTest < ActiveSupport::TestCase @channel.subscribe_to_channel assert @channel.room - assert @channel.subscribed? + assert_predicate @channel, :subscribed? @channel.unsubscribe_from_channel - assert ! @channel.room - assert ! @channel.subscribed? + assert_not @channel.room + assert_not_predicate @channel, :subscribed? end test "connection identifiers" do @@ -224,12 +227,13 @@ class ActionCable::Channel::BaseTest < ActiveSupport::TestCase events << ActiveSupport::Notifications::Event.new(*args) end - @channel.stubs(:subscription_confirmation_sent?).returns(false) - @channel.send(:transmit_subscription_confirmation) + @channel.stub(:subscription_confirmation_sent?, false) do + @channel.send(:transmit_subscription_confirmation) - assert_equal 1, events.length - assert_equal "transmit_subscription_confirmation.action_cable", events[0].name - assert_equal "ActionCable::Channel::BaseTest::ChatChannel", events[0].payload[:channel_class] + assert_equal 1, events.length + assert_equal "transmit_subscription_confirmation.action_cable", events[0].name + assert_equal "ActionCable::Channel::BaseTest::ChatChannel", events[0].payload[:channel_class] + end ensure ActiveSupport::Notifications.unsubscribe "transmit_subscription_confirmation.action_cable" end diff --git a/actioncable/test/channel/broadcasting_test.rb b/actioncable/test/channel/broadcasting_test.rb index 3476c1db31..f184147c51 100644 --- a/actioncable/test/channel/broadcasting_test.rb +++ b/actioncable/test/channel/broadcasting_test.rb @@ -1,8 +1,13 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" require "stubs/test_connection" require "stubs/room" class ActionCable::Channel::BroadcastingTest < ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class ChatChannel < ActionCable::Channel::Base end @@ -11,8 +16,16 @@ class ActionCable::Channel::BroadcastingTest < ActiveSupport::TestCase end test "broadcasts_to" do - ActionCable.stubs(:server).returns mock().tap { |m| m.expects(:broadcast).with("action_cable:channel:broadcasting_test:chat:Room#1-Campfire", "Hello World") } - ChatChannel.broadcast_to(Room.new(1), "Hello World") + assert_called_with( + ActionCable.server, + :broadcast, + [ + "action_cable:channel:broadcasting_test:chat:Room#1-Campfire", + "Hello World" + ] + ) do + ChatChannel.broadcast_to(Room.new(1), "Hello World") + end end test "broadcasting_for with an object" do diff --git a/actioncable/test/channel/naming_test.rb b/actioncable/test/channel/naming_test.rb index 08f0e7be48..6f094fbb5e 100644 --- a/actioncable/test/channel/naming_test.rb +++ b/actioncable/test/channel/naming_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class ActionCable::Channel::NamingTest < ActiveSupport::TestCase diff --git a/actioncable/test/channel/periodic_timers_test.rb b/actioncable/test/channel/periodic_timers_test.rb index 17a8e45a35..8d9482577c 100644 --- a/actioncable/test/channel/periodic_timers_test.rb +++ b/actioncable/test/channel/periodic_timers_test.rb @@ -1,9 +1,14 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_connection" require "stubs/room" require "active_support/time" +require "active_support/testing/method_call_assertions" class ActionCable::Channel::PeriodicTimersTest < ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class ChatChannel < ActionCable::Channel::Base # Method name arg periodically :send_updates, every: 1 @@ -62,11 +67,22 @@ class ActionCable::Channel::PeriodicTimersTest < ActiveSupport::TestCase end test "timer start and stop" do - @connection.server.event_loop.expects(:timer).times(3).returns(stub(shutdown: nil)) - channel = ChatChannel.new @connection, "{id: 1}", id: 1 + mock = Minitest::Mock.new + 3.times { mock.expect(:shutdown, nil) } + + assert_called( + @connection.server.event_loop, + :timer, + times: 3, + returns: mock + ) do + channel = ChatChannel.new @connection, "{id: 1}", id: 1 + + channel.subscribe_to_channel + channel.unsubscribe_from_channel + assert_equal [], channel.send(:active_periodic_timers) + end - channel.subscribe_to_channel - channel.unsubscribe_from_channel - assert_equal [], channel.send(:active_periodic_timers) + assert mock.verify end end diff --git a/actioncable/test/channel/rejection_test.rb b/actioncable/test/channel/rejection_test.rb index 99c4a7603a..897efeb65a 100644 --- a/actioncable/test/channel/rejection_test.rb +++ b/actioncable/test/channel/rejection_test.rb @@ -1,4 +1,7 @@ +# frozen_string_literal: true + require "test_helper" +require "minitest/mock" require "stubs/test_connection" require "stubs/room" @@ -18,24 +21,36 @@ class ActionCable::Channel::RejectionTest < ActiveSupport::TestCase end test "subscription rejection" do - @connection.expects(:subscriptions).returns mock().tap { |m| m.expects(:remove_subscription).with instance_of(SecretChannel) } - @channel = SecretChannel.new @connection, "{id: 1}", id: 1 - @channel.subscribe_to_channel + subscriptions = Minitest::Mock.new + subscriptions.expect(:remove_subscription, SecretChannel, [SecretChannel]) + + @connection.stub(:subscriptions, subscriptions) do + @channel = SecretChannel.new @connection, "{id: 1}", id: 1 + @channel.subscribe_to_channel + + expected = { "identifier" => "{id: 1}", "type" => "reject_subscription" } + assert_equal expected, @connection.last_transmission + end - expected = { "identifier" => "{id: 1}", "type" => "reject_subscription" } - assert_equal expected, @connection.last_transmission + assert subscriptions.verify end test "does not execute action if subscription is rejected" do - @connection.expects(:subscriptions).returns mock().tap { |m| m.expects(:remove_subscription).with instance_of(SecretChannel) } - @channel = SecretChannel.new @connection, "{id: 1}", id: 1 - @channel.subscribe_to_channel + subscriptions = Minitest::Mock.new + subscriptions.expect(:remove_subscription, SecretChannel, [SecretChannel]) - expected = { "identifier" => "{id: 1}", "type" => "reject_subscription" } - assert_equal expected, @connection.last_transmission - assert_equal 1, @connection.transmissions.size + @connection.stub(:subscriptions, subscriptions) do + @channel = SecretChannel.new @connection, "{id: 1}", id: 1 + @channel.subscribe_to_channel + + expected = { "identifier" => "{id: 1}", "type" => "reject_subscription" } + assert_equal expected, @connection.last_transmission + assert_equal 1, @connection.transmissions.size + + @channel.perform_action("action" => :secret_action) + assert_equal 1, @connection.transmissions.size + end - @channel.perform_action("action" => :secret_action) - assert_equal 1, @connection.transmissions.size + assert subscriptions.verify end end diff --git a/actioncable/test/channel/stream_test.rb b/actioncable/test/channel/stream_test.rb index 50fc7be30b..ed42f1acd4 100644 --- a/actioncable/test/channel/stream_test.rb +++ b/actioncable/test/channel/stream_test.rb @@ -1,4 +1,8 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" +require "minitest/mock" require "stubs/test_connection" require "stubs/room" @@ -51,39 +55,58 @@ module ActionCable::StreamTests test "streaming start and stop" do run_in_eventmachine do connection = TestConnection.new - connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) } - channel = ChatChannel.new connection, "{id: 1}", id: 1 - channel.subscribe_to_channel + pubsub = Minitest::Mock.new connection.pubsub - wait_for_async + pubsub.expect(:subscribe, nil, ["test_room_1", Proc, Proc]) + pubsub.expect(:unsubscribe, nil, ["test_room_1", Proc]) - connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) } - channel.unsubscribe_from_channel + connection.stub(:pubsub, pubsub) do + channel = ChatChannel.new connection, "{id: 1}", id: 1 + channel.subscribe_to_channel + + wait_for_async + channel.unsubscribe_from_channel + end + + assert pubsub.verify end end test "stream from non-string channel" do run_in_eventmachine do connection = TestConnection.new - connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("channel", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) } - channel = SymbolChannel.new connection, "" - channel.subscribe_to_channel + pubsub = Minitest::Mock.new connection.pubsub - wait_for_async + pubsub.expect(:subscribe, nil, ["channel", Proc, Proc]) + pubsub.expect(:unsubscribe, nil, ["channel", Proc]) + + connection.stub(:pubsub, pubsub) do + channel = SymbolChannel.new connection, "" + channel.subscribe_to_channel + + wait_for_async - connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) } - channel.unsubscribe_from_channel + channel.unsubscribe_from_channel + end + + assert pubsub.verify end end test "stream_for" do run_in_eventmachine do connection = TestConnection.new - connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("action_cable:stream_tests:chat:Room#1-Campfire", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) } channel = ChatChannel.new connection, "" channel.subscribe_to_channel channel.stream_for Room.new(1) + wait_for_async + + pubsub_call = channel.pubsub.class.class_variable_get "@@subscribe_called" + + assert_equal "action_cable:stream_tests:chat:Room#1-Campfire", pubsub_call[:channel] + assert_instance_of Proc, pubsub_call[:callback] + assert_instance_of Proc, pubsub_call[:success_callback] end end @@ -141,6 +164,8 @@ module ActionCable::StreamTests end class StreamFromTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + setup do @server = TestServer.new(subscription_adapter: ActionCable::SubscriptionAdapter::Async) @server.config.allowed_request_origins = %w( http://rubyonrails.com ) @@ -151,10 +176,11 @@ module ActionCable::StreamTests connection = open_connection subscribe_to connection, identifiers: { id: 1 } - connection.websocket.expects(:transmit) - @server.broadcast "test_room_1", { foo: "bar" }, coder: DummyEncoder - wait_for_async - wait_for_executor connection.server.worker_pool.executor + assert_called(connection.websocket, :transmit) do + @server.broadcast "test_room_1", { foo: "bar" }, { coder: DummyEncoder } + wait_for_async + wait_for_executor connection.server.worker_pool.executor + end end end @@ -165,7 +191,7 @@ module ActionCable::StreamTests @server.broadcast "channel", {} wait_for_async - refute Thread.current[:ran_callback], "User callback was not run through the worker pool" + assert_not Thread.current[:ran_callback], "User callback was not run through the worker pool" end end @@ -173,10 +199,10 @@ module ActionCable::StreamTests run_in_eventmachine do connection = open_connection expected = { "identifier" => { "channel" => MultiChatChannel.name }.to_json, "type" => "confirm_subscription" } - connection.websocket.expects(:transmit).with(expected.to_json) - receive(connection, command: "subscribe", channel: MultiChatChannel.name, identifiers: {}) - - wait_for_async + assert_called_with(connection.websocket, :transmit, [expected.to_json]) do + receive(connection, command: "subscribe", channel: MultiChatChannel.name, identifiers: {}) + wait_for_async + end end end @@ -190,15 +216,15 @@ module ActionCable::StreamTests Connection.new(@server, env).tap do |connection| connection.process - assert connection.websocket.possible? + assert_predicate connection.websocket, :possible? wait_for_async - assert connection.websocket.alive? + assert_predicate connection.websocket, :alive? end end def receive(connection, command:, identifiers:, channel: "ActionCable::StreamTests::ChatChannel") - identifier = JSON.generate(channel: channel, **identifiers) + identifier = JSON.generate(identifiers.merge(channel: channel)) connection.dispatch_websocket_message JSON.generate(command: command, identifier: identifier) wait_for_async end diff --git a/actioncable/test/client_test.rb b/actioncable/test/client_test.rb index 98a114a5f4..92fe59c803 100644 --- a/actioncable/test/client_test.rb +++ b/actioncable/test/client_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "concurrent" @@ -5,6 +7,7 @@ require "websocket-client-simple" require "json" require "active_support/hash_with_indifferent_access" +require "active_support/testing/method_call_assertions" #### # 😷 Warning suppression 😷 @@ -25,6 +28,8 @@ WebSocket::Frame::Data.prepend Module.new { #### class ClientTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + WAIT_WHEN_EXPECTING_EVENT = 2 WAIT_WHEN_NOT_EXPECTING_EVENT = 0.5 @@ -68,12 +73,33 @@ class ClientTest < ActionCable::TestCase server.min_threads = 1 server.max_threads = 4 - t = Thread.new { server.run.join } - yield port + thread = server.run + + begin + yield port + + ensure + server.stop + + begin + thread.join + + rescue IOError + # Work around https://bugs.ruby-lang.org/issues/13405 + # + # Puma's sometimes raising while shutting down, when it closes + # its internal pipe. We can safely ignore that, but we do need + # to do the step skipped by the exception: + server.binder.close - ensure - server.stop(true) if server - t.join if t + rescue RuntimeError => ex + # Work around https://bugs.ruby-lang.org/issues/13239 + raise unless ex.message =~ /can't modify frozen IOError/ + + # Handle this as if it were the IOError: do the same as above. + server.binder.close + end + end end class SyncClient @@ -266,9 +292,10 @@ class ClientTest < ActionCable::TestCase subscriptions = app.connections.first.subscriptions.send(:subscriptions) assert_not_equal 0, subscriptions.size, "Missing EchoChannel subscription" channel = subscriptions.first[1] - channel.expects(:unsubscribed) - c.close - sleep 0.1 # Data takes a moment to process + assert_called(channel, :unsubscribed) do + c.close + sleep 0.1 # Data takes a moment to process + end # All data is removed: No more connection or subscription information! assert_equal(0, app.connections.count) @@ -284,7 +311,7 @@ class ClientTest < ActionCable::TestCase ActionCable.server.restart c.wait_for_close - assert c.closed? + assert_predicate c, :closed? end end end diff --git a/actioncable/test/connection/authorization_test.rb b/actioncable/test/connection/authorization_test.rb index dcdbe9c1d1..be41d510ff 100644 --- a/actioncable/test/connection/authorization_test.rb +++ b/actioncable/test/connection/authorization_test.rb @@ -1,7 +1,12 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" require "stubs/test_server" class ActionCable::Connection::AuthorizationTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base attr_reader :websocket @@ -23,9 +28,9 @@ class ActionCable::Connection::AuthorizationTest < ActionCable::TestCase "HTTP_HOST" => "localhost", "HTTP_ORIGIN" => "http://rubyonrails.com" connection = Connection.new(server, env) - connection.websocket.expects(:close) - - connection.process + assert_called(connection.websocket, :close) do + connection.process + end end end end diff --git a/actioncable/test/connection/base_test.rb b/actioncable/test/connection/base_test.rb index 9bcd0700cf..9e480ab60d 100644 --- a/actioncable/test/connection/base_test.rb +++ b/actioncable/test/connection/base_test.rb @@ -1,8 +1,13 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" require "active_support/core_ext/object/json" +require "active_support/testing/method_call_assertions" class ActionCable::Connection::BaseTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base attr_reader :websocket, :subscriptions, :message_buffer, :connected @@ -37,10 +42,10 @@ class ActionCable::Connection::BaseTest < ActionCable::TestCase connection = open_connection connection.process - assert connection.websocket.possible? + assert_predicate connection.websocket, :possible? wait_for_async - assert connection.websocket.alive? + assert_predicate connection.websocket, :alive? end end @@ -57,11 +62,12 @@ class ActionCable::Connection::BaseTest < ActionCable::TestCase run_in_eventmachine do connection = open_connection - connection.websocket.expects(:transmit).with({ type: "welcome" }.to_json) - connection.message_buffer.expects(:process!) - - connection.process - wait_for_async + assert_called_with(connection.websocket, :transmit, [{ type: "welcome" }.to_json]) do + assert_called(connection.message_buffer, :process!) do + connection.process + wait_for_async + end + end assert_equal [ connection ], @server.connections assert connection.connected @@ -74,14 +80,14 @@ class ActionCable::Connection::BaseTest < ActionCable::TestCase connection.process # Setup the connection - connection.server.stubs(:timer).returns(true) connection.send :handle_open assert connection.connected - connection.subscriptions.expects(:unsubscribe_from_all) - connection.send :handle_close + assert_called(connection.subscriptions, :unsubscribe_from_all) do + connection.send :handle_close + end - assert ! connection.connected + assert_not connection.connected assert_equal [], @server.connections end end @@ -93,7 +99,7 @@ class ActionCable::Connection::BaseTest < ActionCable::TestCase statistics = connection.statistics - assert statistics[:identifier].blank? + assert_predicate statistics[:identifier], :blank? assert_kind_of Time, statistics[:started_at] assert_equal [], statistics[:subscriptions] end @@ -104,8 +110,9 @@ class ActionCable::Connection::BaseTest < ActionCable::TestCase connection = open_connection connection.process - connection.websocket.expects(:close) - connection.close + assert_called(connection.websocket, :close) do + connection.close + end end end diff --git a/actioncable/test/connection/client_socket_test.rb b/actioncable/test/connection/client_socket_test.rb index bc3ff6a3d7..07bdc7c52a 100644 --- a/actioncable/test/connection/client_socket_test.rb +++ b/actioncable/test/connection/client_socket_test.rb @@ -1,7 +1,12 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" +require "active_support/testing/method_call_assertions" class ActionCable::Connection::ClientSocketTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base attr_reader :connected, :websocket, :errors @@ -38,10 +43,12 @@ class ActionCable::Connection::ClientSocketTest < ActionCable::TestCase # Internal hax = :( client = connection.websocket.send(:websocket) - client.instance_variable_get("@stream").expects(:write).raises("foo") - client.expects(:client_gone).never + client.instance_variable_get("@stream").stub(:write, proc { raise "foo" }) do - client.write("boo") + assert_not_called(client, :client_gone) do + client.write("boo") + end + end assert_equal %w[ foo ], connection.errors end end @@ -65,9 +72,9 @@ class ActionCable::Connection::ClientSocketTest < ActionCable::TestCase env = Rack::MockRequest.env_for "/test", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket", "HTTP_HOST" => "localhost", "HTTP_ORIGIN" => "http://rubyonrails.com" - io = \ + io, client_io = \ begin - Socket.pair(Socket::AF_UNIX, Socket::SOCK_STREAM, 0).first + Socket.pair(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) rescue StringIO.new end @@ -75,6 +82,14 @@ class ActionCable::Connection::ClientSocketTest < ActionCable::TestCase Connection.new(@server, env).tap do |connection| connection.process + if client_io + # Make sure server returns handshake response + Timeout.timeout(1) do + loop do + break if client_io.readline == "\r\n" + end + end + end connection.send :handle_open assert connection.connected end diff --git a/actioncable/test/connection/cross_site_forgery_test.rb b/actioncable/test/connection/cross_site_forgery_test.rb index 37bedfd734..3e21138ffc 100644 --- a/actioncable/test/connection/cross_site_forgery_test.rb +++ b/actioncable/test/connection/cross_site_forgery_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" diff --git a/actioncable/test/connection/identifier_test.rb b/actioncable/test/connection/identifier_test.rb index f3d3bc0603..a7e23b4cd8 100644 --- a/actioncable/test/connection/identifier_test.rb +++ b/actioncable/test/connection/identifier_test.rb @@ -1,8 +1,13 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" require "stubs/test_server" require "stubs/user" class ActionCable::Connection::IdentifierTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base identified_by :current_user attr_reader :websocket @@ -16,52 +21,52 @@ class ActionCable::Connection::IdentifierTest < ActionCable::TestCase test "connection identifier" do run_in_eventmachine do - open_connection_with_stubbed_pubsub + open_connection assert_equal "User#lifo", @connection.connection_identifier end end test "should subscribe to internal channel on open and unsubscribe on close" do run_in_eventmachine do - pubsub = mock("pubsub_adapter") - pubsub.expects(:subscribe).with("action_cable/User#lifo", kind_of(Proc)) - pubsub.expects(:unsubscribe).with("action_cable/User#lifo", kind_of(Proc)) - server = TestServer.new - server.stubs(:pubsub).returns(pubsub) - open_connection server: server + open_connection(server) close_connection + wait_for_async + + %w[subscribe unsubscribe].each do |method| + pubsub_call = server.pubsub.class.class_variable_get "@@#{method}_called" + + assert_equal "action_cable/User#lifo", pubsub_call[:channel] + assert_instance_of Proc, pubsub_call[:callback] + end end end test "processing disconnect message" do run_in_eventmachine do - open_connection_with_stubbed_pubsub + open_connection - @connection.websocket.expects(:close) - @connection.process_internal_message "type" => "disconnect" + assert_called(@connection.websocket, :close) do + @connection.process_internal_message "type" => "disconnect" + end end end test "processing invalid message" do run_in_eventmachine do - open_connection_with_stubbed_pubsub + open_connection - @connection.websocket.expects(:close).never - @connection.process_internal_message "type" => "unknown" + assert_not_called(@connection.websocket, :close) do + @connection.process_internal_message "type" => "unknown" + end end end private - def open_connection_with_stubbed_pubsub - server = TestServer.new - server.stubs(:adapter).returns(stub_everything("adapter")) - - open_connection server: server - end + def open_connection(server = nil) + server ||= TestServer.new - def open_connection(server:) env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket" @connection = Connection.new(server, env) diff --git a/actioncable/test/connection/multiple_identifiers_test.rb b/actioncable/test/connection/multiple_identifiers_test.rb index ca1a08f4d6..51716410b2 100644 --- a/actioncable/test/connection/multiple_identifiers_test.rb +++ b/actioncable/test/connection/multiple_identifiers_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" require "stubs/user" @@ -14,28 +16,19 @@ class ActionCable::Connection::MultipleIdentifiersTest < ActionCable::TestCase test "multiple connection identifiers" do run_in_eventmachine do - open_connection_with_stubbed_pubsub + open_connection + assert_equal "Room#my-room:User#lifo", @connection.connection_identifier end end private - def open_connection_with_stubbed_pubsub + def open_connection server = TestServer.new - server.stubs(:pubsub).returns(stub_everything("pubsub")) - - open_connection server: server - end - - def open_connection(server:) env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket" @connection = Connection.new(server, env) @connection.process @connection.send :handle_open end - - def close_connection - @connection.send :handle_close - end end diff --git a/actioncable/test/connection/stream_test.rb b/actioncable/test/connection/stream_test.rb index 36e1d3c095..daf7c37c79 100644 --- a/actioncable/test/connection/stream_test.rb +++ b/actioncable/test/connection/stream_test.rb @@ -1,7 +1,13 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" +require "minitest/mock" require "stubs/test_server" class ActionCable::Connection::StreamTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base attr_reader :connected, :websocket, :errors @@ -39,10 +45,12 @@ class ActionCable::Connection::StreamTest < ActionCable::TestCase # Internal hax = :( client = connection.websocket.send(:websocket) - client.instance_variable_get("@stream").instance_variable_get("@rack_hijack_io").expects(:write).raises(closed_exception, "foo") - client.expects(:client_gone) - - client.write("boo") + rack_hijack_io = client.instance_variable_get("@stream").instance_variable_get("@rack_hijack_io") + rack_hijack_io.stub(:write, proc { raise(closed_exception, "foo") }) do + assert_called(client, :client_gone) do + client.write("boo") + end + end assert_equal [], connection.errors end end diff --git a/actioncable/test/connection/string_identifier_test.rb b/actioncable/test/connection/string_identifier_test.rb index 6d53e249cb..f7019b926a 100644 --- a/actioncable/test/connection/string_identifier_test.rb +++ b/actioncable/test/connection/string_identifier_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" @@ -16,28 +18,19 @@ class ActionCable::Connection::StringIdentifierTest < ActionCable::TestCase test "connection identifier" do run_in_eventmachine do - open_connection_with_stubbed_pubsub + open_connection + assert_equal "random-string", @connection.connection_identifier end end private - def open_connection_with_stubbed_pubsub - @server = TestServer.new - @server.stubs(:pubsub).returns(stub_everything("pubsub")) - - open_connection - end - def open_connection + server = TestServer.new env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket" - @connection = Connection.new(@server, env) + @connection = Connection.new(server, env) @connection.process @connection.send :on_open end - - def close_connection - @connection.send :on_close - end end diff --git a/actioncable/test/connection/subscriptions_test.rb b/actioncable/test/connection/subscriptions_test.rb index a1c8a4613c..7bc8c4241c 100644 --- a/actioncable/test/connection/subscriptions_test.rb +++ b/actioncable/test/connection/subscriptions_test.rb @@ -1,6 +1,11 @@ +# frozen_string_literal: true + require "test_helper" +require "active_support/testing/method_call_assertions" class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase + include ActiveSupport::Testing::MethodCallAssertions + class Connection < ActionCable::Connection::Base attr_reader :websocket @@ -43,7 +48,7 @@ class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase setup_connection @subscriptions.execute_command "command" => "subscribe" - assert @subscriptions.identifiers.empty? + assert_empty @subscriptions.identifiers end end @@ -53,10 +58,12 @@ class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase subscribe_to_chat_channel channel = subscribe_to_chat_channel - channel.expects(:unsubscribe_from_channel) - @subscriptions.execute_command "command" => "unsubscribe", "identifier" => @chat_identifier - assert @subscriptions.identifiers.empty? + assert_called(channel, :unsubscribe_from_channel) do + @subscriptions.execute_command "command" => "unsubscribe", "identifier" => @chat_identifier + end + + assert_empty @subscriptions.identifiers end end @@ -65,7 +72,7 @@ class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase setup_connection @subscriptions.execute_command "command" => "unsubscribe" - assert @subscriptions.identifiers.empty? + assert_empty @subscriptions.identifiers end end @@ -90,10 +97,11 @@ class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase channel2_id = ActiveSupport::JSON.encode(id: 2, channel: "ActionCable::Connection::SubscriptionsTest::ChatChannel") channel2 = subscribe_to_chat_channel(channel2_id) - channel1.expects(:unsubscribe_from_channel) - channel2.expects(:unsubscribe_from_channel) - - @subscriptions.unsubscribe_from_all + assert_called(channel1, :unsubscribe_from_channel) do + assert_called(channel2, :unsubscribe_from_channel) do + @subscriptions.unsubscribe_from_all + end + end end end diff --git a/actioncable/test/server/base_test.rb b/actioncable/test/server/base_test.rb index f0a51c5a7d..3b5931f0a4 100644 --- a/actioncable/test/server/base_test.rb +++ b/actioncable/test/server/base_test.rb @@ -1,8 +1,13 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" require "active_support/core_ext/hash/indifferent_access" +require "active_support/testing/method_call_assertions" class BaseTest < ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions + def setup @server = ActionCable::Server::Base.new @server.config.cable = { adapter: "async" }.with_indifferent_access @@ -17,17 +22,20 @@ class BaseTest < ActiveSupport::TestCase conn = FakeConnection.new @server.add_connection(conn) - conn.expects(:close) - @server.restart + assert_called(conn, :close) do + @server.restart + end end test "#restart shuts down worker pool" do - @server.worker_pool.expects(:halt) - @server.restart + assert_called(@server.worker_pool, :halt) do + @server.restart + end end test "#restart shuts down pub/sub adapter" do - @server.pubsub.expects(:shutdown) - @server.restart + assert_called(@server.pubsub, :shutdown) do + @server.restart + end end end diff --git a/actioncable/test/server/broadcasting_test.rb b/actioncable/test/server/broadcasting_test.rb index ed377b7d5d..72cec26234 100644 --- a/actioncable/test/server/broadcasting_test.rb +++ b/actioncable/test/server/broadcasting_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" diff --git a/actioncable/test/stubs/global_id.rb b/actioncable/test/stubs/global_id.rb index 334f0d03e8..15fab6b8a7 100644 --- a/actioncable/test/stubs/global_id.rb +++ b/actioncable/test/stubs/global_id.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class GlobalID attr_reader :uri delegate :to_param, :to_s, to: :uri diff --git a/actioncable/test/stubs/room.rb b/actioncable/test/stubs/room.rb index 1664b07d12..df7236f408 100644 --- a/actioncable/test/stubs/room.rb +++ b/actioncable/test/stubs/room.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Room attr_reader :id, :name diff --git a/actioncable/test/stubs/test_adapter.rb b/actioncable/test/stubs/test_adapter.rb index bbd142b287..5f23a137ea 100644 --- a/actioncable/test/stubs/test_adapter.rb +++ b/actioncable/test/stubs/test_adapter.rb @@ -1,10 +1,16 @@ +# frozen_string_literal: true + class SuccessAdapter < ActionCable::SubscriptionAdapter::Base + class << self; attr_accessor :subscribe_called, :unsubscribe_called end + def broadcast(channel, payload) end def subscribe(channel, callback, success_callback = nil) + @@subscribe_called = { channel: channel, callback: callback, success_callback: success_callback } end def unsubscribe(channel, callback) + @@unsubscribe_called = { channel: channel, callback: callback } end end diff --git a/actioncable/test/stubs/test_connection.rb b/actioncable/test/stubs/test_connection.rb index cd2e219d88..155c68e38c 100644 --- a/actioncable/test/stubs/test_connection.rb +++ b/actioncable/test/stubs/test_connection.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + require "stubs/user" class TestConnection - attr_reader :identifiers, :logger, :current_user, :server, :transmissions + attr_reader :identifiers, :logger, :current_user, :server, :subscriptions, :transmissions delegate :pubsub, to: :server diff --git a/actioncable/test/stubs/test_server.rb b/actioncable/test/stubs/test_server.rb index 5bf2a151dc..0bc4625e28 100644 --- a/actioncable/test/stubs/test_server.rb +++ b/actioncable/test/stubs/test_server.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "ostruct" class TestServer diff --git a/actioncable/test/stubs/user.rb b/actioncable/test/stubs/user.rb index a66b4f87d5..7894d1d9ae 100644 --- a/actioncable/test/stubs/user.rb +++ b/actioncable/test/stubs/user.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class User attr_reader :name diff --git a/actioncable/test/subscription_adapter/async_test.rb b/actioncable/test/subscription_adapter/async_test.rb index 7bc2e55d40..6e038259b5 100644 --- a/actioncable/test/subscription_adapter/async_test.rb +++ b/actioncable/test/subscription_adapter/async_test.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + require "test_helper" -require_relative "./common" +require_relative "common" class AsyncAdapterTest < ActionCable::TestCase include CommonSubscriptionAdapterTest diff --git a/actioncable/test/subscription_adapter/base_test.rb b/actioncable/test/subscription_adapter/base_test.rb index 212ea49d2f..999dc0cba1 100644 --- a/actioncable/test/subscription_adapter/base_test.rb +++ b/actioncable/test/subscription_adapter/base_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "stubs/test_server" @@ -39,35 +41,25 @@ class ActionCable::SubscriptionAdapter::BaseTest < ActionCable::TestCase # TEST METHODS THAT ARE REQUIRED OF THE ADAPTER'S BACKEND STORAGE OBJECT test "#broadcast is implemented" do - broadcast = SuccessAdapter.new(@server).broadcast("channel", "payload") - - assert_respond_to(SuccessAdapter.new(@server), :broadcast) - assert_nothing_raised do - broadcast + SuccessAdapter.new(@server).broadcast("channel", "payload") end end test "#subscribe is implemented" do callback = lambda { puts "callback" } success_callback = lambda { puts "success" } - subscribe = SuccessAdapter.new(@server).subscribe("channel", callback, success_callback) - - assert_respond_to(SuccessAdapter.new(@server), :subscribe) assert_nothing_raised do - subscribe + SuccessAdapter.new(@server).subscribe("channel", callback, success_callback) end end test "#unsubscribe is implemented" do callback = lambda { puts "callback" } - unsubscribe = SuccessAdapter.new(@server).unsubscribe("channel", callback) - - assert_respond_to(SuccessAdapter.new(@server), :unsubscribe) assert_nothing_raised do - unsubscribe + SuccessAdapter.new(@server).unsubscribe("channel", callback) end end end diff --git a/actioncable/test/subscription_adapter/channel_prefix.rb b/actioncable/test/subscription_adapter/channel_prefix.rb index 9ad659912e..3071facd9d 100644 --- a/actioncable/test/subscription_adapter/channel_prefix.rb +++ b/actioncable/test/subscription_adapter/channel_prefix.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class ActionCable::Server::WithIndependentConfig < ActionCable::Server::Base diff --git a/actioncable/test/subscription_adapter/common.rb b/actioncable/test/subscription_adapter/common.rb index 3aa88c2caa..b3e9ae9d5c 100644 --- a/actioncable/test/subscription_adapter/common.rb +++ b/actioncable/test/subscription_adapter/common.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" require "concurrent" @@ -30,7 +32,7 @@ module CommonSubscriptionAdapterTest subscribed = Concurrent::Event.new adapter.subscribe(channel, callback, Proc.new { subscribed.set }) subscribed.wait(WAIT_WHEN_EXPECTING_EVENT) - assert subscribed.set? + assert_predicate subscribed, :set? yield queue @@ -112,4 +114,18 @@ module CommonSubscriptionAdapterTest assert_equal "two", queue.pop end end + + def test_long_identifiers + channel_1 = "a" * 100 + "1" + channel_2 = "a" * 100 + "2" + subscribe_as_queue(channel_1) do |queue| + subscribe_as_queue(channel_2) do |queue_2| + @tx_adapter.broadcast(channel_1, "apples") + @tx_adapter.broadcast(channel_2, "oranges") + + assert_equal "apples", queue.pop + assert_equal "oranges", queue_2.pop + end + end + end end diff --git a/actioncable/test/subscription_adapter/evented_redis_test.rb b/actioncable/test/subscription_adapter/evented_redis_test.rb deleted file mode 100644 index 256458bc24..0000000000 --- a/actioncable/test/subscription_adapter/evented_redis_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require "test_helper" -require_relative "./common" -require_relative "./channel_prefix" - -class EventedRedisAdapterTest < ActionCable::TestCase - include CommonSubscriptionAdapterTest - include ChannelPrefixTest - - def setup - assert_deprecated do - super - end - - # em-hiredis is warning-rich - @previous_verbose, $VERBOSE = $VERBOSE, nil - end - - def teardown - super - - # Ensure EM is shut down before we re-enable warnings - EventMachine.reactor_thread.tap do |thread| - EventMachine.stop - thread.join - end - - $VERBOSE = @previous_verbose - end - - def test_slow_eventmachine - require "eventmachine" - require "thread" - - lock = Mutex.new - - EventMachine.singleton_class.class_eval do - alias_method :delayed_initialize_event_machine, :initialize_event_machine - define_method(:initialize_event_machine) do - lock.synchronize do - sleep 0.5 - delayed_initialize_event_machine - end - end - end - - test_basic_broadcast - ensure - lock.synchronize do - EventMachine.singleton_class.class_eval do - alias_method :initialize_event_machine, :delayed_initialize_event_machine - remove_method :delayed_initialize_event_machine - end - end - end - - def cable_config - { adapter: "evented_redis", url: "redis://127.0.0.1:6379/12" } - end -end diff --git a/actioncable/test/subscription_adapter/inline_test.rb b/actioncable/test/subscription_adapter/inline_test.rb index 52bfa00aba..6305626b2b 100644 --- a/actioncable/test/subscription_adapter/inline_test.rb +++ b/actioncable/test/subscription_adapter/inline_test.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + require "test_helper" -require_relative "./common" +require_relative "common" class InlineAdapterTest < ActionCable::TestCase include CommonSubscriptionAdapterTest diff --git a/actioncable/test/subscription_adapter/postgresql_test.rb b/actioncable/test/subscription_adapter/postgresql_test.rb index 7c2608a7b8..5fb26a8896 100644 --- a/actioncable/test/subscription_adapter/postgresql_test.rb +++ b/actioncable/test/subscription_adapter/postgresql_test.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + require "test_helper" -require_relative "./common" +require_relative "common" require "active_record" @@ -12,7 +14,7 @@ class PostgresqlAdapterTest < ActionCable::TestCase if Dir.exist?(ar_tests) require File.join(ar_tests, "config") require File.join(ar_tests, "support/config") - local_config = ARTest.config["arunit"] + local_config = ARTest.config["connections"]["postgresql"]["arunit"] database_config.update local_config if local_config end diff --git a/actioncable/test/subscription_adapter/redis_test.rb b/actioncable/test/subscription_adapter/redis_test.rb index 4df5e0cbcd..63823d6ef0 100644 --- a/actioncable/test/subscription_adapter/redis_test.rb +++ b/actioncable/test/subscription_adapter/redis_test.rb @@ -1,13 +1,18 @@ +# frozen_string_literal: true + require "test_helper" -require_relative "./common" -require_relative "./channel_prefix" +require_relative "common" +require_relative "channel_prefix" + +require "active_support/testing/method_call_assertions" +require "action_cable/subscription_adapter/redis" class RedisAdapterTest < ActionCable::TestCase include CommonSubscriptionAdapterTest include ChannelPrefixTest def cable_config - { adapter: "redis", driver: "ruby", url: "redis://127.0.0.1:6379/12" } + { adapter: "redis", driver: "ruby" } end end @@ -16,3 +21,27 @@ class RedisAdapterTest::Hiredis < RedisAdapterTest super.merge(driver: "hiredis") end end + +class RedisAdapterTest::AlternateConfiguration < RedisAdapterTest + def cable_config + alt_cable_config = super.dup + alt_cable_config.delete(:url) + alt_cable_config.merge(host: "127.0.0.1", port: 6379, db: 12) + end +end + +class RedisAdapterTest::Connector < ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions + + test "slices url, host, port, db, and password from config" do + config = { url: 1, host: 2, port: 3, db: 4, password: 5 } + + assert_called_with ::Redis, :new, [ config ] do + connect config.merge(other: "unrelated", stuff: "here") + end + end + + def connect(config) + ActionCable::SubscriptionAdapter::Redis.redis_connector.call(config) + end +end diff --git a/actioncable/test/subscription_adapter/subscriber_map_test.rb b/actioncable/test/subscription_adapter/subscriber_map_test.rb index 76b984c849..ed81099cbc 100644 --- a/actioncable/test/subscription_adapter/subscriber_map_test.rb +++ b/actioncable/test/subscription_adapter/subscriber_map_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class SubscriberMapTest < ActionCable::TestCase diff --git a/actioncable/test/test_helper.rb b/actioncable/test/test_helper.rb index a47032753b..755f7b71b4 100644 --- a/actioncable/test/test_helper.rb +++ b/actioncable/test/test_helper.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + require "action_cable" require "active_support/testing/autorun" require "puma" -require "mocha/setup" require "rack/mock" begin @@ -11,7 +12,7 @@ rescue LoadError end # Require all the stubs and models -Dir[File.dirname(__FILE__) + "/stubs/*.rb"].each { |file| require file } +Dir[File.expand_path("stubs/*.rb", __dir__)].each { |file| require file } class ActionCable::TestCase < ActiveSupport::TestCase def wait_for_async diff --git a/actioncable/test/worker_test.rb b/actioncable/test/worker_test.rb index 3385593f74..bc1f3e415a 100644 --- a/actioncable/test/worker_test.rb +++ b/actioncable/test/worker_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "test_helper" class WorkerTest < ActiveSupport::TestCase |