You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is intended as an analog for #3298 in the context of Ruby.
We don't presently have a good story for reading from multiple changefeeds concurrently in Ruby, as in the Python case; this should get fixed before 2.0.
Like in the Python case (prior to 3.4) and unlike in the JavaScript driver, Ruby does not bundle a way of doing nonblocking IO in the base language. Unlike in the Python case, Ruby does offer Fibers starting in 1.9. Fibers are cooperatively scheduled coroutines, more or less; they have small stacks reserved for them but the differences are very technical and they can be thought of as coroutines. So we might be able to do this without using an additional library.
Another alternative is using something like EventMachine. I have used EM before and it's rather scary, not the least of which because it uses its own I/O routines, entirely sidestepping Ruby; it also has the worst implementation of popen I have ever seen, which I swear I fixed years ago but which does not appear to have ever been accepted by upstream. So I would prefer to use Fibers here.
I think we should consider doing both (i.e. offering an EventMachine integration even if we go with fibers for the main driver). A lot of other libraries people want to use (e.g. Websocket libraries) already use EventMachine, so it would be nice if people could just hook changefeeds up to those).
I have not been a bleeding edge Ruby developer for several years, so it doesn't surprise me that people are moving away from EM given its deficiencies. I've never heard of Celluloid, though, so I'll have to look into that.
Hopefully if we support Fibers, then EM/Celluloid/InsertFrameworkDuJourHere will all be compatible.
Possible implementation: assume we have @coffeemug's .on proposal from #3298 (comment) . If we pass that a Fiber object, then we could call Fiber.resume(cursorargs). This would look like this from the client's POV:
feed1=r.table('foo').changes().run(conn).on(Fiber.newdo |change|
untilchange.nil?# ... do something ...change=Fiber.yieldendend)feed2=r.table('bar').changes().run(conn).on(Fiber.newdo |change|
untilchange.nil?# ... do something ...change=Fiber.yieldendend)# in base Ruby caseconn.poll(wait=true)
We can also invert it, with a new method, maybe .fiber(identifier), that returns a Fiber which gives us a new value every time we call yield on it. This doesn't really support readiness, tho. Also, there's probably a better name, but that'll do for the moment. We can add readiness by adding a new type that amounts to a union of the streams; so it would look like this:
feed1=r.table('foo').changes().run(conn).fiber(:foo)feed2=r.table('bar').changes().run(conn).fiber(:bar)union=feed1 + feed2# in base Ruby caseforfeed,changeinuniondocasefeedwhen:foo# do something with change from feed1when:bar# do something with change from feed2endend
With EventMachine and this .fiber thing, this would look like this:
EventMachine.rundoFiber.new{forchangeinr.table('foo').changes().run(conn).fiber# ... do somethingend}.resumeFiber.new{forchangeinr.table('bar').changes().run(conn).fiber# ... do somethingend}.resumeend
I could also imagine .on taking an object and a symbol suitable for .send; so that would make this look something like this.
classKlassdefbar(change)
...
enddeffoo(change)
...
end
...
endk=Klass.newfeed1=r.table('foo').changes().run(conn).on(k,:foo)feed2=r.table('bar').changes().run(conn).on(k,:bar)# in base Ruby caseconn.poll(wait=true)
Upon further reflection the EM examples will probably require us, on some level at least, to hitch the Ruby driver's wagon to EM's horse. I don't like this, but I don't think it's avoidable and there are EM-aware versions of several other protocols that we would need to copy.
I've been thinking about this, and I think we should:
Provide our own API that's as easy as possible to implement and reason about.
Integrate with EventMachine for people who want event-style programming.
It's obvious how to do (2); it's just a pain. For (1) I think we should do something like @coffeemug mentioned in #3298 -- we should offer a way to merge multiple lazy streams into a single lazy stream, and offer a way to figure out which . To use @coffeemug's r.join syntax:
c1=r.table('test').changes.runc2=r.table('test2').changes.runboth=c1.join(c2)# also legal: `r.join(c1, c2)`both.each{|change|
# do something with change}both.each{|change,cursor|
ifcursor == c1# also legal: cursor.query == q1# do something with changes from q1elseifcursor == c2# do something with changes from q2end}
In an offline discussion with @larkost , @coffeemug , @timmaxw and @mlucy , we decided to provide an event-loop integration in 2.0.
Since EventMachine is the most common one, we should implement support for that first.
@gchpaco described in #3678 (comment) that we could implement a fiber-based interface and then very easily put an EventMachine API on top of that. If we can re-use the fiber implementation for EventMachine I have no objections to that.
So now we just have to come up with the details of our EventMachine (and possibly fiber) API.
@mlucy since you had recently used some EventMachine framework, maybe you can describe what you think a natural EventMachine API for cursors would look like?
@mlucy can you comment on the interface? You had mentioned something about named events in the context of your Slack ReQL bot development. Which interface would seem natural to you given the other EventMachine interfaces that you have encountered?
EventMachine.run do
Fiber.new {
for change in r.table('foo').changes().run(conn).fiber
# ... do something
end
}.resume
Fiber.new {
for change in r.table('bar').changes().run(conn).fiber
# ... do something
end
}.resume
end
or alternatively one that uses on with a callback, possibly also supporting an object/method name pair:
class Klass
def bar(change)
...
end
def foo(change)
...
end
...
end
k = Klass.new
feed1 = r.table('foo').changes().run(conn).on(k, :foo)
feed2 = r.table('bar').changes().run(conn).on(k, :bar)
(not sure what this would look like exactly with EventMachine. @gchpaco can you clarify?)
Also, while I was working on this I discovered a few problems with the interface we talked about earlier (no way to get errors with the simple interface, the difference between StreamHandler and ChangeHandler stopped making since once changes worked on both, etc.). I'm making a few small changes (supporting both arity-1 and arity-2 callbacks so that you can receive an error like in JS for the simple case, have StreamHandler and ChangeHandler be just Handler where the behavior is determined by what functions you define in the subclass, etc.).
I'm going to write up a short tutorial/guide when I'm done; if after reading it people don't like the changes I'm making to the interface I'd be happy to roll them back (they aren't really the hard part at all).
The simplest way to access RethinkDB with EventMachine is to call em_run with a block. If RethinkDB returns a sequence (an array or a
stream), the block will be called with each element of that sequence.
If RethinkDB returns anything else, the block will be called once with
that value.
Example 1: iterating over a stream
# Insert some data.r.table('test').insert([{id: 0},{id: 1},{id: 2}]).run($conn)EM.run{# Print every row in the table.r.table('test').order_by(index: 'id').em_run($conn){|row|
prow}}
Will print:
{"id"=>0}{"id"=>1}{"id"=>2}
Example 2: iterating over an array
EM.run{# Print an array.r.expr([1,2,3]).em_run($conn){|n|
pn}}``Willprint:
```rb123
Example 3: accessing a single row
# Insert some data.r.table('test').insert([{id: 0},{id: 1},{id: 2}]).run($conn)EM.run{# Print a single row.r.table('test').get(0).em_run($conn){|row|
prow}}
Will print:
{"id"=>0}
Basic Error Handling
If you pass em_run a block that only accepts a single argument,
RethinkDB's EM adapter will handle errors by re-throwing them. You
can also handle errors in the block by passing em_run a block that
accepts two arguments. If you do so, then the block will either be
called with nil as its first argument and data as its second
argument, or with an error as its first argument and nil as its
second argument.
Note that it's possible for the block to be passed data many times,
and then be passed an error. For example, this can happen if you lose
availability in the middle of a long read.
[:err,"Table `test.non_existent` does not exist.\nBacktrace:\nr.table(\"non_existent\")\n^^^^^^^^^^^^^^^^^^^^^^^"]
And
# Insert some data.r.table('test').insert([{id: 0},{id: 1},{id: 2}]).run($conn)EM.run{# Print every row in the table.r.table('test').order_by(index: 'id').em_run($conn){|err,row|
iferrp[:err,err.to_s]elsep[:row,row]end}}
Will print:
[:row,{"id"=>0}][:row,{"id"=>1}][:row,{"id"=>2}]
Advanced Usage
More precise control is provided by a superclass RethinkDB::Handler.
You can write a class that inherits from RethinkDB::Handler and
overrides certain methods, then pass an instance of that class to em_run. (If you instead pass the name of the class, the RethinkDB
event machine adapter will instantiatie it for you with no arguments
and use that.)
Here's a simple example of a handler that prints things:
# Insert some data.r.table('test').insert([{id: 0},{id: 1},{id: 2}]).run($conn)EM.run{# Print every row in the table.r.table('test').order_by(index: 'id').em_run($conn,Printer)}
Sometimes you want to treat atoms differently from sequences, or to
distinguish streams from arrays. You can do that by defining on_array, on_atom, and on_stream_val. (If on_array isn't
defined but on_atom is, then arrays will be passed to on_atom. If
neither on_array nor on_atom is defined, each element of the array
will be passed to on_stream_val (or on_val if on_stream_val
isn't defined).
(Note that when you register multiple callbacks, the order they're
called in isn't guaranteed -- it would be perfectly legal for this to
have printed the result of r.expr([1, 2, 3]) first.)
Changefeeds
Changefeeds can be treated like normal streams. If you pass a block
to em_run, that block will be called with each document in the
change stream. If you pass a Handler that defines on_val or on_stream_val, that function will be called with each document in
the change stream.
If you want more granular control, there are also several changefeed
specific functions that can be defined:
on_initial_val -- if you're subscribed to a changefeed that
returns initial values (.get.changes and .order_by.limit.changes
right now), those initial values will be passed to this function.
on_change -- changes will be passed to this function.
on_change_error -- sometimes the change stream includes documents
specifying errors that don't abort the feed (e.g. if the client is
reading too slowly and the server was forced to discard changes).
Those will be passed to this function if it's defined.
on_state -- sometimes the change stream includes documents
specifying the state of the stream. Those will be passed to this
function if it's defined.
Here's our printer class with these functions defined:
# Insert some data.r.table('test').insert([{id: 0},{id: 1},{id: 2}]).run($conn)EM.run{# Subscribe to changes on the two smallest elements.r.table('test').order_by(index: 'id').limit(2).changes.em_run($conn,Printer)}
If you call Handler::stop, that handler will stop processing
changes, and any open streams which try to use that handler will close
themselves. (Note that queries registered to the handler will not
be interrupted. See Closing a QueryHandle below if you want to
interrupt a query.)
Example 1: printing the first 5 changes
classPrinter < RethinkDB::Handlerdefinitialize(max)@counter=maxstopif@counter <= 0enddefon_open# Once the changefeed is open, insert 10 rows.r.table('test').insert([{}]*10).run($conn,noreply: true)enddefon_val(val)# Every time we print a change, decrement `@counter` and stop if we hit 0.pval@counter -= 1stopif@counter <= 0endendEM.run{r.table('test').changes.em_run($conn,Printer.new(5))}
r.table('test').insert({id: 0}).run($conn)pr.table('test').get(0).run($conn)sleep="x = (new Date()).getTime(); while ((new Date()).getTime() < x + 1000) { }"slow1=r.js(sleep).do(1)EM.run{h=r.table('test').get(0).update({a: slow1},non_atomic: true).em_run($conn){}h.closeEM.stop}pr.table('test').get(0).run($conn)
Will print:
{"id"=>0}{"id"=>0}
Multiple Queries with One Handler
It's possible to register multiple queries with one Hanlder. If you
do this and you want to know which query is calling a method on your
handler, you can define that method to take an addition argument,
which will be set to the appropriate QueryHandle.
@gchpaco you mentioned earlier that it's customary in the EM world to prefix asynchronous functions with an a. Do you think em_run is fine or do you think we should rename it to arun?
As an outsider, I'd prefer em_run because it's more explicit about which framework is being used, but for users already familiar with EM things could be different.
EM tends to be of the EM::Protocols::BlahBlahBlah.connect mold, which doesn't fit the structure here (It's more like the Tornado driver with a special .connect and an otherwise ordinary .run). Celluloid is entirely different and appears to use .async.whatever.
Basically, it's Ruby. No two groups or projects can agree on any one style ;)
Activity
danielmewes commentedon Jan 28, 2015
I think it's a good idea to provide a consistent basic interface across all drivers where it makes sense, such as this one #3298 (comment) .
In addition, making sure that our driver works with Ruby Fibers sounds like a great idea to make changefeeds easy to use in Ruby.
mlucy commentedon Jan 28, 2015
I think we should consider doing both (i.e. offering an EventMachine integration even if we go with fibers for the main driver). A lot of other libraries people want to use (e.g. Websocket libraries) already use EventMachine, so it would be nice if people could just hook changefeeds up to those).
gchpaco commentedon Jan 28, 2015
Using Fiber libraries from EM appears to be fairly easy; https://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/
thelinuxlich commentedon Jan 28, 2015
I thought rubyists were moving to https://celluloid.io/ where async is concerned
gchpaco commentedon Jan 28, 2015
I have not been a bleeding edge Ruby developer for several years, so it doesn't surprise me that people are moving away from EM given its deficiencies. I've never heard of Celluloid, though, so I'll have to look into that.
Hopefully if we support Fibers, then EM/Celluloid/InsertFrameworkDuJourHere will all be compatible.
gchpaco commentedon Jan 29, 2015
Possible implementation: assume we have @coffeemug's
.onproposal from #3298 (comment) . If we pass that aFiberobject, then we could callFiber.resume(cursorargs). This would look like this from the client's POV:We can also invert it, with a new method, maybe
.fiber(identifier), that returns aFiberwhich gives us a new value every time we callyieldon it. This doesn't really support readiness, tho. Also, there's probably a better name, but that'll do for the moment. We can add readiness by adding a new type that amounts to a union of the streams; so it would look like this:With EventMachine and this
.fiberthing, this would look like this:gchpaco commentedon Jan 29, 2015
I could also imagine
.ontaking an object and a symbol suitable for.send; so that would make this look something like this.gchpaco commentedon Jan 30, 2015
Upon further reflection the EM examples will probably require us, on some level at least, to hitch the Ruby driver's wagon to EM's horse. I don't like this, but I don't think it's avoidable and there are EM-aware versions of several other protocols that we would need to copy.
coffeemug commentedon Feb 5, 2015
For reference -- see #3298 (comment). It specs a simpler API in Python that could be trivially adapted to Ruby.
mlucy commentedon Feb 9, 2015
I've been thinking about this, and I think we should:
It's obvious how to do (2); it's just a pain. For (1) I think we should do something like @coffeemug mentioned in #3298 -- we should offer a way to merge multiple lazy streams into a single lazy stream, and offer a way to figure out which . To use @coffeemug's
r.joinsyntax:mlucy commentedon Feb 9, 2015
(I think we should extend discussion on this and #3298 since it's important and we don't yet seem to know what we want to do.)
danielmewes commentedon Feb 10, 2015
In an offline discussion with @larkost , @coffeemug , @timmaxw and @mlucy , we decided to provide an event-loop integration in 2.0.
Since EventMachine is the most common one, we should implement support for that first.
@gchpaco described in #3678 (comment) that we could implement a fiber-based interface and then very easily put an EventMachine API on top of that. If we can re-use the fiber implementation for EventMachine I have no objections to that.
So now we just have to come up with the details of our EventMachine (and possibly fiber) API.
@mlucy since you had recently used some EventMachine framework, maybe you can describe what you think a natural EventMachine API for cursors would look like?
danielmewes commentedon Feb 16, 2015
We should get this going.
@mlucy can you comment on the interface? You had mentioned something about named events in the context of your Slack ReQL bot development. Which interface would seem natural to you given the other EventMachine interfaces that you have encountered?
So far @gchpaco has suggested this interface:
or alternatively one that uses
onwith a callback, possibly also supporting an object/method name pair:(not sure what this would look like exactly with EventMachine. @gchpaco can you clarify?)
27 remaining items
mlucy commentedon Mar 12, 2015
Also, while I was working on this I discovered a few problems with the interface we talked about earlier (no way to get errors with the simple interface, the difference between
StreamHandlerandChangeHandlerstopped making since once changes worked on both, etc.). I'm making a few small changes (supporting both arity-1 and arity-2 callbacks so that you can receive an error like in JS for the simple case, haveStreamHandlerandChangeHandlerbe justHandlerwhere the behavior is determined by what functions you define in the subclass, etc.).I'm going to write up a short tutorial/guide when I'm done; if after reading it people don't like the changes I'm making to the interface I'd be happy to roll them back (they aren't really the hard part at all).
gchpaco commentedon Mar 12, 2015
How charming. Well, that happens, thank you for taking it on.
coffeemug commentedon Mar 12, 2015
I'd go with the second option because the user is always right, (unless they're not, but in this case I think they are).
mlucy commentedon Mar 13, 2015
This is in CR 2716. The brief tutorial I promised is below.
mlucy commentedon Mar 13, 2015
Accessing RethinkDB with EventMachine
Basic Usage
The simplest way to access RethinkDB with EventMachine is to call
em_runwith a block. If RethinkDB returns a sequence (an array or astream), the block will be called with each element of that sequence.
If RethinkDB returns anything else, the block will be called once with
that value.
Example 1: iterating over a stream
Will print:
Example 2: iterating over an array
Example 3: accessing a single row
Will print:
Basic Error Handling
If you pass
em_runa block that only accepts a single argument,RethinkDB's EM adapter will handle errors by re-throwing them. You
can also handle errors in the block by passing
em_runa block thataccepts two arguments. If you do so, then the block will either be
called with
nilas its first argument and data as its secondargument, or with an error as its first argument and
nilas itssecond argument.
Note that it's possible for the block to be passed data many times,
and then be passed an error. For example, this can happen if you lose
availability in the middle of a long read.
Example 1: re-thrown errors
Will produce an error:
Example 2: handling errors in the block
Will print:
And
Will print:
Advanced Usage
More precise control is provided by a superclass
RethinkDB::Handler.You can write a class that inherits from
RethinkDB::Handlerandoverrides certain methods, then pass an instance of that class to
em_run. (If you instead pass the name of the class, the RethinkDBevent machine adapter will instantiatie it for you with no arguments
and use that.)
Here's a simple example of a handler that prints things:
Example 1: handling a stream
Will print:
Granular Advanced Usage
Sometimes you want to treat atoms differently from sequences, or to
distinguish streams from arrays. You can do that by defining
on_array,on_atom, andon_stream_val. (Ifon_arrayisn'tdefined but
on_atomis, then arrays will be passed toon_atom. Ifneither
on_arraynoron_atomis defined, each element of the arraywill be passed to
on_stream_val(oron_valifon_stream_valisn't defined).
Example 1: handling granular results
Will print:
(Note that when you register multiple callbacks, the order they're
called in isn't guaranteed -- it would be perfectly legal for this to
have printed the result of
r.expr([1, 2, 3])first.)Changefeeds
Changefeeds can be treated like normal streams. If you pass a block
to
em_run, that block will be called with each document in thechange stream. If you pass a
Handlerthat defineson_valoron_stream_val, that function will be called with each document inthe change stream.
If you want more granular control, there are also several changefeed
specific functions that can be defined:
on_initial_val-- if you're subscribed to a changefeed thatreturns initial values (
.get.changesand.order_by.limit.changesright now), those initial values will be passed to this function.
on_change-- changes will be passed to this function.on_change_error-- sometimes the change stream includes documentsspecifying errors that don't abort the feed (e.g. if the client is
reading too slowly and the server was forced to discard changes).
Those will be passed to this function if it's defined.
on_state-- sometimes the change stream includes documentsspecifying the state of the stream. Those will be passed to this
function if it's defined.
Here's our printer class with these functions defined:
Example 1:
.order_by.limit.changesWill print:
If you then insert a new row with an
idof 0.5:It will replace
{id: 1}in the set with{id: 0.5}:If the table is then dropped:
The changefeed will receive an error and be closed:
Stopping a Handler
If you call
Handler::stop, that handler will stop processingchanges, and any open streams which try to use that handler will close
themselves. (Note that queries registered to the handler will not
be interrupted. See Closing a QueryHandle below if you want to
interrupt a query.)
Example 1: printing the first 5 changes
Will print:
Example 2: stopping a changefeed based on another changefeed
Will print changes to the table
testuntil you runr.table('commands').insert({stop: true}).Closing a QueryHandle
em_runreturns aQueryHandle. Callingcloseon thatQueryHandlewill close it and interrupt any outstanding queriesassociated with the
QueryHandle.Example 1: Printing the first 3 elements of a table
Will print:
Example 2: Aborting a long-running query
Will print:
Multiple Queries with One Handler
It's possible to register multiple queries with one
Hanlder. If youdo this and you want to know which query is calling a method on your
handler, you can define that method to take an addition argument,
which will be set to the appropriate
QueryHandle.Example 1: Printing changes to multiple tables
Will print:
deontologician commentedon Mar 18, 2015
Is this review still going on? I would like to use this in the logstash plugins if possible
mlucy commentedon Mar 18, 2015
The review is still going on, but you can develop off of
mlucy_em_integrationuntil it's done.mlucy commentedon Mar 18, 2015
(Er, to be clearer,
mlucy_em_integrationis a branch.)deontologician commentedon Mar 18, 2015
cool, thanks
danielmewes commentedon Mar 18, 2015
I'm excited about this 👏 .
@gchpaco you mentioned earlier that it's customary in the EM world to prefix asynchronous functions with an
a. Do you thinkem_runis fine or do you think we should rename it toarun?As an outsider, I'd prefer
em_runbecause it's more explicit about which framework is being used, but for users already familiar with EM things could be different.mlucy commentedon Mar 23, 2015
This is in next and 2.0.x . @chipotle -- I updated the documentation comment above, it should be complete now.
gchpaco commentedon Mar 24, 2015
EM tends to be of the
EM::Protocols::BlahBlahBlah.connectmold, which doesn't fit the structure here (It's more like the Tornado driver with a special.connectand an otherwise ordinary.run). Celluloid is entirely different and appears to use.async.whatever.Basically, it's Ruby. No two groups or projects can agree on any one style ;)
danielmewes commentedon Mar 24, 2015
Fair enough. I think our current interface is fine then.