-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
implement actioncable streams using #async_run
- Loading branch information
Showing
2 changed files
with
57 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
module NoBrainer::Streams | ||
extend ActiveSupport::Concern | ||
|
||
included do | ||
on_unsubscribe :stop_all_streams | ||
end | ||
|
||
private | ||
|
||
def 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) | ||
cursors << cursor | ||
end | ||
|
||
def 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 cursors | ||
@_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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters