-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
abstract-iterator.js
397 lines (318 loc) · 9.71 KB
/
abstract-iterator.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
'use strict'
const ModuleError = require('module-error')
const combineErrors = require('maybe-combine-errors')
const { getOptions, emptyOptions, noop } = require('./lib/common')
const { AbortError } = require('./lib/errors')
const kWorking = Symbol('working')
const kDecodeOne = Symbol('decodeOne')
const kDecodeMany = Symbol('decodeMany')
const kSignal = Symbol('signal')
const kPendingClose = Symbol('pendingClose')
const kClosingPromise = Symbol('closingPromise')
const kKeyEncoding = Symbol('keyEncoding')
const kValueEncoding = Symbol('valueEncoding')
const kKeys = Symbol('keys')
const kValues = Symbol('values')
const kLimit = Symbol('limit')
const kCount = Symbol('count')
const kEnded = Symbol('ended')
// This class is an internal utility for common functionality between AbstractIterator,
// AbstractKeyIterator and AbstractValueIterator. It's not exported.
class CommonIterator {
constructor (db, options) {
if (typeof db !== 'object' || db === null) {
const hint = db === null ? 'null' : typeof db
throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)
}
if (typeof options !== 'object' || options === null) {
throw new TypeError('The second argument must be an options object')
}
this[kWorking] = false
this[kPendingClose] = null
this[kClosingPromise] = null
this[kKeyEncoding] = options[kKeyEncoding]
this[kValueEncoding] = options[kValueEncoding]
this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity
this[kCount] = 0
this[kSignal] = options.signal != null ? options.signal : null
// Ending means reaching the natural end of the data and (unlike closing) that can
// be reset by seek(), unless the limit was reached.
this[kEnded] = false
this.db = db
this.db.attachResource(this)
}
get count () {
return this[kCount]
}
get limit () {
return this[kLimit]
}
async next () {
startWork(this)
try {
if (this[kEnded] || this[kCount] >= this[kLimit]) {
this[kEnded] = true
return undefined
}
let item = await this._next()
if (item === undefined) {
this[kEnded] = true
return undefined
}
try {
item = this[kDecodeOne](item)
} catch (err) {
throw new IteratorDecodeError(err)
}
this[kCount]++
return item
} finally {
endWork(this)
}
}
async _next () {}
async nextv (size, options) {
if (!Number.isInteger(size)) {
throw new TypeError("The first argument 'size' must be an integer")
}
options = getOptions(options, emptyOptions)
if (size < 1) size = 1
if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])
startWork(this)
try {
if (this[kEnded] || size <= 0) {
this[kEnded] = true
return []
}
const items = await this._nextv(size, options)
if (items.length === 0) {
this[kEnded] = true
return items
}
try {
this[kDecodeMany](items)
} catch (err) {
throw new IteratorDecodeError(err)
}
this[kCount] += items.length
return items
} finally {
endWork(this)
}
}
async _nextv (size, options) {
const acc = []
while (acc.length < size) {
const item = await this._next(options)
if (item !== undefined) {
acc.push(item)
} else {
// Must track this here because we're directly calling _next()
this[kEnded] = true
break
}
}
return acc
}
async all (options) {
options = getOptions(options, emptyOptions)
startWork(this)
try {
if (this[kEnded] || this[kCount] >= this[kLimit]) {
return []
}
const items = await this._all(options)
try {
this[kDecodeMany](items)
} catch (err) {
throw new IteratorDecodeError(err)
}
this[kCount] += items.length
return items
} catch (err) {
endWork(this)
await destroy(this, err)
} finally {
this[kEnded] = true
if (this[kWorking]) {
endWork(this)
await this.close()
}
}
}
async _all (options) {
// Must count here because we're directly calling _nextv()
let count = this[kCount]
const acc = []
while (true) {
// Not configurable, because implementations should optimize _all().
const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3
if (size <= 0) {
return acc
}
const items = await this._nextv(size, options)
if (items.length === 0) {
return acc
}
acc.push.apply(acc, items)
count += items.length
}
}
seek (target, options) {
options = getOptions(options, emptyOptions)
if (this[kClosingPromise] !== null) {
// Don't throw here, to be kind to implementations that wrap
// another db and don't necessarily control when the db is closed
} else if (this[kWorking]) {
throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {
code: 'LEVEL_ITERATOR_BUSY'
})
} else {
const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])
const keyFormat = keyEncoding.format
if (options.keyEncoding !== keyFormat) {
options = { ...options, keyEncoding: keyFormat }
}
const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat, false)
this._seek(mapped, options)
// If _seek() was successfull, more data may be available.
this[kEnded] = false
}
}
_seek (target, options) {
throw new ModuleError('Iterator does not support seek()', {
code: 'LEVEL_NOT_SUPPORTED'
})
}
async close () {
if (this[kClosingPromise] !== null) {
// First caller of close() is responsible for error
return this[kClosingPromise].catch(noop)
}
// Wrap to avoid race issues on recursive calls
this[kClosingPromise] = new Promise((resolve, reject) => {
this[kPendingClose] = () => {
this[kPendingClose] = null
privateClose(this).then(resolve, reject)
}
})
// If working we'll delay closing, but still handle the close error (if any) here
if (!this[kWorking]) {
this[kPendingClose]()
}
return this[kClosingPromise]
}
async _close () {}
async * [Symbol.asyncIterator] () {
try {
let item
while ((item = (await this.next())) !== undefined) {
yield item
}
} catch (err) {
await destroy(this, err)
} finally {
await this.close()
}
}
}
// For backwards compatibility this class is not (yet) called AbstractEntryIterator.
class AbstractIterator extends CommonIterator {
constructor (db, options) {
super(db, options)
this[kKeys] = options.keys !== false
this[kValues] = options.values !== false
}
[kDecodeOne] (entry) {
const key = entry[0]
const value = entry[1]
if (key !== undefined) {
entry[0] = this[kKeys] ? this[kKeyEncoding].decode(key) : undefined
}
if (value !== undefined) {
entry[1] = this[kValues] ? this[kValueEncoding].decode(value) : undefined
}
return entry
}
[kDecodeMany] (entries) {
const keyEncoding = this[kKeyEncoding]
const valueEncoding = this[kValueEncoding]
for (const entry of entries) {
const key = entry[0]
const value = entry[1]
if (key !== undefined) entry[0] = this[kKeys] ? keyEncoding.decode(key) : undefined
if (value !== undefined) entry[1] = this[kValues] ? valueEncoding.decode(value) : undefined
}
}
}
class AbstractKeyIterator extends CommonIterator {
[kDecodeOne] (key) {
return this[kKeyEncoding].decode(key)
}
[kDecodeMany] (keys) {
const keyEncoding = this[kKeyEncoding]
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
if (key !== undefined) keys[i] = keyEncoding.decode(key)
}
}
}
class AbstractValueIterator extends CommonIterator {
[kDecodeOne] (value) {
return this[kValueEncoding].decode(value)
}
[kDecodeMany] (values) {
const valueEncoding = this[kValueEncoding]
for (let i = 0; i < values.length; i++) {
const value = values[i]
if (value !== undefined) values[i] = valueEncoding.decode(value)
}
}
}
// Internal utility, not typed or exported
class IteratorDecodeError extends ModuleError {
constructor (cause) {
super('Iterator could not decode data', {
code: 'LEVEL_DECODE_ERROR',
cause
})
}
}
const startWork = function (iterator) {
if (iterator[kClosingPromise] !== null) {
throw new ModuleError('Iterator is not open: cannot read after close()', {
code: 'LEVEL_ITERATOR_NOT_OPEN'
})
} else if (iterator[kWorking]) {
throw new ModuleError('Iterator is busy: cannot read until previous read has completed', {
code: 'LEVEL_ITERATOR_BUSY'
})
} else if (iterator[kSignal] !== null && iterator[kSignal].aborted) {
throw new AbortError()
}
iterator[kWorking] = true
}
const endWork = function (iterator) {
iterator[kWorking] = false
if (iterator[kPendingClose] !== null) {
iterator[kPendingClose]()
}
}
const privateClose = async function (iterator) {
await iterator._close()
iterator.db.detachResource(iterator)
}
const destroy = async function (iterator, err) {
try {
await iterator.close()
} catch (closeErr) {
throw combineErrors([err, closeErr])
}
throw err
}
// Exposed so that AbstractLevel can set these options
AbstractIterator.keyEncoding = kKeyEncoding
AbstractIterator.valueEncoding = kValueEncoding
exports.AbstractIterator = AbstractIterator
exports.AbstractKeyIterator = AbstractKeyIterator
exports.AbstractValueIterator = AbstractValueIterator