Skip to content

Proposal: triggers #997

Closed
Closed

Description

@coffeemug
// r.createTrigger(name, table, type, condition, action)
// r.dropTrigger(name)

// Every time someone inserts a new user older than 20, beep
r.createTrigger('test', 'users', r.insert,
  function(new_user) {
    return new_user('age').gt(20);
  },
  r.js('npm.beep()'))

// Every time someone turns 18, beep
r.createTrigger('test2', 'users', r.update,
  function(old_row, new_row) {
    return r.and(old_row('age').ne(18),
                 new_row('age').eq(18));
  },
  r.js('npm.beep()'))

// Stop beeping for twenty year olds
r.dropTrigger('test');

A couple of things:

  1. While the action could be any ReQL expression, to be really useful we have to run nodejs on the server. Then people can use things like RabbitMQ to communicate with other applications, which is immensely useful.
  2. The triggers are defined with respect to a single table, and can be run on a predefined set of operations (presumably inserts, updates/replaces, and deletes). Defining triggers with arbitrary conditions would be way too slow (since we'd have to evaluate potentially expensive conditions on every single mutation operation, it's questionable how to do that cross cluster, etc.)
  3. I think this functionality would be awesome. Obviously it's a bit away.

Activity

  1. coffeemug commented on Jun 13, 2013

    @coffeemug
    ContributorAuthor

    Actually, instead of passing the table name as a parameter to a trigger, a better way would be as follows:

    r.table('users').createTrigger('test', r.insert,
      function(new_user) {
        return new_user('age').gt(20);
      },
      r.js('npm.beep()'))
    
    // Stop beeping for twenty year olds
    r.table('users').dropTrigger('test');
  2. wmrowan commented on Jun 13, 2013

    @wmrowan
    Contributor

    For the action to be meaningful it must have a side effect. The only side effects we allow are write queries to tables. Though I've never tried to write an r.js query that had a side effect, I don't think we do anything to prevent them.

    In short, doing any meaningful action would be quite clunky. Most of the time it would mean trying to create an XMLHttpRequest from within a r.js term, yuck.

    Here's an alternative suggestion:

    # on_insert produces lazy stream of all new rows that match the predicate
    # This loop blocks until the event is triggered and a new value is returned to the cursor
    for new_user in r.table('users').on_insert(lambda new_user: new_user['age'] > 20).run():
       # Now control is returned to the client, and the application can perform the action
       stop = go_do_some_action(new_user)
       if stop:
          break # This causes the loop to exit and the cursor to be deleted
                   # Thus the trigger is "canceled" when the cursor is closed
    
    # Since we only support triggers on insert, replace, and delete, we just
    # have on_insert, on_replace, on_delete, rather than on(event, ...)
    # This is also necessary because different events have different types.
    # Here `on_replace` takes a binary function and produces results of the form {'old':..., 'new':...}
    # Note that the application is only interested in the new values so it does a map on
    # the results to select just that field.
    cursor = r.table('user').on_replace(
          lambda old_val, new_val: old_val['age'] != 18 & new_val['age'] == 18
    ).map(r.row['new']).run()
    
    for new_user in cursor:
       do_something(new_user)
    
    # We can do our side effecting in the query as well.
    # This query blocks the client thread indefinitely, the trigger is "deleted" when this query
    # exits, i.e. when the client thread is interrupted or the connection is closed
    r.table('user').on_delete(lambda dead_user: dead_user['age'] < 5).for_each(lambda du: r.table('dead_children').insert(du)).run()
  3. coffeemug commented on Jun 13, 2013

    @coffeemug
    ContributorAuthor

    yuck

    I disagree. I think embedding node into the server and allowing access to it from r.js can be an extremely powerful primitive. This way triggers can run even when there are no clients connected, which is what one wants. Requiring a client to be connected for the triggers to work introduces all sorts of deployment issues that are very non-trivial for the users to resolve.

    That being said, I didn't think of allowing triggers to bubble up events all the way up to the clients. We should definitely explore that.

  4. wmrowan commented on Jun 13, 2013

    @wmrowan
    Contributor

    Alternatively, we don't need to fold a filter into the on_* functions:

    # The filter can simply be chained
    r.table('user').on_delete().filter(lambda user: ...)
    
    # Or omitted
    # This query always returns the new size of the table when a record is deleted
    r.table('user').on_delete().map(lambda user: r.table('user').count())
    
    # on_replace would be a little more annoying to use though
    # This is how you would have to do the same query as in the previous comment
    r.table('user').on_replace().filter(r.row['old']['age'] != 18 & r.row['new']['age'] == 18).map(r.row['new'])
    
    # This also removes much of the rational for `on_*` over `on(event)`
    r.table('user').on('insert').filter(lambda new_user: ...)

    Also, I want to point out that this is finally an instance where JS's asynchronous event based nature is more fitting:

    r.table('user').onInsert().run(conn, function(err, cur) {
       cur.every(function(new_user) {
          // This function is actually an event handler and not a continuation!
          do_something(new_user);
       });
    });
  5. wmrowan commented on Jun 14, 2013

    @wmrowan
    Contributor

    The 'yuck' comment was not about the idea of using JS actions within the server but about the hoops you'd have to jump through to get something meaningful out of a triggered JS action. This is what I was imagining when I first read the proposal:

    import BaseHttpServer
    
    class NewUserHandler(BaseHttpServer.BaseHttpRequestHandler):
       def do_GET(request):
          process_request(request)
    
    r.table('users').create_trigger('inserted', lambda row: True, r.js("""function(newUser) {
    var http = require('http');
    var options = {
      host: "my_app_server.com",
      path: "/new_user_event/?user="+JSON.stringify(newUser)
    };
    
    http.request(options);
    }""").run()
    
    BaseHttpServer.HttpServer(("my_app_server.com", 80), NewUserHandler).server_forever()

    This example assumes that what you really want to do is transfer control after an event back to the application server. Since this is where the application is running, I assume that this is where the user wants to get events. In order to produce an event, at least one client has to be running and interacting with the database so I would assume it's not any more difficult to have a second application process or thread waiting on these events.

    Even so, I appreciate that for some kinds of event handlers you might want to trigger an action within the database server. I'm imagining, in particular, the out of the box experience you might have playing with events in the data explorer. To play with triggers users shouldn't have to spin up a client process and have it listen for events.

    We could build something into the web UI for events, similar to how we currently support a simplified UI for creating secondary indexes. We'd could then define a simple API for common actions so that you can easily script it and not have to go through all the steps I showed above just to send an HTTP request:

    +----------------+
    | on insert   \/ |
    +----------------+
    +----------------------------------------------------------+
    | function(new_doc) {                                         |
    |    var doc_string = JSON.stringify(new_doc);   |
    |    http.get("http://my_app/?doc="+doc_string); |
    |    fs.log("Inserted: "+doc_string);                      |
    | }                                                                        |
    +----------------------------------------------------------+
    

    For more complex event handlers in larger and more complex systems that are already using multiple client processes and servers though, I think users would appreciate the the greater flexibility of an API that allowed them to easily transfer control back to a client server running one of the drivers.

    Also, there's no reason why we can't support both kinds of event handlers. With the API I outlined, the body of the event handler (inside the for_each) can use a JS term to run some action. There are two open questions though with this approach that I can think of.

    First, we'd probably need a way for a client to create this persistent event handler and disconnect. This is not possible with the API as I first outlined it. We could get away with this though if we build support for this into the web ui. Alternatively, we could add a run option for a persistent query that continues running on the server for its side effects even after the client disconnects. Still, we'd need a way to cancel these events. Maybe such a query would return a query id which could later be used to cancel the query.

    The second is how we move from embedded v8 to node. Without node we don't get file system API's etc. However we do this it will require mucking around in a pretty fragile part of the code base. We could, however, support the web UI based JS events I outlined with a separate external node process running the JS driver rather than supporting node within the embedded JS engine backing r.js.

    Honestly, if we don't bother yet trying to integrate node in place of embedded v8, this doesn't sound like it would be that hard to implement for 1.8 or 1.9 since most of the code is in the QL layer. At least one potential user I've talked to has indicated that this is the only missing feature he's waiting on. If this is really that doable in the near term, I think this would make a really killer feature (so please excuse my enthusiasm).

  6. coffeemug commented on Jun 14, 2013

    @coffeemug
    ContributorAuthor

    Ok, this is getting a bit complex. I think we should hold this discussion until triggers are slated for a sprint. We can pick it up then.

  7. neumino commented on Jun 14, 2013

    @neumino
    Member

    If we have triggers + atomic set/get (#976), it would just awesome to run RethinkDB with meteor.

  8. kofalt commented on Aug 1, 2013

    @kofalt

    Without chiming in on the runtime bundling stuff - another way to think about triggers could be exposing events to external software and letting them handle it. The initial comment implies a model where RethinkDB fires an event off to RabbitMQ - it could be the other way around.

    This is simpler in some ways and more complex in others. How about something like couchDB's change feed? If I write an application using the python driver, for example, I'm probably going to run some python in response to a triggered event. Why not let that same software listen for changes?

    Rather open-ended so I'll stop here. I'm excited to see this feature implemented in some form or another, and I hope several different approaches are considered to arrive at a robust solution.

  9. jdoliner commented on Aug 1, 2013

    @jdoliner
    Contributor

    @kofalt we haven't been been updating this issue too much but I think we've agreed internally that a change feed is a better way to accomplish this than packaging runtimes internally. One of the biggest disadvantages of packaging runtimes is that it in distributed environments it's tough to tell which machine your code is going to run on. This can be a problem if you have some machines behind a firewall while others aren't. A stream of changes you can access through the query language and dispatch however you want in whatever language you're already using really sounds like the best solution to me.

    This functionality is unfortunately a ways off. It's probably not making it in before production readiness.

  10. kofalt commented on Aug 1, 2013

    @kofalt

    @jdoliner Great to hear regarding internal discussion on a changes feed. I thought that would be a cleaner solution than packaging a runtime, but I didn't want to squash ideas prematurely :)

    Definitely a complex feature, I'm happy to wait for triggers to be good & ready before release.

  11. defunctzombie commented on Oct 29, 2013

    @defunctzombie

    Instead of trying to support all the complex cases of triggers, I think a simple changes feed would be more ideal. Those familiar with mongodb, this would be similar to listening to the oplog and just filtering out what you are interested in. Yes, the type of queries you can listen to are limited (join, etc would be out I think), but you do get nice notifications when things change in the db. One nice aspect of such a system is having web UI interfaces across disparate browser sessions update (i.e. someone adds a new comment and it can show up on everyone's screen).

    It might be possible to retask the replication or hot backup layer to do this. I don't know what data format that thing spits out or how but I would imagine that all the db updates are present in it to allow for replication or realtime backup.

  12. coffeemug commented on Oct 30, 2013

    @coffeemug
    ContributorAuthor

    @defunctzombie -- thanks, we'll consider this approach too!

  13. jdoliner commented on Oct 30, 2013

    @jdoliner
    Contributor

    @defunctzombi this is actually more or less the way we're planning to implement this. We're pretty far away from having a concrete spec on this but I'm pretty sure it's going to look something like what you're describing.

  14. marshall007 commented on Dec 5, 2013

    @marshall007
    Contributor

    Instead of trying to support all the complex cases of triggers, I think a simple changes feed would be more ideal.

    I agree, CouchDB's concept of change notifications is a really elegant solution that solves most users needs.

    Actually, instead of passing the table name as a parameter to a trigger, a better way would be as follows:

    r.table('users').createTrigger('test', r.insert, ... )
    
    // Stop beeping for twenty year olds
    r.table('users').dropTrigger('test');
    

    In terms of the API. I think conforming to the EventEmitter pattern would be best (at least for the JS driver). It might be interesting to introduce the concept of a feed to allow arbitrary querying and more focused syntax. Example being:

    var feed = r.table('user').changes({ since: r.now(), return_vals: true });
    
    // Subscribe to all updates
    feed.on('update', function(user) {
      ...
    });
    
    // Fires on insert of a user with age >20
    feed.filter(r.row('age').gt(20)).on('insert', function(new_user) {
      ...
    });
  15. andrewreedy commented on Feb 4, 2014

    @andrewreedy

    +1

  16. 125 remaining items

  17. srh commented on Apr 9, 2014

    @srh
    Contributor

    I'd have to think more about the specific implementation details. I think the buffering should be per-server-with-cursors so that when a changefeed requests more data there doesn't need to be intracluster traffic to fetch it.

    @mlucy: We still need information on who does what where for this first version, and we also need an end-game in mind to make sure that the first version makes actual progress toward the end version (and isn't merely and equal-effort alternative implementation). Replicas going down is a side-show. What we need to know is: will all change feeds go down when a single client does an insert workload? Will all change feeds go down when two clients do an insert workload? (Or if throttling happens, the questions transform: how badly will we throttle?) To answer this we need to know what messages are being sent across the cluster and to the client, and what responses are being sent, when, in both the first implementation and in terms of what the first implementation would have, the 1.13/1.14 goal, and the end goal.

  18. coffeemug commented on Apr 9, 2014

    @coffeemug
    ContributorAuthor

    How opposed would people be to requiring that people have at least one replica on the master?

    If you're asking what I think you're asking, we already do this in practice and I can't think of scenarios where we'd want to not do it. So I think it's ok.

    Pinging @timmaxw -- Tim do you think this would be ok to bake this assumption in?

    Also, @timmaxw should probably code review this.

  19. srh commented on Apr 9, 2014

    @srh
    Contributor

    @coffeemug, it doesn't matter, if a replica is on the master we'd still miss writes.

  20. coffeemug commented on Apr 9, 2014

    @coffeemug
    ContributorAuthor

    @srh -- I think letting one bad client throttle the entire table is a bad idea. I think we should do the first version/prototype without throttling, and then test. May be feeds will go down in some situations, may be not. May be users will be ok with it, may be not. I think we should implement it and measure.

  21. danielmewes commented on Apr 9, 2014

    @danielmewes
    Member

    @srh: It matters, because we only miss writes if the master goes down. Aborting any query reading from a feed when the master goes down is acceptable and probably expected, and a master getting lost is a well defined event.
    A secondary being unavailable is more tricky, because writes will often still go through, and we are not sure if the replica is just temporarily unavailable (i.e. we should not abort feeds but just keep waiting) or permanently down (i.e. we should abort feeds),

  22. coffeemug commented on Apr 9, 2014

    @coffeemug
    ContributorAuthor

    It matters, because we only miss writes if the master goes down. Aborting any query reading from a feed when the master goes down is acceptable and probably expected, and a master getting lost is a well defined event.

    👍

  23. srh commented on Apr 9, 2014

    @srh
    Contributor

    @danielmewes We also miss writes when the parser goes down. Or when the client goes down. So worries about missing writes is an invalid reason. If a replica were on the parser, we'd want to stream changes from that instead. If a replica were in the same datacenter as the parser, and the master were not, the same is true.

  24. mlucy commented on Apr 9, 2014

    @mlucy
    Member

    I talked about this with @srh in person. Two things that complicate this implementation are:

    • Making sure that change feeds don't see writes which happened just before they started.
    • Making sure that change feeds receive changes in the right order (apparently our current mailbox_ts don't offer an ordering guarantee).
  25. mlucy commented on Apr 9, 2014

    @mlucy
    Member

    Also, we need to detect when the master goes down and terminate the feeds cleanly rather than leaving them dangling open.

  26. timmaxw commented on Apr 10, 2014

    @timmaxw
    Member

    Pinging @timmaxw -- Tim do you think this would be ok to bake this assumption in?

    I don't think that assumption breaks anything.

    But I don't think it's a useful assumption. Unless I'm misunderstanding something, the only reason to serve change feeds from the master is that if we serve change feeds from a secondary, then the secondary can die while writes continue to happen, so the client will miss some changes. But there are a lot of other things that can go wrong and cause the client to miss changes. For example, the client-server connection can be lost; the parser; or the connection between the master and the parser can be lost; or the master can go down, then back up, and writes can happen before the parser can reinstall the change feed. The long-term solution is to implement the since option and version tokens. The short-term solution of serving change feeds from the master only improves the functionality slightly, and we'll want to tear it out when we implement the long-term solution; so I don't see the point. In other words, I agree with Sam's comment two hours ago. I suggest that for the prototype, every replica should be able to serve change feeds.

    @mlucy: On a completely unrelated note, consider using the existing registrar_t and registrant_t types in your implementation of change feeds. These generic types are designed for the case where one "registrar" needs to provide some service to zero or more "registrants" on other machines in the cluster. The registrant_t will automatically notify the registrar_t in its constructor and destructor. They also will detect when the connection is lost. This might save you some boilerplate.

  27. self-assigned this
    on Apr 24, 2014
  28. neumino commented on Apr 29, 2014

    @neumino
    Member

    I have a question about feeds.
    Can I keep track of how many documents I have in a table?

    Does that works? (I mean, is it safe?)

    var count = undefined;
    r.table("test").changes().run(c, function(err, cursor) {
        cursor.forEach(function(err, change) {
            if (count === undefined) {
                count = null;
                r.table("test").count().run(c, function(err, result) {
                    count = result;
                })
            }
            else if (count != null) { // <-- Should I increment/decrement even if the count query hasn't returned yet?
                 if (change.old_val == null) {
                    count++;
                }
                else if (change.new_val == null) {
                    count--;
                 }
            }
        })
    });
  29. coffeemug commented on Apr 29, 2014

    @coffeemug
    ContributorAuthor

    This (or something like it) will work, with a caveat.

    The only issue is that the feed and count can't be run atomically now, so you might be a few items off from the beginning. If we allow the feed to run atomically along with another read query, this will work perfectly (but that won't happen in 1.13).

  30. coffeemug commented on May 22, 2014

    @coffeemug
    ContributorAuthor

    @mlucy just merged this into next -- congrats!!

    Closing this issue, we'll open specific ones for anything that remains to be done here.

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