Permalink
Browse files

handle error paths

  • Loading branch information...
1 parent bea529e commit f491ff5eba72a28ea811647972b273af35a84a44 @dominictarr committed Jan 7, 2013
Showing with 42 additions and 6 deletions.
  1. +42 −6 index.js
View
@@ -1,5 +1,8 @@
var parserx = require('parse-regexp')
+//don't make the timeout too large, because it will prevent the process from exiting...
+var TIMEOUT = 100
+
var exports = module.exports = function (schema) {
if('function' == typeof schema)
return schema
@@ -13,8 +16,11 @@ var exports = module.exports = function (schema) {
for (var i in rules) {
var r = rules[i]
var m = key.match(r.rx)
- if(m && m.index === 0)
- return r.fn(key)
+ if(m && m.index === 0) {
+ var scuttlebutt = r.fn(key)
+ scuttlebutt.name = key
+ return scuttlebutt
+ }
}
}
@@ -27,7 +33,7 @@ var exports = module.exports = function (schema) {
exports.schema = exports
exports.cache =
-function cached (open) {
+function cached (open, onCache) {
var local = {}
return function (name, tail, cb) {
if('function' == typeof tail)
@@ -36,25 +42,47 @@ function cached (open) {
var cached = local[name]
if(cached && 'function' === typeof cached.clone) {
var n = cached.clone()
+ n.name = name
cb(null, n)
return n
}
var clone
- var scuttlebutt = open(name, tail, function (err) {
+ var scuttlebutt = open(name, tail, function (err, scuttlebutt) {
+ scuttlebutt.name = name
cb(err, clone || scuttlebutt)
})
+
+ //will callback an error
+ if(!scuttlebutt) return
+
+ scuttlebutt.name = name
//only scuttlebutts with clone can be cleanly cached.
if('function' === typeof scuttlebutt.clone) {
local[name] = scuttlebutt
clone = scuttlebutt.clone()
+ clone.name = name
+ if(onCache) onCache('cache', scuttlebutt.name)
//okay... have something to dispose the scuttlebutt when there are 0 streams.
//hmm, count streams... and emit an event 'unstream' or something?
//okay, if all the steams have closed but this one, then it means no one is using this,
//so close...
//TODO add this to level-scuttlebutt.
+
+ var timer = null
scuttlebutt.on('unstream', function (n) {
- if(n === 1) scuttlebutt.dispose()
+ if(n === 1) {
+ clearTimeout(timer)
+ timer = setTimeout(function () {
+ scuttlebutt.dispose()
+ if(onCache) onCache('uncache', scuttlebutt.name)
+ }, TIMEOUT)
+ //if an emitter was passed, imet
+ } else if(n > 1)
+ clearTimeout(timer)
+ })
+ scuttlebutt.on('dispose', function () {
+ delete local[name]
})
}
@@ -64,11 +92,19 @@ function cached (open) {
exports.sync =
exports.open = function (schema, connect) {
+ //pass in a string name, or a scuttlebutt instance
+ //you want to reconnect to the server.
return function (name, tail, cb) {
if('function' == typeof tail)
cb = tail, tail = true
- var scuttlebutt = schema(name)
+ var scuttlebutt
+ if('string' === typeof name)
+ scuttlebutt = schema(name)
+ else {
+ scuttlebutt = name
+ name = scuttlebutt.name
+ }
var es = scuttlebutt.createStream()
var stream = connect(name)

0 comments on commit f491ff5

Please sign in to comment.