sse-rails-engine 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (50) hide show
  1. checksums.yaml +7 -0
  2. data/Rakefile +35 -0
  3. data/app/controllers/sse_rails_engine/application_controller.rb +4 -0
  4. data/app/controllers/sse_rails_engine/sse_controller.rb +13 -0
  5. data/config/initializers/sse_rails_engine.rb +2 -0
  6. data/config/routes.rb +3 -0
  7. data/lib/sse-rails-engine.rb +30 -0
  8. data/lib/sse_rails_engine/engine.rb +7 -0
  9. data/lib/sse_rails_engine/manager.rb +68 -0
  10. data/lib/sse_rails_engine/version.rb +3 -0
  11. data/lib/tasks/sse_rails_engine_tasks.rake +4 -0
  12. data/test/controllers/sse_rails_engine/sse_controller_test.rb +23 -0
  13. data/test/dummy/Rakefile +6 -0
  14. data/test/dummy/app/assets/javascripts/application.js +13 -0
  15. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  16. data/test/dummy/app/controllers/application_controller.rb +5 -0
  17. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  18. data/test/dummy/bin/bundle +3 -0
  19. data/test/dummy/bin/rails +4 -0
  20. data/test/dummy/bin/rake +4 -0
  21. data/test/dummy/bin/setup +29 -0
  22. data/test/dummy/config.ru +4 -0
  23. data/test/dummy/config/application.rb +29 -0
  24. data/test/dummy/config/boot.rb +5 -0
  25. data/test/dummy/config/environment.rb +5 -0
  26. data/test/dummy/config/environments/development.rb +38 -0
  27. data/test/dummy/config/environments/production.rb +76 -0
  28. data/test/dummy/config/environments/test.rb +42 -0
  29. data/test/dummy/config/initializers/assets.rb +11 -0
  30. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  31. data/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  32. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  33. data/test/dummy/config/initializers/inflections.rb +16 -0
  34. data/test/dummy/config/initializers/mime_types.rb +4 -0
  35. data/test/dummy/config/initializers/session_store.rb +3 -0
  36. data/test/dummy/config/initializers/wrap_parameters.rb +9 -0
  37. data/test/dummy/config/locales/en.yml +23 -0
  38. data/test/dummy/config/routes.rb +3 -0
  39. data/test/dummy/config/secrets.yml +22 -0
  40. data/test/dummy/log/development.log +0 -0
  41. data/test/dummy/log/test.log +357 -0
  42. data/test/dummy/public/404.html +67 -0
  43. data/test/dummy/public/422.html +67 -0
  44. data/test/dummy/public/500.html +66 -0
  45. data/test/dummy/public/favicon.ico +0 -0
  46. data/test/integration/navigation_test.rb +9 -0
  47. data/test/lib/sse_rails_engine/manager_test.rb +40 -0
  48. data/test/lib/sse_rails_engine_test.rb +50 -0
  49. data/test/test_helper.rb +27 -0
  50. metadata +202 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9588b7d4742873aa7d61489b824970e2c75242ab
