-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
64 lines (51 loc) · 1.42 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
var shasum = require('shasum')
//if a job starts, and another is queued before the current job ends,
//delay it, so that the job is only triggered once.
module.exports = function (input, jobs, map, work) {
if(!work) work = map, map = function (data) { return data.key }
//create a subsection for the jobs,
//if you don't pass in a separate db,
//create a section inside the input
var pending = {}, running = {}
if('string' === typeof jobs)
jobs = input.sublevel(jobs)
var retry = []
function doJob (data) {
//don't process deletes!
if(!data.value) return
var hash = shasum(data.value)
if(!running[hash])
running[hash] = true
else return
var done = false
work(data.value, function (err) {
if(done) return
done = true
if(err) {
running[hash]
return setTimeout(function () {
doJob(data)
}, 500)
}
jobs.del(data.key, function (err) {
if(err) return retry.push(data)
delete running[hash]
if(pending[hash]) {
delete pending[hash]
doJob(data)
}
})
})
}
input.pre(function (ch, add) {
var key = map(ch)
var hash = shasum(key)
if(!pending[hash])
add({key: Date.now(), value: key, type: 'put'}, jobs)
else
pending[hash] = (0 || pending[hash]) + 1
})
jobs.createReadStream().on('data', doJob)
jobs.post(doJob)
return jobs
}