pfraze/scuttlebot — pull request #16 by pfraze (2014-11-23 19:14:43+00:00)
Title: Organizing plugins: scheduling and events

Plugins which close the RPC channel may conflict with other plugins.

```js
module.exports = function (server) {
server.on('authorized', function (rpc) {
replicate(server, rpc, function (err, progress) {
if(err) return console.error(err)
server.emit('replicated', progress)
rpc.close(function () {}) // <-- this is an issue
})
})
}
```

Plugins should not directly control the lifecycle of a connection. This patch adds the scheduling API which allows plugins to register a job and specify a time limit. When all jobs are finished or timed-out, the server closes the channel.

```js
module.exports = function (server) {
server.on('rpc:authorized', function(rpc) {
// schedule 30 seconds to do replication
server.schedule(rpc, 'replicate', 30, function(err, done) {
if (err) return console.log('REPLICATE Failed to schedule session time', err)
server.emit('replicate:start', rpc)
replicate(server, rpc, function (err, progress) {
if(err) {
server.emit('replicate:fail', rpc, err)
console.error(err)
} else
server.emit('replicate:finish', rpc, progress)
done()
})
})
})
}
```

This patch additionally structures the events using a namespace scheme of `'plugin:event'`. These are the current events:

- `rpc:connect` - a new rpc session has been created
- `rpc:peer` - an incoming rpc session has been created
- `rpc:client` - an outgoing rpc session has been created
- `rpc:close` - an rpc session has been closed
- `rpc:authorized` - the rpc session has successfully authorized with the remote peer
- `rpc:unauthorized` - the rpc session has failed to authorize with the remote peer
- `replicate:start` - replicate plugin has started its job
- `replicate:finish` - replicate plugin successfully finished its job
- `replicate:fail` - replicate plugin failed its job
- `gossip:connect` - gossip plugin created a new rpc session