4
+ data.tar.gz: 6e4e448cd2c510b4f05e0b0e261cc87814ea0b86
5
+ SHA512:
6
+ metadata.gz: b75e9bb0140fc7a88c958cbec8337319c46add07ef6db3767b4d3d4beff26dc070d605027de9b0b0d160d23bbdfe55cdadeb39574a8f0c8dfef9f7f4933e71b9
7
+ data.tar.gz: fdaf7bea23120d4b7e5b0c6855c04bf78d5a06db14cb63232f6e24974c922da091a854df590172f4bf767c3e54afb658b55b8d8dfea5ad26d1d2f3fee17e5994
data/Rakefile ADDED
@@ -0,0 +1,35 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'SseRailsEngine'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.rdoc')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+
18
+
19
+ load 'rails/tasks/statistics.rake'
20
+
21
+
22
+
23
+ Bundler::GemHelper.install_tasks
24
+
25
+ require 'rake/testtask'
26
+
27
+ Rake::TestTask.new(:test) do |t|
28
+ t.libs << 'lib'
29
+ t.libs << 'test'
30
+ t.pattern = 'test/**/*_test.rb'
31
+ t.verbose = false
32
+ end
33
+
34
+
35
+ task default: :test
@@ -0,0 +1,4 @@
1
+ module SseRailsEngine
2
+ class ApplicationController < ActionController::Base
3
+ end
4
+ end
@@ -0,0 +1,13 @@
1
+ require_dependency "sse_rails_engine/application_controller"
2
+
3
+ module SseRailsEngine
4
+ class SseController < ApplicationController
5
+ include ActionController::Live
6
+
7
+ def connect
8
+ SseRailsEngine.manager.register(response)
9
+ SseRailsEngine.wait_for_disconnect(response)
10
+ render json: {}
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,2 @@
1
+
2
+ Rails.configuration.middleware.delete "Rack::Lock"
data/config/routes.rb ADDED
@@ -0,0 +1,3 @@
1
+ SseRailsEngine::Engine.routes.draw do
2
+ root to: 'sse#connect'
3
+ end
@@ -0,0 +1,30 @@
1
+ require 'sse_rails_engine/engine'
2
+ require 'sse_rails_engine/manager'
3
+
4
+ module SseRailsEngine
5
+ mattr_accessor :disconnect_wait_time
6
+ mattr_accessor :heartbeat_interval
7
+
8
+ @@disconnect_wait_time = 3.seconds
9
+ @@heartbeat_interval = 5.seconds
10
+
11
+ def self.manager
12
+ @manager ||= Manager.new
13
+ end
14
+
15
+ def self.wait_for_disconnect(response)
16
+ loop do
17
+ sleep disconnect_wait_time
18
+ break unless manager.registered?(response)
19
+ end
20
+ true
21
+ end
22
+
23
+ def self.send_event(name, data)
24
+ manager.send_event(name, data)
25
+ end
26
+
27
+ def self.setup
28
+ yield self
29
+ end
30
+ end
@@ -0,0 +1,7 @@
1
+ module SseRailsEngine
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace SseRailsEngine
4
+
5
+ config.sse_rails_engine = SseRailsEngine
6
+ end
7
+ end
@@ -0,0 +1,68 @@
1
+ module SseRailsEngine
2
+ class Manager
3
+ attr_reader :connections
4
+
5
+ def initialize
6
+ @mutex = Mutex.new
7
+ @connections = {}
8
+ start_heartbeats
9
+ end
10
+
11
+ def register(response)
12
+ ActiveRecord::Base.clear_active_connections! if defined?(ActiveRecord)
13
+ response.headers['Content-Type'] = 'text/event-stream'
14
+ response.headers['Cache-Control'] = 'no-cache'
15
+ @mutex.synchronize do
16
+ @connections[response.stream] = ActionController::Live::SSE.new(response.stream)
17
+ end
18
+ end
19
+
20
+ def registered?(response)
21
+ @mutex.synchronize do
22
+ @connections[response.stream] ? true : false
23
+ end
24
+ end
25
+
26
+ def unregister(response)
27
+ @mutex.synchronize do
28
+ close_connection(response.stream)
29
+ end
30
+ end
31
+
32
+ def send_event(name, data)
33
+ @mutex.synchronize do
34
+ @connections.dup.each do |stream, sse|
35
+ begin
36
+ sse.write(data, event: name)
37
+ rescue ActionController::Live::ClientDisconnected
38
+ close_connection(stream)
39
+ rescue => ex
40
+ Rails.logger.error "Failed to send event to SSE: #{stream} (#{name}, #{data} - #{ex.message}"
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ private
47
+
48
+ def close_connection(stream)
49
+ return if @connections[stream].nil?
50
+ @connections[stream].close
51
+ @connections.delete(stream)
52
+ stream.close unless stream.closed?
53
+ end
54
+
55
+ def heartbeat
56
+ send_event('heartbeat', '')
57
+ end
58
+
59
+ def start_heartbeats
60
+ Thread.new do
61
+ loop do
62
+ sleep SseRailsEngine.heartbeat_interval
63
+ heartbeat
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,3 @@
1
+ module SseRailsEngine
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :sse_rails_engine do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,23 @@
1
+ require_relative '../../test_helper'
2
+
3
+ describe SseRailsEngine::SseController do
4
+ before do
5
+ SseRailsEngine.instance_variable_set(:@manager, nil)
6
+ @routes = SseRailsEngine::Engine.routes
7
+ end
8
+
9
+ it 'registers new connections' do
10
+ SseRailsEngine.expects(:wait_for_disconnect).returns(true)
11
+ get :connect
12
+ assert_response :success
13
+ SseRailsEngine.manager.connections.size.must_equal 1
14
+ end
15
+
16
+ it 'sends event to connection' do
17
+ SseRailsEngine.expects(:wait_for_disconnect).returns(true)
18
+ get :connect
19
+ SseRailsEngine.manager.connections.size.must_equal 1
20
+ ActionController::Live::SSE.any_instance.expects(:write).with('bar', event: 'foo').once
21
+ SseRailsEngine.send_event('foo', 'bar')
22
+ end
23
+ end
@@ -0,0 +1,6 @@
1
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
2
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3
+
4
+ require File.expand_path('../config/application', __FILE__)
5
+
6
+ Rails.application.load_tasks
@@ -0,0 +1,13 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // compiled file.
9
+ //
10
+ // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require_tree .
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any styles
10
+ * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11
+ * file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,5 @@
1
+ class ApplicationController < ActionController::Base
2
+ # Prevent CSRF attacks by raising an exception.
3
+ # For APIs, you may want to use :null_session instead.
4
+ protect_from_forgery with: :exception
5
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6
+ <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3
+ load Gem.bin_path('bundler', 'bundle')
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
3
+ require_relative '../config/boot'
4
+ require 'rails/commands'
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require_relative '../config/boot'
3
+ require 'rake'
4
+ Rake.application.run
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ require 'pathname'
3
+
4
+ # path to your application root.
5
+ APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
6
+
7
+ Dir.chdir APP_ROOT do
8
+ # This script is a starting point to setup your application.
9
+ # Add necessary setup steps to this file:
10
+
11
+ puts "== Installing dependencies =="
12
+ system "gem install bundler --conservative"
13
+ system "bundle check || bundle install"
14
+
15
+ # puts "\n== Copying sample files =="
16
+ # unless File.exist?("config/database.yml")
17
+ # system "cp config/database.yml.sample config/database.yml"
18
+ # end
19
+
20
+ puts "\n== Preparing database =="
21
+ system "bin/rake db:setup"
22
+
23
+ puts "\n== Removing old logs and tempfiles =="
24
+ system "rm -f log/*"
25
+ system "rm -rf tmp/cache"
26
+
27
+ puts "\n== Restarting application server =="
28
+ system "touch tmp/restart.txt"
29
+ end
@@ -0,0 +1,4 @@
1
+ # This file is used by Rack-based servers to start the application.
2
+
3
+ require ::File.expand_path('../config/environment', __FILE__)
4
+ run Rails.application
@@ -0,0 +1,29 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ # Pick the frameworks you want:
4
+ # require "active_record/railtie"
5
+ require "action_controller/railtie"
6
+ require "action_mailer/railtie"
7
+ require "action_view/railtie"
8
+ require "sprockets/railtie"
9
+ require "rails/test_unit/railtie"
10
+
11
+ Bundler.require(*Rails.groups)
12
+ require "sse-rails-engine"
13
+
14
+ module Dummy
15
+ class Application < Rails::Application
16
+ # Settings in config/environments/* take precedence over those specified here.
17
+ # Application configuration should go into files in config/initializers
18
+ # -- all .rb files in that directory are automatically loaded.
19
+
20
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
21
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
22
+ # config.time_zone = 'Central Time (US & Canada)'
23
+
24
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
25
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
26
+ # config.i18n.default_locale = :de
27
+ end
28
+ end
29
+
@@ -0,0 +1,5 @@
1
+ # Set up gems listed in the Gemfile.
2
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
3
+
4
+ require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
5
+ $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
@@ -0,0 +1,5 @@
1
+ # Load the Rails application.
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the Rails application.
5
+ Rails.application.initialize!
@@ -0,0 +1,38 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # In the development environment your application's code is reloaded on
5
+ # every request. This slows down response time but is perfect for development
6
+ # since you don't have to restart the web server when you make code changes.
7
+ config.cache_classes = false
8
+
9
+ # Do not eager load code on boot.
10
+ config.eager_load = false
11
+
12
+ # Show full error reports and disable caching.
13
+ config.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Don't care if the mailer can't send.
17
+ config.action_mailer.raise_delivery_errors = false
18
+
19
+ # Print deprecation notices to the Rails logger.
20
+ config.active_support.deprecation = :log
21
+
22
+ # Debug mode disables concatenation and preprocessing of assets.
23
+ # This option may cause significant delays in view rendering with a large
24
+ # number of complex assets.
25
+ config.assets.debug = true
26
+
27
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
28
+ # yet still be able to expire them through the digest params.
29
+ config.assets.digest = true
30
+
31
+ # Adds additional error checking when serving assets at runtime.
32
+ # Checks for improperly declared sprockets dependencies.
33
+ # Raises helpful error messages.
34
+ config.assets.raise_runtime_errors = true
35
+
36
+ # Raises error for missing translations
37
+ # config.action_view.raise_on_missing_translations = true
38
+ end
@@ -0,0 +1,76 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # Code is not reloaded between requests.
5
+ config.cache_classes = true
6
+
7
+ # Eager load code on boot. This eager loads most of Rails and
8
+ # your application in memory, allowing both threaded web servers
9
+ # and those relying on copy on write to perform better.
10
+ # Rake tasks automatically ignore this option for performance.
11
+ config.eager_load = true
12
+
13
+ # Full error reports are disabled and caching is turned on.
14
+ config.consider_all_requests_local = false
15
+ config.action_controller.perform_caching = true
16
+
17
+ # Enable Rack::Cache to put a simple HTTP cache in front of your application
18
+ # Add `rack-cache` to your Gemfile before enabling this.
19
+ # For large-scale production use, consider using a caching reverse proxy like
20
+ # NGINX, varnish or squid.
21
+ # config.action_dispatch.rack_cache = true
22
+
23
+ # Disable serving static files from the `/public` folder by default since
24
+ # Apache or NGINX already handles this.
25
+ config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
26
+
27
+ # Compress JavaScripts and CSS.
28
+ config.assets.js_compressor = :uglifier
29
+ # config.assets.css_compressor = :sass
30
+
31
+ # Do not fallback to assets pipeline if a precompiled asset is missed.
32
+ config.assets.compile = false
33
+
34
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
35
+ # yet still be able to expire them through the digest params.
36
+ config.assets.digest = true
37
+
38
+ # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
39
+
40
+ # Specifies the header that your server uses for sending files.
41
+ # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
42
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
43
+
44
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
45
+ # config.force_ssl = true
46
+
47
+ # Use the lowest log level to ensure availability of diagnostic information
48
+ # when problems arise.
49
+ config.log_level = :debug
50
+
51
+ # Prepend all log lines with the following tags.
52
+ # config.log_tags = [ :subdomain, :uuid ]
53
+
54
+ # Use a different logger for distributed setups.
55
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
56
+
57
+ # Use a different cache store in production.
58
+ # config.cache_store = :mem_cache_store
59
+
60
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server.
61
+ # config.action_controller.asset_host = 'http://assets.example.com'
62
+
63
+ # Ignore bad email addresses and do not raise email delivery errors.
64
+ # Set this to true and configure the email server for immediate delivery to raise delivery errors.
65
+ # config.action_mailer.raise_delivery_errors = false
66
+
67
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
68
+ # the I18n.default_locale when a translation cannot be found).
69
+ config.i18n.fallbacks = true
70
+
71
+ # Send deprecation notices to registered listeners.
72
+ config.active_support.deprecation = :notify
73
+
74
+ # Use default logging formatter so that PID and timestamp are not suppressed.
75
+ config.log_formatter = ::Logger::Formatter.new
76
+ end