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
// r.createTrigger(name, table, type, condition, action)// r.dropTrigger(name)// Every time someone inserts a new user older than 20, beepr.createTrigger('test','users',r.insert,function(new_user){returnnew_user('age').gt(20);},r.js('npm.beep()'))// Every time someone turns 18, beepr.createTrigger('test2','users',r.update,function(old_row,new_row){returnr.and(old_row('age').ne(18),new_row('age').eq(18));},r.js('npm.beep()'))// Stop beeping for twenty year oldsr.dropTrigger('test');
A couple of things:
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.
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.)
I think this functionality would be awesome. Obviously it's a bit away.
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){returnnew_user('age').gt(20);},r.js('npm.beep()'))// Stop beeping for twenty year oldsr.table('users').dropTrigger('test');
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 cursorfornew_userinr.table('users').on_insert(lambdanew_user: new_user['age'] >20).run():
# Now control is returned to the client, and the application can perform the actionstop=go_do_some_action(new_user)
ifstop:
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(
lambdaold_val, new_val: old_val['age'] !=18&new_val['age'] ==18
).map(r.row['new']).run()
fornew_userincursor:
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 closedr.table('user').on_delete(lambdadead_user: dead_user['age'] <5).for_each(lambdadu: r.table('dead_children').insert(du)).run()
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.
Alternatively, we don't need to fold a filter into the on_* functions:
# The filter can simply be chainedr.table('user').on_delete().filter(lambdauser: ...)
# Or omitted# This query always returns the new size of the table when a record is deletedr.table('user').on_delete().map(lambdauser: 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 commentr.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(lambdanew_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);});});
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:
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:
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).
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.
@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.
@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.
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.
@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.
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:
varfeed=r.table('user').changes({since: r.now(),return_vals: true});// Subscribe to all updatesfeed.on('update',function(user){
...
});// Fires on insert of a user with age >20feed.filter(r.row('age').gt(20)).on('insert',function(new_user){
...
});
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.
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?
@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.
@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),
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.
@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.
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.
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?)
varcount=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;})}elseif(count!=null){// <-- Should I increment/decrement even if the count query hasn't returned yet?if(change.old_val==null){count++;}elseif(change.new_val==null){count--;}}})});
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).
Activity
coffeemug commentedon Jun 13, 2013
Actually, instead of passing the table name as a parameter to a trigger, a better way would be as follows:
wmrowan commentedon Jun 13, 2013
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.jsquery 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.jsterm, yuck.Here's an alternative suggestion:
coffeemug commentedon Jun 13, 2013
I disagree. I think embedding node into the server and allowing access to it from
r.jscan 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.
wmrowan commentedon Jun 13, 2013
Alternatively, we don't need to fold a filter into the
on_*functions:Also, I want to point out that this is finally an instance where JS's asynchronous event based nature is more fitting:
wmrowan commentedon Jun 14, 2013
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:
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:
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).
coffeemug commentedon Jun 14, 2013
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.
neumino commentedon Jun 14, 2013
If we have triggers + atomic set/get (#976), it would just awesome to run RethinkDB with meteor.
kofalt commentedon Aug 1, 2013
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.
jdoliner commentedon Aug 1, 2013
@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.
kofalt commentedon Aug 1, 2013
@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.
defunctzombie commentedon Oct 29, 2013
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.
coffeemug commentedon Oct 30, 2013
@defunctzombie -- thanks, we'll consider this approach too!
jdoliner commentedon Oct 30, 2013
@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.
marshall007 commentedon Dec 5, 2013
I agree, CouchDB's concept of change notifications is a really elegant solution that solves most users needs.
In terms of the API. I think conforming to the
EventEmitterpattern would be best (at least for the JS driver). It might be interesting to introduce the concept of afeedto allow arbitrary querying and more focused syntax. Example being:andrewreedy commentedon Feb 4, 2014
+1
125 remaining items
srh commentedon Apr 9, 2014
@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.
coffeemug commentedon Apr 9, 2014
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.
srh commentedon Apr 9, 2014
@coffeemug, it doesn't matter, if a replica is on the master we'd still miss writes.
coffeemug commentedon Apr 9, 2014
@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.
danielmewes commentedon Apr 9, 2014
@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),
coffeemug commentedon Apr 9, 2014
👍
srh commentedon Apr 9, 2014
@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.
mlucy commentedon Apr 9, 2014
I talked about this with @srh in person. Two things that complicate this implementation are:
mailbox_ts don't offer an ordering guarantee).mlucy commentedon Apr 9, 2014
Also, we need to detect when the master goes down and terminate the feeds cleanly rather than leaving them dangling open.
timmaxw commentedon Apr 10, 2014
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
sinceoption 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_tandregistrant_ttypes 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. Theregistrant_twill automatically notify theregistrar_tin its constructor and destructor. They also will detect when the connection is lost. This might save you some boilerplate.neumino commentedon Apr 29, 2014
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?)
coffeemug commentedon Apr 29, 2014
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).
coffeemug commentedon May 22, 2014
@mlucy just merged this into next -- congrats!!
Closing this issue, we'll open specific ones for anything that remains to be done here.