Skip to content

Reading from multiple changefeeds in Ruby #3678

Closed

Description

@gchpaco

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.

Activity

  1. added this to the 2.0 milestone on Jan 28, 2015
  2. danielmewes commented on Jan 28, 2015

    @danielmewes
    Member

    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.

  3. mlucy commented on Jan 28, 2015

    @mlucy
    Member

    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).

  4. gchpaco commented on Jan 28, 2015

    @gchpaco
    ContributorAuthor
  5. thelinuxlich commented on Jan 28, 2015

    @thelinuxlich

    I thought rubyists were moving to https://celluloid.io/ where async is concerned

  6. gchpaco commented on Jan 28, 2015

    @gchpaco
    ContributorAuthor

    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.

  7. gchpaco commented on Jan 29, 2015

    @gchpaco
    ContributorAuthor

    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.new do |change|
      until change.nil?
        # ... do something ...
        change = Fiber.yield
      end
    end)
    feed2 = r.table('bar').changes().run(conn).on(Fiber.new do |change|
      until change.nil?
        # ... do something ...
        change = Fiber.yield
      end
    end)
    # in base Ruby case
    conn.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 case
    for feed, change in union do
        case feed
        when :foo
            # do something with change from feed1
        when :bar
            # do something with change from feed2
        end
    end

    With EventMachine and this .fiber thing, this would look like this:

    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
  8. gchpaco commented on Jan 29, 2015

    @gchpaco
    ContributorAuthor

    I could also imagine .on taking an object and a symbol suitable for .send; so that would make this look something like this.

    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)
    # in base Ruby case
    conn.poll(wait=true)
  9. gchpaco commented on Jan 30, 2015

    @gchpaco
    ContributorAuthor

    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.

  10. coffeemug commented on Feb 5, 2015

    @coffeemug
    Contributor

    For reference -- see #3298 (comment). It specs a simpler API in Python that could be trivially adapted to Ruby.

  11. mlucy commented on Feb 9, 2015

    @mlucy
    Member

    I've been thinking about this, and I think we should:

    1. Provide our own API that's as easy as possible to implement and reason about.
    2. 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.run
    c2 = r.table('test2').changes.run
    both = c1.join(c2) # also legal: `r.join(c1, c2)`
    both.each {|change|
      # do something with change
    }
    both.each {|change, cursor|
      if cursor == c1 # also legal: cursor.query == q1
        # do something with changes from q1
      else if cursor == c2
        # do something with changes from q2
      end
    }
  12. mlucy commented on Feb 9, 2015

    @mlucy
    Member

    (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.)

  13. danielmewes commented on Feb 10, 2015

    @danielmewes
    Member

    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?

  14. danielmewes commented on Feb 16, 2015

    @danielmewes
    Member

    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:

    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?)

  15. 27 remaining items

  16. mlucy commented on Mar 12, 2015

    @mlucy
    Member

    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).

  17. gchpaco commented on Mar 12, 2015

    @gchpaco
    ContributorAuthor

    How charming. Well, that happens, thank you for taking it on.

  18. coffeemug commented on Mar 12, 2015

    @coffeemug
    Contributor

    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).

  19. mlucy commented on Mar 13, 2015

    @mlucy
    Member

    This is in CR 2716. The brief tutorial I promised is below.

  20. mlucy commented on Mar 13, 2015

    @mlucy
    Member

    Accessing RethinkDB with EventMachine

    Basic Usage

    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|
        p row
      }
    }

    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|
        p n
      }
    }
    ``
    
    Will print:
    
    ```rb
    1
    2
    3

    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|
        p row
      }
    }

    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.

    Example 1: re-thrown errors

    EM.run {
      r.table('non_existent').em_run($conn) {|row|
        p row
      }
    }

    Will produce an error:

    RethinkDB::RqlRuntimeError: Table `test.non_existent` does not exist.
    Backtrace:
    r.table("non_existent")
    ^^^^^^^^^^^^^^^^^^^^^^^

    Example 2: handling errors in the block

    EM.run {
      r.table('non_existent').em_run($conn) {|err, row|
        if err
          p [:err, err.to_s]
        else
          p [:row, row]
        end
      }
    }

    Will print:

    [: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|
        if err
          p [:err, err.to_s]
        else
          p [: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:

    class Printer < RethinkDB::Handler
      def on_open
        p :open
      end
      def on_close
        p :closed
      end
      def on_error(err)
        p [:err, err.to_s]
      end
      def on_val(val)
        p [:val, val]
      end
    end

    Example 1: handling 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, Printer)
    }

    Will print:

    :open
    [:val, {"id"=>0}]
    [:val, {"id"=>1}]
    [:val, {"id"=>2}]
    :closed

    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, 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).

    class Printer < RethinkDB::Handler
      def on_open
        p :open
      end
      def on_close
        p :closed
      end
      def on_error(err)
        p [:err, err.to_s]
      end
      def on_atom(atom)
        p [:atom, atom]
      end
      def on_array(array)
        p [:array, array]
      end
      def on_stream_val(val)
        p [:stream_val, val]
      end
    end

    Example 1: handling granular results

    # 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)
      # Print an array.
      r.expr([1, 2, 3]).em_run($conn, Printer)
      # Print a single row.
      r.table('test').get(0).em_run($conn, Printer)
    }
    

    Will print:

    :open
    [:stream_val, {"id"=>0}]
    [:stream_val, {"id"=>1}]
    [:stream_val, {"id"=>2}]
    :closed
    :open
    [:array, [1, 2, 3]]
    :closed
    :open
    [:atom, {"id"=>0}]
    :closed
    

    (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:

    class Printer < RethinkDB::Handler
      def on_open
        p :open
      end
      def on_close
        p :closed
      end
      def on_error(err)
        p [:err, err.to_s]
      end
    
      def on_change_error(err_str)
        p [:change_error, err_str]
      end
      def on_initial_val(val)
        p [:initial_val, val]
      end
      def on_state(state)
        p [:state, state]
      end
      def on_change(old_val, new_val)
        p [:change, old_val, new_val]
      end
    end

    Example 1: .order_by.limit.changes

    # 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)
    }

    Will print:

    :open
    [:state, "initializing"]
    [:initial_val, {"id"=>1}]
    [:initial_val, {"id"=>0}]
    [:state, "ready"]

    If you then insert a new row with an id of 0.5:

    r.table('test').insert({id: 0.5}).run($conn)

    It will replace {id: 1} in the set with {id: 0.5}:

    [:change, {"id"=>1}, {"id"=>0.5}]

    If the table is then dropped:

    r.table_drop('test').run($conn)

    The changefeed will receive an error and be closed:

    [:err, "Changefeed aborted (table unavailable).\nBacktrace:\nr.table(\"test\").changes\n^^^^^^^^^^^^^^^^^^^^^^^"]
    :closed

    Stopping a Handler

    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

    class Printer < RethinkDB::Handler
      def initialize(max)
        @counter = max
        stop if @counter <= 0
      end
      def on_open
        # Once the changefeed is open, insert 10 rows.
        r.table('test').insert([{}]*10).run($conn, noreply: true)
      end
      def on_val(val)
        # Every time we print a change, decrement `@counter` and stop if we hit 0.
        p val
        @counter -= 1
        stop if @counter <= 0
      end
    end
    
    EM.run {
      r.table('test').changes.em_run($conn, Printer.new(5))
    }

    Will print:

    {"old_val"=>nil, "new_val"=>{"id"=>"07cb420f-905b-4cbf-bd82-b4885babe1e1"}}
    {"old_val"=>nil, "new_val"=>{"id"=>"4517ba6d-5511-405d-8991-682ca0a375fd"}}
    {"old_val"=>nil, "new_val"=>{"id"=>"c5f1074e-7a72-403c-bfe9-9d7d7de4a2e9"}}
    {"old_val"=>nil, "new_val"=>{"id"=>"f41daf81-fa00-40be-97e8-bba02fedd9ae"}}
    {"old_val"=>nil, "new_val"=>{"id"=>"1975449c-9cd7-4a3b-b027-1b9bdabf1299"}}
    

    Example 2: stopping a changefeed based on another changefeed

    class Printer < RethinkDB::Handler
      def on_val(val)
        p val
      end
    end
    
    EM.run {
      printer = Printer.new
      r.table('test').changes.em_run($conn, Printer)
      r.table('commands').changes['new_val']['stop'].em_run($conn) {|should_stop|
        printer.stop if should_stop
      }
    }

    Will print changes to the table test until you run
    r.table('commands').insert({stop: true}).

    Closing a QueryHandle

    em_run returns a QueryHandle. Calling close on that
    QueryHandle will close it and interrupt any outstanding queries
    associated with the QueryHandle.

    Example 1: Printing the first 3 elements of a table

    r.table('test').insert((0...10).map{|i| {id: i}}).run
    EM.run {
      printed = 0
      handle = r.table('test').order_by(index: 'id').em_run($conn) {|res|
        printed += 1
        if printed > 3
          handle.close
        else
          p res
        end
      }
    }

    Will print:

    {"id"=>0}
    {"id"=>1}
    {"id"=>2}

    Example 2: Aborting a long-running query

    r.table('test').insert({id: 0}).run($conn)
    p r.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.close
      EM.stop
    }
    p r.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.

    Example 1: Printing changes to multiple tables

    class Printer < RethinkDB::Handler
      def on_open(handle)
        p [:open, $names[handle]]
      end
      def on_close(handle)
        @closed = @closed.to_i + 1
        p [:close, $names[handle]]
        EM.stop if @closed == 2
      end
      def on_val(val, handle)
        p [:val, val, $names[handle]]
      end
    end
    
    EM.run {
      printer = Printer.new
      h1 = r.expr(1).em_run($conn, printer)
      h2 = r.expr(2).em_run($conn, printer)
      $names = {h1 => "h1", h2 => "h2"}
    }

    Will print:

    [:open, "h1"]
    [:val, 1, "h1"]
    [:close, "h1"]
    [:open, "h2"]
    [:val, 2, "h2"]
    [:close, "h2"]
    
  21. deontologician commented on Mar 18, 2015

    @deontologician
    Contributor

    Is this review still going on? I would like to use this in the logstash plugins if possible

  22. mlucy commented on Mar 18, 2015

    @mlucy
    Member

    The review is still going on, but you can develop off of mlucy_em_integration until it's done.

  23. mlucy commented on Mar 18, 2015

    @mlucy
    Member

    (Er, to be clearer, mlucy_em_integration is a branch.)

  24. deontologician commented on Mar 18, 2015

    @deontologician
    Contributor

    cool, thanks

  25. danielmewes commented on Mar 18, 2015

    @danielmewes
    Member

    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 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.

  26. mlucy commented on Mar 23, 2015

    @mlucy
    Member

    This is in next and 2.0.x . @chipotle -- I updated the documentation comment above, it should be complete now.

  27. gchpaco commented on Mar 24, 2015

    @gchpaco
    ContributorAuthor

    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 ;)

  28. danielmewes commented on Mar 24, 2015

    @danielmewes
    Member

    Fair enough. I think our current interface is fine then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions