Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add module for Rails 5.0 ActionCable streams #192

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
69 changes: 69 additions & 0 deletions lib/no_brainer/streams.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
module NoBrainer::Streams
extend ActiveSupport::Concern

included do
on_unsubscribe :stop_all_streams
end

private

def stream_from(query, options = {}, callback = nil)
if query.respond_to? :to_rql
nobrainer_stream_from(query, options, callback)
else
super(query, options, callback)
end
end

def stop_all_streams
nobrainer_stop_all_streams
super
end

def nobrainer_stream_from(query, options = {}, callback = nil)
callback ||= -> (changes) do
transmit changes, via: "streamed from #{query.inspect}"
end

# defer_subscription_confirmation!
connection = NoBrainer::Streams::streams_connection
cursor = query.to_rql.changes(options).async_run(connection, ConcurrentAsyncHandler, &callback)
nobrainer_cursors << cursor
end

def nobrainer_stop_all_streams
cursors.each do |cursor|
begin
logger.info "Closing cursor: #{cursor.inspect}"
cursor.close
rescue => e
logger.error "Could not close cursor: #{e.message}\n#{e.backtrace.join("\n")}"
end
end
end

def nobrainer_cursors
@_nobrainer_cursors ||= []
end

def self.streams_connection
@@streams_connection ||= NoBrainer::ConnectionManager.get_new_connection.raw
end

class ConcurrentAsyncHandler < RethinkDB::AsyncHandler
def run(&action)
options[:query_handle_class] = AsyncQueryHandler
yield
end

def handler
callback
end

class AsyncQueryHandler < RethinkDB::QueryHandle
def guarded_async_run(&b)
Concurrent.global_io_executor.post(&b)
end
end
end
end
2 changes: 1 addition & 1 deletion lib/nobrainer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module NoBrainer
# We eager load things that could be loaded when handling the first web request.
# Code that is loaded through the DSL of NoBrainer should not be eager loaded.
autoload :Document, :IndexManager, :Loader, :Fork, :Geo, :SymbolDecoration
eager_autoload :Config, :Connection, :ConnectionManager, :Error,
eager_autoload :Config, :Connection, :ConnectionManager, :Error, :Streams,
:QueryRunner, :Criteria, :RQL, :Lock, :ReentrantLock, :Profiler, :System

class << self
Expand Down