forked from kappa-db/multifeed-index
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
273 lines (235 loc) · 6.95 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter
var State = require('./lib/state')
module.exports = Indexer
var Status = {
Indexing: 1,
Ready: 2,
Paused: 3
}
function Indexer (opts) {
if (!(this instanceof Indexer)) return new Indexer(opts)
if (!opts) throw new Error('missing opts param')
if (!opts.log) throw new Error('missing opts param "log"')
if (!opts.batch) throw new Error('missing opts param "batch"')
if (!allOrNone(!!opts.storeState, !!opts.fetchState)) {
throw new Error('either none or all of (opts.storeState, opts.fetchState) must be provided')
}
if (!unset(opts.version) && typeof opts.version !== 'number') throw new Error('opts.version must be a number')
// TODO: support forward & backward indexing from newest
this._version = unset(opts.version) ? 1 : opts.version
this._log = opts.log
this._batch = opts.batch
this._maxBatch = unset(opts.maxBatch) ? 50 : opts.maxBatch
this._state = Status.Indexing
this._at = null
// bind methods to this so we can pass them directly to event listeners
this._run = this._run.bind(this)
this._onNewFeed = this._onNewFeed.bind(this)
if (!opts.storeState && !opts.fetchState && !opts.clearIndex) {
// In-memory storage implementation
var state
this._storeState = function (buf, cb) {
state = buf
process.nextTick(cb)
}
this._fetchState = function (cb) {
process.nextTick(cb, null, state)
}
this._clearIndex = function (cb) {
state = null
process.nextTick(cb)
}
} else {
this._storeState = opts.storeState
this._fetchState = opts.fetchState
this._clearIndex = opts.clearIndex || null
}
var self = this
this._log.ready(function () {
self._fetchState(function (err, state) {
if (err && !err.notFound) {
self.emit('error', err)
return
}
if (!state) {
start()
return
}
try {
state = State.deserialize(state)
} catch (e) {
self.emit('error', e)
return
}
// Wipe existing index if versions don't match (and there's a 'clearIndex' implementation)
var storedVersion = state.version
if (storedVersion !== self._version && self._clearIndex) {
self._clearIndex(function (err) {
if (err) {
self.emit('error', err)
} else {
start()
}
})
} else {
start()
}
})
})
function start () {
self._state = Status.Ready
self._run()
}
this._log.on('feed', this._onNewFeed)
this.setMaxListeners(1024)
}
inherits(Indexer, EventEmitter)
Indexer.prototype._onNewFeed = function (feed, idx) {
var self = this
feed.setMaxListeners(128)
feed.ready(function () {
// It's possible these listeners are already attached. Ensure they are
// removed before attaching them to avoid attaching them twice
feed.removeListener('append', self._run)
feed.removeListener('download', self._run)
feed.on('append', self._run)
feed.on('download', self._run)
if (self._state === Status.Ready) self._run()
})
}
Indexer.prototype.pause = function (cb) {
cb = cb || function () {}
var self = this
if (this._state === Status.Paused || this._wantPause) {
process.nextTick(cb)
} else if (this._state === Status.Ready) {
this._state = Status.Paused
process.nextTick(cb)
} else {
this._wantPause = true
this.once('pause', function () {
self._wantPause = false
self._state = Status.Paused
cb()
})
}
}
Indexer.prototype.resume = function () {
if (this._state !== Status.Paused) return
this._state = Status.Ready
this._run()
}
Indexer.prototype.ready = function (fn) {
if (this._state === Status.Ready) process.nextTick(fn)
else this.once('ready', fn)
}
Indexer.prototype._run = function () {
if (this._wantPause) {
this._wantPause = false
this._pending = true
this.emit('pause')
return
}
if (this._state !== Status.Ready) {
this._pending = true
return
}
var self = this
this._state = Status.Indexing
var didWork = false
var pending = 1
// load state from storage
if (!this._at) {
this._fetchState(function (err, state) {
if (err && !err.notFound) throw err // TODO: how to bubble up errors? eventemitter?
if (!state) {
self._at = {}
self._log.feeds().forEach(function (feed) {
self._at[feed.key.toString('hex')] = {
key: feed.key,
min: 0,
max: 0
}
})
} else {
self._at = State.deserialize(state).keys
}
self._log.feeds().forEach(function (feed) {
feed.setMaxListeners(128)
// The ready() method also adds these events listeners. Try to remove
// them first so that they aren't added twice.
feed.removeListener('append', self._run)
feed.removeListener('download', self._run)
feed.on('append', self._run)
feed.on('download', self._run)
})
work()
})
} else {
work()
}
function work () {
var feeds = self._log.feeds()
var nodes = []
;(function collect (i) {
if (i >= feeds.length) return done()
feeds[i].ready(function () {
var key = feeds[i].key.toString('hex')
if (self._at[key] === undefined) {
self._at[key] = { key: feeds[i].key, min: 0, max: 0 }
}
// prefer to process forward
var at = self._at[key].max
var to = Math.min(feeds[i].length, at + self._maxBatch)
if (!feeds[i].has(at, to)) {
return collect(i + 1)
} else if (at < to) {
// TODO: This waits for all of the blocks to be available, and
// actually blocks ALL indexing until it's ready. The intention is to
// get min(maxBatch, feed.length-at) CONTIGUOUS entries
feeds[i].getBatch(at, to, {wait: false}, function (err, res) {
if (err || !res.length) {
return collect(i + 1)
}
for (var j = 0; j < res.length; j++) {
var node = res[j]
nodes.push({
key: feeds[i].key.toString('hex'),
seq: j + at,
value: node
})
}
didWork = true
self._batch(nodes, function () {
self._at[key].max += nodes.length
self._storeState(State.serialize(self._at, self._version), function () {
self.emit('indexed', nodes)
done()
})
})
})
} else {
collect(i + 1)
}
})
})(0)
function done () {
if (!--pending) {
self._state = Status.Ready
if (didWork || self._pending) {
self._pending = false
self._run()
} else {
self.emit('ready')
}
}
}
}
}
function allOrNone (a, b) {
return (!!a && !!b) || (!a && !b)
}
function unset (x) {
return x === null || x === undefined
}