From 654bb949e31b78793d0a58036cb4f7573cad8154 Mon Sep 17 00:00:00 2001 From: Ben Langfeld Date: Wed, 5 Dec 2018 18:16:54 -0200 Subject: [PATCH] Corrects Style/StringLiterals and Style/StringLiteralsInInterpolation offenses Sets the EnforcedStyle to `double_quotes` because this makes much more sense than the default. See https://github.com/rubocop-hq/rubocop/issues/5306 --- .rubocop.yml | 6 ++ .rubocop_todo.yml | 18 +--- Gemfile | 24 ++--- Rakefile | 32 +++---- examples/bench/config.ru | 6 +- examples/bench/puma.rb | 2 +- examples/bench/unicorn.conf.rb | 2 +- examples/chat/Gemfile | 6 +- examples/chat/chat.rb | 32 +++---- examples/chat/config.ru | 2 +- examples/minimal/Gemfile | 4 +- examples/minimal/config.ru | 2 +- lib/message_bus.rb | 12 +-- lib/message_bus/backends/postgres.rb | 48 +++++----- lib/message_bus/backends/redis.rb | 6 +- lib/message_bus/client.rb | 2 +- lib/message_bus/connection_manager.rb | 4 +- lib/message_bus/diagnostics.rb | 8 +- lib/message_bus/distributed_cache.rb | 10 +-- lib/message_bus/rack/diagnostics.rb | 44 +++++----- lib/message_bus/rack/middleware.rb | 30 +++---- lib/message_bus/rack/thin_ext.rb | 2 +- message_bus.gemspec | 8 +- spec/assets/support/jasmine_helper.rb | 2 +- spec/lib/fake_async_middleware.rb | 14 +-- .../message_bus/assets/asset_encoding_spec.rb | 14 +-- spec/lib/message_bus/backend_spec.rb | 14 +-- spec/lib/message_bus/client_spec.rb | 58 ++++++------ .../message_bus/connection_manager_spec.rb | 6 +- .../lib/message_bus/distributed_cache_spec.rb | 22 ++--- spec/lib/message_bus/multi_process_spec.rb | 8 +- spec/lib/message_bus/rack/middleware_spec.rb | 88 +++++++++---------- spec/lib/message_bus/timer_thread_spec.rb | 4 +- spec/lib/message_bus_spec.rb | 38 ++++---- spec/spec_helper.rb | 18 ++-- 35 files changed, 293 insertions(+), 303 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index a0c6e56c..b1e921d6 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -23,3 +23,9 @@ Metrics/BlockLength: Exclude: - '**/spec_helper.rb' - '**/**_spec.rb' + +# Single quotes being faster is hardly measurable and only affects parse time. +# Enforcing double quotes reduces the times where you need to change them when introducing an interpolation. +# Use single quotes only if their semantics are needed. +Style/StringLiterals: + EnforcedStyle: double_quotes diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index d87d849b..34191b92 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,6 +1,6 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2018-12-03 15:33:57 +0000 using RuboCop version 0.60.0. +# on 2018-12-05 20:15:45 +0000 using RuboCop version 0.60.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -542,22 +542,6 @@ Style/SpecialGlobalVars: - 'message_bus.gemspec' - 'spec/spec_helper.rb' -# Offense count: 657 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Enabled: false - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiteralsInInterpolation: - Exclude: - - 'examples/chat/chat.rb' - - 'lib/message_bus/rack/diagnostics.rb' - # Offense count: 1 Style/StructInheritance: Exclude: diff --git a/Gemfile b/Gemfile index 5c92ddc1..d8cbf2d5 100644 --- a/Gemfile +++ b/Gemfile @@ -1,20 +1,20 @@ -source 'https://rubygems.org' +source "https://rubygems.org" # Specify your gem's dependencies in message_bus.gemspec gemspec group :test do - gem 'minitest' - gem 'minitest-hooks' - gem 'rake' - gem 'http_parser.rb' - gem 'thin' - gem 'rack-test', require: 'rack/test' - gem 'jasmine' + gem "minitest" + gem "minitest-hooks" + gem "rake" + gem "http_parser.rb" + gem "thin" + gem "rack-test", require: "rack/test" + gem "jasmine" end -gem 'rack' -gem 'concurrent-ruby' # for distributed-cache +gem "rack" +gem "concurrent-ruby" # for distributed-cache -gem 'rubocop' -gem 'yard' +gem "rubocop" +gem "yard" diff --git a/Rakefile b/Rakefile index 0885c2e0..4505d666 100644 --- a/Rakefile +++ b/Rakefile @@ -1,17 +1,17 @@ -require 'rubygems' -require 'rake/testtask' -require 'bundler' -require 'bundler/gem_tasks' -require 'bundler/setup' -require 'jasmine' +require "rubygems" +require "rake/testtask" +require "bundler" +require "bundler/gem_tasks" +require "bundler/setup" +require "jasmine" -ENV['JASMINE_CONFIG_PATH'] ||= File.join(Dir.pwd, 'spec', 'assets', 'support', 'jasmine.yml') -load 'jasmine/tasks/jasmine.rake' +ENV["JASMINE_CONFIG_PATH"] ||= File.join(Dir.pwd, "spec", "assets", "support", "jasmine.yml") +load "jasmine/tasks/jasmine.rake" -require 'rubocop/rake_task' +require "rubocop/rake_task" RuboCop::RakeTask.new -require 'yard' +require "yard" YARD::Rake::YardocTask.new desc "Generate documentation for Yard, and fail if there are any warnings" @@ -38,25 +38,25 @@ end run_spec = proc do |backend| begin - ENV['MESSAGE_BUS_BACKEND'] = backend + ENV["MESSAGE_BUS_BACKEND"] = backend sh "#{FileUtils::RUBY} -e \"ARGV.each{|f| load f}\" #{Dir['spec/**/*_spec.rb'].to_a.join(' ')}" ensure - ENV.delete('MESSAGE_BUS_BACKEND') + ENV.delete("MESSAGE_BUS_BACKEND") end end task spec: [:spec_memory, :spec_redis, :spec_postgres, :spec_client_js, :rubocop, :test_doc] -task spec_client_js: 'jasmine:ci' +task spec_client_js: "jasmine:ci" task :spec_redis do - run_spec.call('redis') + run_spec.call("redis") end task :spec_memory do - run_spec.call('memory') + run_spec.call("memory") end task :spec_postgres do - run_spec.call('postgres') + run_spec.call("postgres") end diff --git a/examples/bench/config.ru b/examples/bench/config.ru index afd6ab46..508d21f2 100644 --- a/examples/bench/config.ru +++ b/examples/bench/config.ru @@ -1,7 +1,7 @@ -$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) +$LOAD_PATH.unshift File.expand_path("../../../lib", __FILE__) -require 'message_bus' -require 'stackprof' +require "message_bus" +require "stackprof" if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| diff --git a/examples/bench/puma.rb b/examples/bench/puma.rb index ffe75c83..bb1dc52d 100644 --- a/examples/bench/puma.rb +++ b/examples/bench/puma.rb @@ -1,4 +1,4 @@ -require 'message_bus' +require "message_bus" on_worker_boot do MessageBus.after_fork end diff --git a/examples/bench/unicorn.conf.rb b/examples/bench/unicorn.conf.rb index 8476990d..0b54ceff 100644 --- a/examples/bench/unicorn.conf.rb +++ b/examples/bench/unicorn.conf.rb @@ -1,4 +1,4 @@ -require 'message_bus' +require "message_bus" after_fork do |_server, _worker| MessageBus.after_fork end diff --git a/examples/chat/Gemfile b/examples/chat/Gemfile index b486b78a..696b895a 100644 --- a/examples/chat/Gemfile +++ b/examples/chat/Gemfile @@ -1,3 +1,3 @@ -gem 'puma' -gem 'redis' -gem 'sinatra' +gem "puma" +gem "redis" +gem "sinatra" diff --git a/examples/chat/chat.rb b/examples/chat/chat.rb index 87646bfe..b58af0f4 100644 --- a/examples/chat/chat.rb +++ b/examples/chat/chat.rb @@ -1,9 +1,9 @@ -$LOAD_PATH.unshift File.expand_path('../../../lib', __FILE__) -require 'message_bus' -require 'sinatra' -require 'sinatra/base' -require 'set' -require 'json' +$LOAD_PATH.unshift File.expand_path("../../../lib", __FILE__) +require "message_bus" +require "sinatra" +require "sinatra/base" +require "set" +require "json" $online = Hash.new @@ -17,7 +17,7 @@ end MessageBus.user_id_lookup do |env| - MessageBus.logger = env['rack.logger'] + MessageBus.logger = env["rack.logger"] name = env["HTTP_X_NAME"] if name unless $online[name] @@ -47,34 +47,34 @@ def expire_old_sessions end class Chat < Sinatra::Base - set :public_folder, File.expand_path('../../../assets', __FILE__) + set :public_folder, File.expand_path("../../../assets", __FILE__) use MessageBus::Rack::Middleware - post '/enter' do + post "/enter" do name = params["name"] i = 1 while $online.include? name - name = "#{params["name"]}#{i}" + name = "#{params['name']}#{i}" i += 1 end - MessageBus.publish '/presence', enter: name + MessageBus.publish "/presence", enter: name { users: $online.keys, name: name }.to_json end - post '/leave' do + post "/leave" do # puts "Got leave for #{params["name"]}" - MessageBus.publish '/presence', leave: params["name"] + MessageBus.publish "/presence", leave: params["name"] end - post '/message' do + post "/message" do msg = { data: params["data"][0..500], name: params["name"][0..100] } - MessageBus.publish '/message', msg + MessageBus.publish "/message", msg "OK" end - get '/' do + get "/" do <<~HTML diff --git a/examples/chat/config.ru b/examples/chat/config.ru index b8fa9e66..0150e975 100644 --- a/examples/chat/config.ru +++ b/examples/chat/config.ru @@ -1,2 +1,2 @@ -require './chat' +require "./chat" run Chat diff --git a/examples/minimal/Gemfile b/examples/minimal/Gemfile index 26bc5f39..b54a0040 100644 --- a/examples/minimal/Gemfile +++ b/examples/minimal/Gemfile @@ -1,3 +1,3 @@ -source 'https://rubygems.org' +source "https://rubygems.org" -gem 'message_bus' +gem "message_bus" diff --git a/examples/minimal/config.ru b/examples/minimal/config.ru index 54731dbd..38a5a1d6 100644 --- a/examples/minimal/config.ru +++ b/examples/minimal/config.ru @@ -1,4 +1,4 @@ -require 'message_bus' +require "message_bus" # MessageBus.long_polling_interval = 1000 * 2 diff --git a/lib/message_bus.rb b/lib/message_bus.rb index ea6a31b7..79275cdb 100644 --- a/lib/message_bus.rb +++ b/lib/message_bus.rb @@ -13,7 +13,7 @@ # we still need to take care of the logger if defined?(::Rails) - require 'message_bus/rails/railtie' + require "message_bus/rails/railtie" end # @see MessageBus::Implementation @@ -64,7 +64,7 @@ def logger=(logger) def logger return @config[:logger] if @config[:logger] - require 'logger' + require "logger" logger = Logger.new(STDOUT) logger.level = Logger::INFO configure(logger: logger) @@ -574,7 +574,7 @@ def decode_channel_name(channel) end def global?(channel) - channel && channel.start_with?('/global/'.freeze) + channel && channel.start_with?("/global/".freeze) end def decode_message!(msg) @@ -692,17 +692,17 @@ def new_subscriber_thread # do the best we can to terminate self cleanly fork do - Process.kill('TERM', pid) + Process.kill("TERM", pid) sleep 10 begin - Process.kill('KILL', pid) + Process.kill("KILL", pid) rescue Errno::ESRCH logger.warn "#{Process.pid} successfully terminated by `TERM` signal." end end sleep 10 - Process.kill('KILL', pid) + Process.kill("KILL", pid) else timer.queue(keepalive_interval, &blk) if keepalive_interval > MIN_KEEPALIVE diff --git a/lib/message_bus/backends/postgres.rb b/lib/message_bus/backends/postgres.rb index 5ca74ec7..9ebfa02c 100644 --- a/lib/message_bus/backends/postgres.rb +++ b/lib/message_bus/backends/postgres.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'pg' +require "pg" require "message_bus/backends/base" @@ -51,40 +51,40 @@ def initialize(config) end def add(channel, value) - hold { |conn| exec_prepared(conn, 'insert_message', [channel, value]) { |r| r.getvalue(0, 0).to_i } } + hold { |conn| exec_prepared(conn, "insert_message", [channel, value]) { |r| r.getvalue(0, 0).to_i } } end def clear_global_backlog(backlog_id, num_to_keep) if backlog_id > num_to_keep - hold { |conn| exec_prepared(conn, 'clear_global_backlog', [backlog_id - num_to_keep]) } + hold { |conn| exec_prepared(conn, "clear_global_backlog", [backlog_id - num_to_keep]) } nil end end def clear_channel_backlog(channel, backlog_id, num_to_keep) - hold { |conn| exec_prepared(conn, 'clear_channel_backlog', [channel, backlog_id, num_to_keep]) } + hold { |conn| exec_prepared(conn, "clear_channel_backlog", [channel, backlog_id, num_to_keep]) } nil end def expire(max_backlog_age) - hold { |conn| exec_prepared(conn, 'expire', [max_backlog_age]) } + hold { |conn| exec_prepared(conn, "expire", [max_backlog_age]) } nil end def backlog(channel, backlog_id) hold do |conn| - exec_prepared(conn, 'channel_backlog', [channel, backlog_id]) { |r| r.values.each { |a| a[0] = a[0].to_i } } + exec_prepared(conn, "channel_backlog", [channel, backlog_id]) { |r| r.values.each { |a| a[0] = a[0].to_i } } end || [] end def global_backlog(backlog_id) hold do |conn| - exec_prepared(conn, 'global_backlog', [backlog_id]) { |r| r.values.each { |a| a[0] = a[0].to_i } } + exec_prepared(conn, "global_backlog", [backlog_id]) { |r| r.values.each { |a| a[0] = a[0].to_i } } end || [] end def get_value(channel, id) - hold { |conn| exec_prepared(conn, 'get_message', [channel, id]) { |r| r.getvalue(0, 0) } } + hold { |conn| exec_prepared(conn, "get_message", [channel, id]) { |r| r.getvalue(0, 0) } } end def reconnect @@ -97,7 +97,7 @@ def reconnect # Dangerous, drops the message_bus table containing the backlog if it exists. def reset! hold do |conn| - conn.exec 'DROP TABLE IF EXISTS message_bus' + conn.exec "DROP TABLE IF EXISTS message_bus" create_table(conn) end end @@ -117,14 +117,14 @@ def max_id(channel = nil) end if channel - hold { |conn| exec_prepared(conn, 'max_channel_id', [channel], &block) } + hold { |conn| exec_prepared(conn, "max_channel_id", [channel], &block) } else - hold { |conn| exec_prepared(conn, 'max_id', &block) } + hold { |conn| exec_prepared(conn, "max_id", &block) } end end def publish(channel, data) - hold { |conn| exec_prepared(conn, 'publish', [channel, data]) } + hold { |conn| exec_prepared(conn, "publish", [channel, data]) } end def subscribe(channel) @@ -163,9 +163,9 @@ def exec_prepared(conn, *a) end def create_table(conn) - conn.exec 'CREATE TABLE message_bus (id bigserial PRIMARY KEY, channel text NOT NULL, value text NOT NULL CHECK (octet_length(value) >= 2), added_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL)' - conn.exec 'CREATE INDEX table_channel_id_index ON message_bus (channel, id)' - conn.exec 'CREATE INDEX table_added_at_index ON message_bus (added_at)' + conn.exec "CREATE TABLE message_bus (id bigserial PRIMARY KEY, channel text NOT NULL, value text NOT NULL CHECK (octet_length(value) >= 2), added_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL)" + conn.exec "CREATE INDEX table_channel_id_index ON message_bus (channel, id)" + conn.exec "CREATE INDEX table_added_at_index ON message_bus (added_at)" nil end @@ -212,16 +212,16 @@ def new_pg_connection create_table(conn) end - conn.exec 'PREPARE insert_message AS INSERT INTO message_bus (channel, value) VALUES ($1, $2) RETURNING id' - conn.exec 'PREPARE clear_global_backlog AS DELETE FROM message_bus WHERE (id <= $1)' - conn.exec 'PREPARE clear_channel_backlog AS DELETE FROM message_bus WHERE ((channel = $1) AND (id <= (SELECT id FROM message_bus WHERE ((channel = $1) AND (id <= $2)) ORDER BY id DESC LIMIT 1 OFFSET $3)))' - conn.exec 'PREPARE channel_backlog AS SELECT id, value FROM message_bus WHERE ((channel = $1) AND (id > $2)) ORDER BY id' - conn.exec 'PREPARE global_backlog AS SELECT id, channel, value FROM message_bus WHERE (id > $1) ORDER BY id' + conn.exec "PREPARE insert_message AS INSERT INTO message_bus (channel, value) VALUES ($1, $2) RETURNING id" + conn.exec "PREPARE clear_global_backlog AS DELETE FROM message_bus WHERE (id <= $1)" + conn.exec "PREPARE clear_channel_backlog AS DELETE FROM message_bus WHERE ((channel = $1) AND (id <= (SELECT id FROM message_bus WHERE ((channel = $1) AND (id <= $2)) ORDER BY id DESC LIMIT 1 OFFSET $3)))" + conn.exec "PREPARE channel_backlog AS SELECT id, value FROM message_bus WHERE ((channel = $1) AND (id > $2)) ORDER BY id" + conn.exec "PREPARE global_backlog AS SELECT id, channel, value FROM message_bus WHERE (id > $1) ORDER BY id" conn.exec "PREPARE expire AS DELETE FROM message_bus WHERE added_at < CURRENT_TIMESTAMP - ($1::text || ' seconds')::interval" - conn.exec 'PREPARE get_message AS SELECT value FROM message_bus WHERE ((channel = $1) AND (id = $2))' - conn.exec 'PREPARE max_channel_id AS SELECT max(id) FROM message_bus WHERE (channel = $1)' - conn.exec 'PREPARE max_id AS SELECT max(id) FROM message_bus' - conn.exec 'PREPARE publish AS SELECT pg_notify($1, $2)' + conn.exec "PREPARE get_message AS SELECT value FROM message_bus WHERE ((channel = $1) AND (id = $2))" + conn.exec "PREPARE max_channel_id AS SELECT max(id) FROM message_bus WHERE (channel = $1)" + conn.exec "PREPARE max_id AS SELECT max(id) FROM message_bus" + conn.exec "PREPARE publish AS SELECT pg_notify($1, $2)" conn end diff --git a/lib/message_bus/backends/redis.rb b/lib/message_bus/backends/redis.rb index cfb2154a..b828ce92 100644 --- a/lib/message_bus/backends/redis.rb +++ b/lib/message_bus/backends/redis.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'redis' -require 'digest' +require "redis" +require "digest" require "message_bus/backends/base" @@ -436,7 +436,7 @@ def is_readonly? # in case we are not connected to the correct server # which can happen when sharing ips pub_redis.client.reconnect - pub_redis.client.call([:set, key, '1']) + pub_redis.client.call([:set, key, "1"]) false rescue ::Redis::CommandError => e return true if e.message =~ /^READONLY/ diff --git a/lib/message_bus/client.rb b/lib/message_bus/client.rb index 6eceb2c9..368b9d33 100644 --- a/lib/message_bus/client.rb +++ b/lib/message_bus/client.rb @@ -186,7 +186,7 @@ def backlog end end - r << MessageBus::Message.new(-1, -1, '/__status', status_message) if status_message + r << MessageBus::Message.new(-1, -1, "/__status", status_message) if status_message r || [] end diff --git a/lib/message_bus/connection_manager.rb b/lib/message_bus/connection_manager.rb index 172ee0e9..a02d55a9 100644 --- a/lib/message_bus/connection_manager.rb +++ b/lib/message_bus/connection_manager.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'json' unless defined? ::JSON +require "json" unless defined? ::JSON # Manages a set of subscribers with active connections to the server, such that # messages which are published during the connection may be dispatched. class MessageBus::ConnectionManager - require 'monitor' + require "monitor" include MonitorMixin # @param [MessageBus::Instance] bus the message bus for which to manage connections diff --git a/lib/message_bus/diagnostics.rb b/lib/message_bus/diagnostics.rb index 40c5d946..cffaa34b 100644 --- a/lib/message_bus/diagnostics.rb +++ b/lib/message_bus/diagnostics.rb @@ -12,7 +12,7 @@ def enable(bus = MessageBus) # it may make sense to add a channel per machine/host to streamline # process to process comms - bus.subscribe('/_diagnostics/hup') do |msg| + bus.subscribe("/_diagnostics/hup") do |msg| if Process.pid == msg.data["pid"] && hostname == msg.data["hostname"] $shutdown = true sleep 4 @@ -20,9 +20,9 @@ def enable(bus = MessageBus) end end - bus.subscribe('/_diagnostics/discover') do |msg| + bus.subscribe("/_diagnostics/discover") do |msg| bus.on_connect.call msg.site_id if bus.on_connect - bus.publish '/_diagnostics/process-discovery', { + bus.publish "/_diagnostics/process-discovery", { pid: Process.pid, process_name: $0, full_path: full_path, @@ -44,7 +44,7 @@ def full_process_path `ps -o command -p #{Process.pid}`.split("\n", 2)[1].strip else info = `ps -eo "%p|$|%a" | grep '^\\s*#{Process.pid}'` - info.strip.split('|$|')[1] + info.strip.split("|$|")[1] end rescue # skip it ... not linux or something weird diff --git a/lib/message_bus/distributed_cache.rb b/lib/message_bus/distributed_cache.rb index 7af43a48..04569922 100644 --- a/lib/message_bus/distributed_cache.rb +++ b/lib/message_bus/distributed_cache.rb @@ -1,18 +1,18 @@ # frozen_string_literal: true -require 'weakref' -require 'base64' -require 'securerandom' +require "weakref" +require "base64" +require "securerandom" module MessageBus # Like a hash, just does its best to stay in sync across the farm. # On boot all instances are blank, but they populate as various processes # fill it up. class DistributedCache - DEFAULT_SITE_ID = 'default' + DEFAULT_SITE_ID = "default" class Manager - CHANNEL_NAME ||= '/distributed_hash'.freeze + CHANNEL_NAME ||= "/distributed_hash".freeze attr_accessor :app_version diff --git a/lib/message_bus/rack/diagnostics.rb b/lib/message_bus/rack/diagnostics.rb index 9ffbcea6..a54bb786 100644 --- a/lib/message_bus/rack/diagnostics.rb +++ b/lib/message_bus/rack/diagnostics.rb @@ -16,39 +16,39 @@ def initialize(app, config = {}) # Process an HTTP request from a subscriber client # @param [Rack::Request::Env] env the request environment def call(env) - return @app.call(env) unless env['PATH_INFO'].start_with? '/message-bus/_diagnostics' + return @app.call(env) unless env["PATH_INFO"].start_with? "/message-bus/_diagnostics" - route = env['PATH_INFO'].split('/message-bus/_diagnostics')[1] + route = env["PATH_INFO"].split("/message-bus/_diagnostics")[1] if @bus.is_admin_lookup.nil? || !@bus.is_admin_lookup.call(env) - return [403, {}, ['not allowed']] + return [403, {}, ["not allowed"]] end return index unless route - if route == '/discover' + if route == "/discover" user_id = @bus.user_id_lookup.call(env) - @bus.publish('/_diagnostics/discover', user_id: user_id) - return [200, {}, ['ok']] + @bus.publish("/_diagnostics/discover", user_id: user_id) + return [200, {}, ["ok"]] end if route =~ /^\/hup\// - hostname, pid = route.split('/hup/')[1].split('/') - @bus.publish('/_diagnostics/hup', hostname: hostname, pid: pid.to_i) - return [200, {}, ['ok']] + hostname, pid = route.split("/hup/")[1].split("/") + @bus.publish("/_diagnostics/hup", hostname: hostname, pid: pid.to_i) + return [200, {}, ["ok"]] end - asset = route.split('/assets/')[1] + asset = route.split("/assets/")[1] if asset && !asset !~ /\// content = asset_contents(asset) - split = asset.split('.') - if split[1] == 'handlebars' + split = asset.split(".") + if split[1] == "handlebars" content = translate_handlebars(split[0], content) end - return [200, { 'content-type' => 'text/javascript;' }, [content]] + return [200, { "content-type" => "text/javascript;" }, [content]] end - return [404, {}, ['not found']] + return [404, {}, ["not found"]] end private @@ -66,7 +66,7 @@ def generate_script_tag(name) end def file_hash(asset) - require 'digest/sha1' + require "digest/sha1" Digest::SHA1.hexdigest(asset_contents(asset)) end @@ -86,13 +86,13 @@ def index
- #{js_asset "jquery-1.8.2.js"} - #{js_asset "handlebars.js"} - #{js_asset "ember.js"} - #{js_asset "message-bus.js"} - #{js_asset "application.handlebars"} - #{js_asset "index.handlebars"} - #{js_asset "application.js"} + #{js_asset 'jquery-1.8.2.js'} + #{js_asset 'handlebars.js'} + #{js_asset 'ember.js'} + #{js_asset 'message-bus.js'} + #{js_asset 'application.handlebars'} + #{js_asset 'index.handlebars'} + #{js_asset 'application.js'} HTML diff --git a/lib/message_bus/rack/middleware.rb b/lib/message_bus/rack/middleware.rb index 1e5336f7..6afa8670 100644 --- a/lib/message_bus/rack/middleware.rb +++ b/lib/message_bus/rack/middleware.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'json' +require "json" # our little message bus, accepts long polling and polling module MessageBus::Rack; end @@ -54,21 +54,21 @@ def stop_listener # Process an HTTP request from a subscriber client # @param [Rack::Request::Env] env the request environment def call(env) - return @app.call(env) unless env['PATH_INFO'] =~ /^\/message-bus\// + return @app.call(env) unless env["PATH_INFO"] =~ /^\/message-bus\// # special debug/test route - if @bus.allow_broadcast? && env['PATH_INFO'] == '/message-bus/broadcast' + if @bus.allow_broadcast? && env["PATH_INFO"] == "/message-bus/broadcast" parsed = Rack::Request.new(env) @bus.publish parsed["channel"], parsed["data"] return [200, { "Content-Type" => "text/html" }, ["sent"]] end - if env['PATH_INFO'].start_with? '/message-bus/_diagnostics' + if env["PATH_INFO"].start_with? "/message-bus/_diagnostics" diags = MessageBus::Rack::Diagnostics.new(@app, message_bus: @bus) return diags.call(env) end - client_id = env['PATH_INFO'].split("/")[2] + client_id = env["PATH_INFO"].split("/")[2] return [404, {}, ["not found"]] unless client_id user_id = @bus.user_id_lookup.call(env) if @bus.user_id_lookup @@ -81,8 +81,8 @@ def call(env) client = MessageBus::Client.new(message_bus: @bus, client_id: client_id, user_id: user_id, site_id: site_id, group_ids: group_ids) - if channels = env['message_bus.channels'] - if seq = env['message_bus.seq'] + if channels = env["message_bus.channels"] + if seq = env["message_bus.seq"] client.seq = seq.to_i end channels.each do |k, v| @@ -90,7 +90,7 @@ def call(env) end else request = Rack::Request.new(env) - is_json = request.content_type && request.content_type.include?('application/json') + is_json = request.content_type && request.content_type.include?("application/json") data = is_json ? JSON.parse(request.body.read) : request.POST data.each do |k, v| if k == "__seq" @@ -118,11 +118,11 @@ def call(env) end long_polling = @bus.long_polling_enabled? && - env['QUERY_STRING'] !~ /dlp=t/ && + env["QUERY_STRING"] !~ /dlp=t/ && @connection_manager.client_count < @bus.max_active_clients - allow_chunked = env['HTTP_VERSION'] == 'HTTP/1.1' - allow_chunked &&= !env['HTTP_DONT_CHUNK'] + allow_chunked = env["HTTP_VERSION"] == "HTTP/1.1" + allow_chunked &&= !env["HTTP_DONT_CHUNK"] allow_chunked &&= @bus.chunked_encoding_enabled? client.use_chunked = allow_chunked @@ -133,8 +133,8 @@ def call(env) client.close @bus.logger.debug "Delivering backlog #{backlog} to client #{client_id} for user #{user_id}" [200, headers, [self.class.backlog_to_json(backlog)]] - elsif long_polling && env['rack.hijack'] && @bus.rack_hijack_enabled? - io = env['rack.hijack'].call + elsif long_polling && env["rack.hijack"] && @bus.rack_hijack_enabled? + io = env["rack.hijack"].call # TODO disable client till deliver backlog is called client.io = io client.headers = headers @@ -144,13 +144,13 @@ def call(env) client.ensure_first_chunk_sent end [418, {}, ["I'm a teapot, undefined in spec"]] - elsif long_polling && env['async.callback'] + elsif long_polling && env["async.callback"] response = nil # load extension if needed begin response = Thin::AsyncResponse.new(env) rescue NameError - require 'message_bus/rack/thin_ext' + require "message_bus/rack/thin_ext" response = Thin::AsyncResponse.new(env) end diff --git a/lib/message_bus/rack/thin_ext.rb b/lib/message_bus/rack/thin_ext.rb index 9c8d11df..b755a3a1 100644 --- a/lib/message_bus/rack/thin_ext.rb +++ b/lib/message_bus/rack/thin_ext.rb @@ -46,7 +46,7 @@ class AsyncResponse attr_accessor :status def initialize(env, status = 200, headers = {}) - @callback = env['async.callback'] + @callback = env["async.callback"] @body = DeferrableBody.new @status = status @headers = headers diff --git a/message_bus.gemspec b/message_bus.gemspec index dd27ef9f..0f6ab9f1 100644 --- a/message_bus.gemspec +++ b/message_bus.gemspec @@ -1,7 +1,7 @@ # frozen_string_literal: true # -*- encoding: utf-8 -*- -require File.expand_path('../lib/message_bus/version', __FILE__) +require File.expand_path("../lib/message_bus/version", __FILE__) Gem::Specification.new do |gem| gem.authors = ["Sam Saffron"] @@ -18,7 +18,7 @@ Gem::Specification.new do |gem| gem.require_paths = ["lib"] gem.version = MessageBus::VERSION gem.required_ruby_version = ">= 2.3.0" - gem.add_runtime_dependency 'rack', '>= 1.1.3' - gem.add_development_dependency 'redis' - gem.add_development_dependency 'pg' + gem.add_runtime_dependency "rack", ">= 1.1.3" + gem.add_development_dependency "redis" + gem.add_development_dependency "pg" end diff --git a/spec/assets/support/jasmine_helper.rb b/spec/assets/support/jasmine_helper.rb index d921d4cd..3d62318d 100644 --- a/spec/assets/support/jasmine_helper.rb +++ b/spec/assets/support/jasmine_helper.rb @@ -1,6 +1,6 @@ Jasmine.configure do |_config| # patch for travis - if ENV['TRAVIS'] + if ENV["TRAVIS"] module ::Phantomjs def self.version @phantom_version ||= `phantomjs --version`.strip diff --git a/spec/lib/fake_async_middleware.rb b/spec/lib/fake_async_middleware.rb index 1c63926a..a08dd51f 100644 --- a/spec/lib/fake_async_middleware.rb +++ b/spec/lib/fake_async_middleware.rb @@ -1,4 +1,4 @@ -require 'http/parser' +require "http/parser" class FakeAsyncMiddleware def initialize(app, config = {}) @app = app @@ -40,7 +40,7 @@ def simulate_hijack? def call(env) unless @allow_chunked - env['HTTP_DONT_CHUNK'] = 'True' + env["HTTP_DONT_CHUNK"] = "True" end if simulate_thin_async? call_thin_async(env) @@ -69,12 +69,12 @@ def call_rack_hijack(env) io = nil EM.run { - env['rack.hijack'] = lambda { + env["rack.hijack"] = lambda { hijacked = true io = StringIO.new } - env['rack.hijack_io'] = io + env["rack.hijack_io"] = io result = @app.call(env) @@ -102,13 +102,13 @@ def call_rack_hijack(env) } @in_async = false - result || [500, {}, ['timeout']] + result || [500, {}, ["timeout"]] end def call_thin_async(env) result = nil EM.run { - env['async.callback'] = lambda { |r| + env["async.callback"] = lambda { |r| # more judo with deferrable body, at this point we just have headers r[2].callback do # even more judo cause rack test does not call each like the spec says @@ -140,6 +140,6 @@ def call_thin_async(env) } @in_async = false - result || [500, {}, ['timeout']] + result || [500, {}, ["timeout"]] end end diff --git a/spec/lib/message_bus/assets/asset_encoding_spec.rb b/spec/lib/message_bus/assets/asset_encoding_spec.rb index 7a154ab4..67d7f161 100644 --- a/spec/lib/message_bus/assets/asset_encoding_spec.rb +++ b/spec/lib/message_bus/assets/asset_encoding_spec.rb @@ -1,18 +1,18 @@ -require_relative '../../../spec_helper' -asset_directory = File.expand_path('../../../../../assets', __FILE__) -asset_file_paths = Dir.glob(File.join(asset_directory, 'message-bus.js')) +require_relative "../../../spec_helper" +asset_directory = File.expand_path("../../../../../assets", __FILE__) +asset_file_paths = Dir.glob(File.join(asset_directory, "message-bus.js")) asset_file_names = asset_file_paths.map { |e| File.basename(e) } describe asset_file_names do - it 'should contain .js files' do - asset_file_names.must_include('message-bus.js') + it "should contain .js files" do + asset_file_names.must_include("message-bus.js") end end asset_file_paths.each do |path| describe "Asset file #{File.basename(path).inspect}" do - it 'should be encodable as UTF8' do - binary_data = File.open(path, 'rb') { |f| f.read } + it "should be encodable as UTF8" do + binary_data = File.open(path, "rb") { |f| f.read } binary_data.encode(Encoding::UTF_8) end end diff --git a/spec/lib/message_bus/backend_spec.rb b/spec/lib/message_bus/backend_spec.rb index ec88e2b7..fabca687 100644 --- a/spec/lib/message_bus/backend_spec.rb +++ b/spec/lib/message_bus/backend_spec.rb @@ -1,5 +1,5 @@ -require_relative '../../spec_helper' -require 'message_bus' +require_relative "../../spec_helper" +require "message_bus" describe PUB_SUB_CLASS do def new_test_bus @@ -22,8 +22,8 @@ def new_test_bus @bus.publish "/foo", "baz" @bus.backlog("/foo", 0).to_a.must_equal [ - MessageBus::Message.new(1, 1, '/foo', 'bar'), - MessageBus::Message.new(2, 2, '/foo', 'baz') + MessageBus::Message.new(1, 1, "/foo", "bar"), + MessageBus::Message.new(2, 2, "/foo", "baz") ] end @@ -43,8 +43,8 @@ def new_test_bus end @bus.backlog("/foo").to_a.must_equal [ - MessageBus::Message.new(3, 3, '/foo', 'three'), - MessageBus::Message.new(4, 4, '/foo', 'four'), + MessageBus::Message.new(3, 3, "/foo", "three"), + MessageBus::Message.new(4, 4, "/foo", "four"), ] end @@ -79,7 +79,7 @@ def new_test_bus end it "should be able to encode and decode messages properly" do - m = MessageBus::Message.new 1, 2, '||', '||' + m = MessageBus::Message.new 1, 2, "||", "||" MessageBus::Message.decode(m.encode).must_equal m end diff --git a/spec/lib/message_bus/client_spec.rb b/spec/lib/message_bus/client_spec.rb index 1bf86d92..1d65908f 100644 --- a/spec/lib/message_bus/client_spec.rb +++ b/spec/lib/message_bus/client_spec.rb @@ -1,5 +1,5 @@ -require_relative '../../spec_helper' -require 'message_bus' +require_relative "../../spec_helper" +require "message_bus" describe MessageBus::Client do describe "subscriptions" do @@ -10,7 +10,7 @@ def setup_client(client_id) before do @bus = MessageBus::Instance.new @bus.configure(MESSAGE_BUS_CONFIG) - @client = setup_client('abc') + @client = setup_client("abc") end after do @@ -57,8 +57,8 @@ def parse_chunk(data) r, w = IO.pipe @client.io = w @client.headers = { "Content-Type" => "application/json; charset=utf-8" } - @client << MessageBus::Message.new(1, 1, '/test', 'test') - @client << MessageBus::Message.new(2, 2, '/test', "a|\r\n|\r\n|b") + @client << MessageBus::Message.new(1, 1, "/test", "test") + @client << MessageBus::Message.new(2, 2, "/test", "a|\r\n|\r\n|b") lines = r.read_nonblock(8000) @@ -70,13 +70,13 @@ def parse_chunk(data) chunk1 = parse_chunk(chunks[0]) chunk1.length.must_equal 1 - chunk1.first["data"].must_equal 'test' + chunk1.first["data"].must_equal "test" chunk2 = parse_chunk(chunks[1]) chunk2.length.must_equal 1 chunk2.first["data"].must_equal "a|\r\n|\r\n|b" - @client << MessageBus::Message.new(3, 3, '/test', 'test3') + @client << MessageBus::Message.new(3, 3, "/test", "test3") @client.close data = r.read @@ -89,7 +89,7 @@ def parse_chunk(data) chunk1 = parse_chunk(chunks[0]) chunk1.length.must_equal 1 - chunk1.first["data"].must_equal 'test3' + chunk1.first["data"].must_equal "test3" # end with [] chunk2 = parse_chunk(chunks[1]) @@ -99,8 +99,8 @@ def parse_chunk(data) it "does not bleed data accross sites" do @client.site_id = "test" - @client.subscribe('/hello', nil) - @bus.publish '/hello', 'world' + @client.subscribe("/hello", nil) + @bus.publish "/hello", "world" log = @client.backlog log.length.must_equal 0 end @@ -108,17 +108,17 @@ def parse_chunk(data) it "does not bleed status accross sites" do @client.site_id = "test" - @client.subscribe('/hello', -1) - @bus.publish '/hello', 'world' + @client.subscribe("/hello", -1) + @bus.publish "/hello", "world" log = @client.backlog log[0].data.must_equal("/hello" => 0) end it "allows negative subscribes to look behind" do - @bus.publish '/hello', 'world' - @bus.publish '/hello', 'sam' + @bus.publish "/hello", "world" + @bus.publish "/hello", "sam" - @client.subscribe('/hello', -2) + @client.subscribe("/hello", -2) log = @client.backlog log.length.must_equal(1) @@ -126,49 +126,49 @@ def parse_chunk(data) end it "provides status" do - @client.subscribe('/hello', -1) + @client.subscribe("/hello", -1) log = @client.backlog log.length.must_equal 1 log[0].data.must_equal("/hello" => 0) end - it 'provides status updates to clients that are not allowed to a message' do - another_client = setup_client('def') + it "provides status updates to clients that are not allowed to a message" do + another_client = setup_client("def") clients = [@client, another_client] channel = SecureRandom.hex clients.each { |client| client.subscribe(channel, nil) } - @bus.publish(channel, "world", client_ids: ['abc']) + @bus.publish(channel, "world", client_ids: ["abc"]) log = @client.backlog log.length.must_equal 1 log[0].channel.must_equal channel - log[0].data.must_equal 'world' + log[0].data.must_equal "world" log = another_client.backlog log.length.must_equal 1 - log[0].channel.must_equal '/__status' + log[0].channel.must_equal "/__status" log[0].data.must_equal(channel => 1) end it "should provide a list of subscriptions" do - @client.subscribe('/hello', nil) - @client.subscriptions['/hello'].wont_equal nil + @client.subscribe("/hello", nil) + @client.subscriptions["/hello"].wont_equal nil end it "should provide backlog for subscribed channel" do - @client.subscribe('/hello', nil) - @bus.publish '/hello', 'world' + @client.subscribe("/hello", nil) + @bus.publish "/hello", "world" log = @client.backlog log.length.must_equal 1 - log[0].channel.must_equal '/hello' - log[0].data.must_equal 'world' + log[0].channel.must_equal "/hello" + log[0].data.must_equal "world" end it "allows only client_id in list if message contains client_ids" do - @message = MessageBus::Message.new(1, 2, '/test', 'hello') + @message = MessageBus::Message.new(1, 2, "/test", "hello") @message.client_ids = ["1", "2"] @client.client_id = "2" @client.allowed?(@message).must_equal true @@ -179,7 +179,7 @@ def parse_chunk(data) describe "targetted at group" do before do - @message = MessageBus::Message.new(1, 2, '/test', 'hello') + @message = MessageBus::Message.new(1, 2, "/test", "hello") @message.group_ids = [1, 2, 3] end diff --git a/spec/lib/message_bus/connection_manager_spec.rb b/spec/lib/message_bus/connection_manager_spec.rb index c9f2323e..98cbcf88 100644 --- a/spec/lib/message_bus/connection_manager_spec.rb +++ b/spec/lib/message_bus/connection_manager_spec.rb @@ -1,5 +1,5 @@ -require_relative '../../spec_helper' -require 'message_bus' +require_relative "../../spec_helper" +require "message_bus" class FakeAsync attr_accessor :cleanup_timer @@ -29,7 +29,7 @@ def cancel; @cancelled = true; end @client = MessageBus::Client.new(client_id: "xyz", user_id: 1, site_id: 10) @resp = FakeAsync.new @client.async_response = @resp - @client.subscribe('test', -1) + @client.subscribe("test", -1) @manager.add_client(@client) @client.cleanup_timer = FakeTimer.new end diff --git a/spec/lib/message_bus/distributed_cache_spec.rb b/spec/lib/message_bus/distributed_cache_spec.rb index c50b6221..b7dd4da0 100644 --- a/spec/lib/message_bus/distributed_cache_spec.rb +++ b/spec/lib/message_bus/distributed_cache_spec.rb @@ -1,7 +1,7 @@ -require_relative '../../spec_helper' -require 'minitest/hooks/default' -require 'message_bus' -require 'message_bus/distributed_cache' +require_relative "../../spec_helper" +require "minitest/hooks/default" +require "message_bus" +require "message_bus/distributed_cache" describe MessageBus::DistributedCache do before :all do @@ -27,7 +27,7 @@ def cache(name) @cache2 = cache(cache_name) end - it 'supports arrays with hashes' do + it "supports arrays with hashes" do c1 = cache("test1") c2 = cache("test1") @@ -40,7 +40,7 @@ def cache(name) expect(c2[:test]).must_equal([{ test: :test }]) end - it 'allows us to store Set' do + it "allows us to store Set" do c1 = cache("test1") c2 = cache("test1") @@ -69,7 +69,7 @@ def cache(name) expect(c1["cats"]).must_equal(set) end - it 'does not leak state across caches' do + it "does not leak state across caches" do c2 = cache("test1") c3 = cache("test1") c2["hi"] = "hi" @@ -81,7 +81,7 @@ def cache(name) assert_nil(@cache1["hi"]) end - it 'allows coerces symbol keys to strings' do + it "allows coerces symbol keys to strings" do @cache1[:key] = "test" expect(@cache1["key"]).must_equal("test") @@ -91,14 +91,14 @@ def cache(name) expect(@cache2["key"]).must_equal("test") end - it 'sets other caches' do + it "sets other caches" do @cache1["test"] = "world" wait_for do @cache2["test"] == "world" end end - it 'deletes from other caches' do + it "deletes from other caches" do @cache1["foo"] = "bar" wait_for do @@ -113,7 +113,7 @@ def cache(name) end end - it 'clears cache on request' do + it "clears cache on request" do @cache1["foo"] = "bar" wait_for do diff --git a/spec/lib/message_bus/multi_process_spec.rb b/spec/lib/message_bus/multi_process_spec.rb index 19855af6..a5e500aa 100644 --- a/spec/lib/message_bus/multi_process_spec.rb +++ b/spec/lib/message_bus/multi_process_spec.rb @@ -1,5 +1,5 @@ -require_relative '../../spec_helper' -require 'message_bus' +require_relative "../../spec_helper" +require "message_bus" describe PUB_SUB_CLASS do def self.error! @@ -35,10 +35,10 @@ def spawn_child end end - n = ENV['MULTI_PROCESS_TIMES'].to_i + n = ENV["MULTI_PROCESS_TIMES"].to_i n = 1 if n < 1 n.times do - it 'gets every response from child processes' do + it "gets every response from child processes" do test_never :memory skip("previous error") if self.class.error? GC.start diff --git a/spec/lib/message_bus/rack/middleware_spec.rb b/spec/lib/message_bus/rack/middleware_spec.rb index 04f81ae8..fd4a7b7d 100644 --- a/spec/lib/message_bus/rack/middleware_spec.rb +++ b/spec/lib/message_bus/rack/middleware_spec.rb @@ -1,8 +1,8 @@ # coding: utf-8 -require_relative '../../../spec_helper' -require 'message_bus' -require 'rack/test' +require_relative "../../../spec_helper" +require "message_bus" +require "rack/test" describe MessageBus::Rack::Middleware do include Rack::Test::Methods @@ -18,7 +18,7 @@ use FakeAsyncMiddleware, message_bus: bus use e_m if e_m use MessageBus::Rack::Middleware, message_bus: bus - run lambda { |_env| [500, { 'Content-Type' => 'text/html' }, 'should not be called'] } + run lambda { |_env| [500, { "Content-Type" => "text/html" }, "should not be called"] } } @async_middleware = builder.to_app @@ -44,13 +44,13 @@ module LongPolling end it "should respond right away if dlp=t" do - post "/message-bus/ABC?dlp=t", '/foo1' => 0 + post "/message-bus/ABC?dlp=t", "/foo1" => 0 @async_middleware.in_async?.must_equal false last_response.ok?.must_equal true end it "should respond right away to long polls that are polling on -1 with the last_id" do - post "/message-bus/ABC", '/foo' => -1 + post "/message-bus/ABC", "/foo" => -1 last_response.ok?.must_equal true parsed = JSON.parse(last_response.body) parsed.length.must_equal 1 @@ -71,7 +71,7 @@ module LongPolling bus.publish "/foo", "םוֹלשָׁ" end - post "/message-bus/ABC", '/foo' => nil + post "/message-bus/ABC", "/foo" => nil last_response.ok?.must_equal true parsed = JSON.parse(last_response.body) @@ -85,7 +85,7 @@ module LongPolling begin @bus.long_polling_interval = 10 s = Time.now.to_f * 1000 - post "/message-bus/ABC", '/foo' => nil + post "/message-bus/ABC", "/foo" => nil # allow for some jitter (Time.now.to_f * 1000 - s).must_be :<, 100 ensure @@ -158,8 +158,8 @@ def @bus.is_admin_lookup; proc { |_| true } end # client always keeps a list of channels with last message id they got on each post "/message-bus/#{client_id}", - '/foo' => nil, - '/bar' => nil + "/foo" => nil, + "/bar" => nil last_response.headers["FOO"].must_equal "BAR" end @@ -169,22 +169,22 @@ def @bus.is_admin_lookup; proc { |_| true } end # client always keeps a list of channels with last message id they got on each post "/message-bus/#{client_id}", - '/foo' => nil, - '/bar' => nil + "/foo" => nil, + "/bar" => nil last_response.ok?.must_equal true end # this means we recover from redis reset it "should understand that larger than position is the same as -1" do - @bus.publish('/foo', 'bar') - @bus.publish('/baz', 'test') - @bus.publish('/boom', 'bang') + @bus.publish("/foo", "bar") + @bus.publish("/baz", "test") + @bus.publish("/boom", "bang") post "/message-bus/ABCD", - '/foo' => 1_000_000, - '/baz' => @bus.last_id('/baz') + 1, - '/boom' => 1_000_000 + "/foo" => 1_000_000, + "/baz" => @bus.last_id("/baz") + 1, + "/boom" => 1_000_000 last_response.ok?.must_equal true parsed = JSON.parse(last_response.body) @@ -199,14 +199,14 @@ def @bus.is_admin_lookup; proc { |_| true } end # even if allow chunked @bus.chunked_encoding_enabled = true - @bus.publish('/foo', 'bar') - @bus.publish('/baz', 'test') - @bus.publish('/boom', 'bang') + @bus.publish("/foo", "bar") + @bus.publish("/baz", "test") + @bus.publish("/boom", "bang") post "/message-bus/ABCD", - '/foo' => -1, - '/baz' => @bus.last_id('/baz') + 1, - '/boom' => -1 + "/foo" => -1, + "/baz" => @bus.last_id("/baz") + 1, + "/boom" => -1 last_response.ok?.must_equal true parsed = JSON.parse(last_response.body) @@ -218,15 +218,15 @@ def @bus.is_admin_lookup; proc { |_| true } end end it "should respond with the data if messages exist in the backlog" do - id = @bus.last_id('/foo') + id = @bus.last_id("/foo") @bus.publish("/foo", "barbs") @bus.publish("/foo", "borbs") client_id = "ABCD" post "/message-bus/#{client_id}", - '/foo' => id, - '/bar' => nil + "/foo" => id, + "/bar" => nil parsed = JSON.parse(last_response.body) parsed.length.must_equal 2 @@ -245,7 +245,7 @@ def @bus.is_admin_lookup; proc { |_| true } end # subscribed on channel 2 post "/message-bus/ABCD", - '/foo' => (msg - 1) + "/foo" => (msg - 1) parsed = JSON.parse(last_response.body) parsed.length.must_equal 0 @@ -260,7 +260,7 @@ def @bus.is_admin_lookup; proc { |_| true } end msg = @bus.publish("/global/foo", "test") post "/message-bus/ABCD", - '/global/foo' => (msg - 1) + "/global/foo" => (msg - 1) parsed = JSON.parse(last_response.body) parsed.length.must_equal 1 @@ -268,11 +268,11 @@ def @bus.is_admin_lookup; proc { |_| true } end it "should not get consumed messages" do @bus.publish("/foo", "barbs") - id = @bus.last_id('/foo') + id = @bus.last_id("/foo") client_id = "ABCD" post "/message-bus/#{client_id}", - '/foo' => id + "/foo" => id parsed = JSON.parse(last_response.body) parsed.length.must_equal 0 @@ -286,7 +286,7 @@ def @bus.is_admin_lookup; proc { |_| true } end client_id = "ABCD" post "/message-bus/#{client_id}", - '/foo' => id - 1 + "/foo" => id - 1 parsed = JSON.parse(last_response.body) parsed.length.must_equal 1 @@ -301,7 +301,7 @@ def @bus.is_admin_lookup; proc { |_| true } end end post "/message-bus/#{client_id}", - '/foo' => id - 1 + "/foo" => id - 1 parsed = JSON.parse(last_response.body) parsed.length.must_equal 1 @@ -315,7 +315,7 @@ def @bus.is_admin_lookup; proc { |_| true } end client_id = "ABCD" post "/message-bus/#{client_id}", - '/foo' => id - 1 + "/foo" => id - 1 parsed = JSON.parse(last_response.body) message = parsed.first @@ -328,19 +328,19 @@ def @bus.is_admin_lookup; proc { |_| true } end end post "/message-bus/#{client_id}", - '/foo' => id - 1 + "/foo" => id - 1 parsed = JSON.parse(last_response.body) parsed.length.must_equal 1 end it "can decode a JSON encoded request" do - id = @bus.last_id('/foo') + id = @bus.last_id("/foo") @bus.publish("/foo", json: true) post("/message-bus/1234", - JSON.generate('/foo' => id), + JSON.generate("/foo" => id), "CONTENT_TYPE" => "application/json") - JSON.parse(last_response.body).first["data"].must_equal('json' => true) + JSON.parse(last_response.body).first["data"].must_equal("json" => true) end describe "on_middleware_error handling" do @@ -356,7 +356,7 @@ def @bus.is_admin_lookup; proc { |_| true } end end post("/message-bus/1234", - JSON.generate('/foo' => 1), + JSON.generate("/foo" => 1), "CONTENT_TYPE" => "application/json") last_response.status.must_equal 407 @@ -373,7 +373,7 @@ def initialize(app) end def call(env) - @app.call(env.merge('message_bus.channels' => { '/foo' => 0 })) + @app.call(env.merge("message_bus.channels" => { "/foo" => 0 })) end end end @@ -384,16 +384,16 @@ def call(env) bar_id = @bus.publish("/bar", "testbar") post "/message-bus/ABCD", - '/foo' => foo_id - 1 + "/foo" => foo_id - 1 parsed = JSON.parse(last_response.body) - parsed.first['data'].must_equal 'testfoo' + parsed.first["data"].must_equal "testfoo" post "/message-bus/ABCD", - '/bar' => bar_id - 1 + "/bar" => bar_id - 1 parsed = JSON.parse(last_response.body) - parsed.first['data'].must_equal 'testfoo' + parsed.first["data"].must_equal "testfoo" end end end diff --git a/spec/lib/message_bus/timer_thread_spec.rb b/spec/lib/message_bus/timer_thread_spec.rb index 09908690..0a324c6c 100644 --- a/spec/lib/message_bus/timer_thread_spec.rb +++ b/spec/lib/message_bus/timer_thread_spec.rb @@ -1,5 +1,5 @@ -require_relative '../../spec_helper' -require 'message_bus/timer_thread' +require_relative "../../spec_helper" +require "message_bus/timer_thread" describe MessageBus::TimerThread do before do diff --git a/spec/lib/message_bus_spec.rb b/spec/lib/message_bus_spec.rb index 41ad9054..aa522cca 100644 --- a/spec/lib/message_bus_spec.rb +++ b/spec/lib/message_bus_spec.rb @@ -1,6 +1,6 @@ -require_relative '../spec_helper' -require 'message_bus' -require 'redis' +require_relative "../spec_helper" +require "message_bus" +require "redis" describe MessageBus do before do @@ -61,9 +61,9 @@ data3.length == 3 && data2.length == 3 && data1.length == 2 end - data1.must_equal ['bananana', "it's so fluffy"] - data2.must_equal ['banana', 'bananana', "it's so fluffy"] - data3.must_equal ['banana', 'bananana', "it's so fluffy"] + data1.must_equal ["bananana", "it's so fluffy"] + data2.must_equal ["banana", "bananana", "it's so fluffy"] + data3.must_equal ["banana", "bananana", "it's so fluffy"] end it "can transmit client_ids" do @@ -73,10 +73,10 @@ client_ids = msg.client_ids end - @bus.publish("/chuck", { yeager: true }, client_ids: ['a', 'b']) + @bus.publish("/chuck", { yeager: true }, client_ids: ["a", "b"]) wait_for(2000) { client_ids } - client_ids.must_equal ['a', 'b'] + client_ids.must_equal ["a", "b"] end it "should recover from a redis flush" do @@ -140,9 +140,9 @@ wait_for(2000) { data } - data.must_equal 'norris' - site_id.must_equal 'magic' - channel.must_equal '/chuck' + data.must_equal "norris" + site_id.must_equal "magic" + channel.must_equal "/chuck" user_ids.must_equal [1, 2, 3] end @@ -159,9 +159,9 @@ wait_for(2000) { data } - data.must_equal 'norris' - site_id.must_equal 'magic' - channel.must_equal '/chuck' + data.must_equal "norris" + site_id.must_equal "magic" + channel.must_equal "/chuck" end it "should have the ability to grab the backlog messages in the correct order" do @@ -171,7 +171,7 @@ r = @bus.backlog("/chuck", id) - r.map { |i| i.data }.to_a.must_equal ['foo', 'bar'] + r.map { |i| i.data }.to_a.must_equal ["foo", "bar"] end it "should correctly get full backlog of a channel" do @@ -179,7 +179,7 @@ @bus.publish("/chuck", "foo") @bus.publish("/chuckles", "bar") - @bus.backlog("/chuck").map { |i| i.data }.to_a.must_equal ['norris', 'foo'] + @bus.backlog("/chuck").map { |i| i.data }.to_a.must_equal ["norris", "foo"] end it "allows you to look up last_message" do @@ -203,9 +203,9 @@ wait_for(2000) { data } - data.must_equal 'norris' - site_id.must_equal 'law-and-order' - channel.must_equal '/chuck' + data.must_equal "norris" + site_id.must_equal "law-and-order" + channel.must_equal "/chuck" end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bf65d319..824eb770 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,21 +1,21 @@ $: << File.dirname(__FILE__) -$: << File.join(File.dirname(__FILE__), '..', 'lib') -require 'thin' -require 'lib/fake_async_middleware' -require 'message_bus' +$: << File.join(File.dirname(__FILE__), "..", "lib") +require "thin" +require "lib/fake_async_middleware" +require "message_bus" -require 'minitest/autorun' -require 'minitest/spec' +require "minitest/autorun" +require "minitest/spec" -backend = (ENV['MESSAGE_BUS_BACKEND'] || :redis).to_sym +backend = (ENV["MESSAGE_BUS_BACKEND"] || :redis).to_sym MESSAGE_BUS_CONFIG = { backend: backend } require "message_bus/backends/#{backend}" PUB_SUB_CLASS = MessageBus::BACKENDS.fetch(backend) case backend when :redis - MESSAGE_BUS_CONFIG.merge!(url: ENV['REDISURL']) + MESSAGE_BUS_CONFIG.merge!(url: ENV["REDISURL"]) when :postgres - MESSAGE_BUS_CONFIG.merge!(backend_options: { host: ENV['PGHOST'], user: ENV['PGUSER'] || ENV['USER'], password: ENV['PGPASSWORD'], dbname: ENV['PGDATABASE'] || 'message_bus_test' }) + MESSAGE_BUS_CONFIG.merge!(backend_options: { host: ENV["PGHOST"], user: ENV["PGUSER"] || ENV["USER"], password: ENV["PGPASSWORD"], dbname: ENV["PGDATABASE"] || "message_bus_test" }) end puts "Running with backend: #{backend}"