• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

albe / node-event-storage / 23400890631

22 Mar 2026 10:14AM UTC coverage: 97.856% (+0.03%) from 97.826%
23400890631

Pull #254

github

web-flow
Merge fcd5390fb into ea855be31
Pull Request #254: iterateRange: use k-way partition merge by sequenceNumber when index=false

649 of 685 branches covered (94.74%)

Branch coverage included in aggregate %.

39 of 39 new or added lines in 2 files covered. (100.0%)

1 existing line in 1 file now uncovered.

1496 of 1507 relevant lines covered (99.27%)

1200.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.28
/src/Storage/ReadableStorage.js
1
const fs = require('fs');
4✔
2
const path = require('path');
4✔
3
const events = require('events');
4✔
4
const Partition = require('../Partition');
4✔
5
const Index = require('../Index');
4✔
6
const { assert, createHmac, matches, wrapAndCheck, buildMetadataForMatcher } = require('../util');
4✔
7

8
const DEFAULT_READ_BUFFER_SIZE = 4 * 1024;
4✔
9

10
/**
11
 * Reverses the items of an iterable
12
 * @param {Generator|Iterable} iterator
13
 * @returns {Generator<*>}
14
 */
15
function *reverse(iterator) {
16
    const items = Array.from(iterator);
68✔
17
    for (let i = items.length - 1; i >= 0; i--) {
68✔
18
        yield items[i];
580✔
19
    }
20
}
21

22
/**
23
 * @typedef {object|function(object):boolean} Matcher
24
 */
25

26
/**
27
 * An append-only storage with highly performant positional range scans.
28
 * It's highly optimized for an event-store and hence does not support compaction or data-rewrite, nor any querying
29
 */
30
class ReadableStorage extends events.EventEmitter {
31

32
    /**
33
     * @param {string} [storageName] The name of the storage.
34
     * @param {object} [config] An object with storage parameters.
35
     * @param {object} [config.serializer] A serializer object with methods serialize(document) and deserialize(data).
36
     * @param {function(object): string} config.serializer.serialize Default is JSON.stringify.
37
     * @param {function(string): object} config.serializer.deserialize Default is JSON.parse.
38
     * @param {string} [config.dataDirectory] The path where the storage data should reside. Default '.'.
39
     * @param {string} [config.indexDirectory] The path where the indexes should be stored. Defaults to dataDirectory.
40
     * @param {string} [config.indexFile] The name of the primary index. Default '{storageName}.index'.
41
     * @param {number} [config.readBufferSize] Size of the read buffer in bytes. Default 4096.
42
     * @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
43
     * @param {string} [config.hmacSecret] A private key that is used to verify matchers retrieved from indexes.
44
     * @param {object} [config.metadata] A metadata object to be stored in all partitions belonging to this storage.
45
     */
46
    constructor(storageName = 'storage', config = {}) {
448!
47
        super();
884✔
48
        if (typeof storageName !== 'string') {
884✔
49
            config = storageName;
52✔
50
            storageName = undefined;
52✔
51
        }
52

53
        this.storageFile = storageName || 'storage';
884✔
54
        const defaults = {
884✔
55
            serializer: { serialize: JSON.stringify, deserialize: JSON.parse },
56
            dataDirectory: '.',
57
            indexFile: this.storageFile + '.index',
58
            indexOptions: {},
59
            hmacSecret: '',
60
            metadata: {}
61
        };
62
        config = Object.assign(defaults, config);
884✔
63
        this.serializer = config.serializer;
884✔
64

65
        this.hmac = createHmac(config.hmacSecret);
884✔
66

67
        this.dataDirectory = path.resolve(config.dataDirectory);
884✔
68

69
        this.initializeIndexes(config);
884✔
70
        this.scanPartitions(config);
880✔
71
    }
72

73
    /**
74
     * @protected
75
     * @param {string} name
76
     * @param {object} [options]
77
     * @returns {{ index: ReadableIndex, matcher?: Matcher }}
78
     */
79
    createIndex(name, options = {}) {
×
80
        /** @type ReadableIndex */
81
        const index = new Index.ReadOnly(name, options);
136✔
82
        return { index };
132✔
83
    }
84

85
    /**
86
     * @protected
87
     * @param {string} name
88
     * @param {object} [options]
89
     * @returns {ReadablePartition}
90
     */
91
    createPartition(name, options = {}) {
×
92
        return new Partition.ReadOnly(name, options);
52✔
93
    }
94

95
    /**
96
     * Create/open the primary index and build the base configuration for all secondary indexes.
97
     *
98
     * @private
99
     * @param {object} config The configuration object
100
     * @returns void
101
     */
102
    initializeIndexes(config) {
103
        this.indexDirectory = path.resolve(config.indexDirectory || this.dataDirectory);
884✔
104

105
        this.indexOptions = config.indexOptions;
884✔
106
        this.indexOptions.dataDirectory = this.indexDirectory;
884✔
107
        // Safety precaution to prevent accidentally restricting main index
108
        delete this.indexOptions.matcher;
884✔
109
        const { index } = this.createIndex(config.indexFile, this.indexOptions);
884✔
110
        this.index = index;
880✔
111
        this.secondaryIndexes = {};
880✔
112
        this.readonlyIndexes = {};
880✔
113
    }
114

115
    /**
116
     * The amount of documents in the storage.
117
     * @returns {number}
118
     */
119
    get length() {
120
        return this.index.length;
3,624✔
121
    }
122

123
    /**
124
     * Scan the data directory for all existing partitions.
125
     * Every file beginning with the storageFile name is considered a partition.
126
     *
127
     * @private
128
     * @param {object} config The configuration object containing options for the partitions.
129
     * @returns void
130
     */
131
    scanPartitions(config) {
132
        const defaults = {
880✔
133
            readBufferSize: DEFAULT_READ_BUFFER_SIZE
134
        };
135
        this.partitionConfig = Object.assign(defaults, config);
880✔
136
        this.partitions = Object.create(null);
880✔
137

138
        const files = fs.readdirSync(this.dataDirectory);
880✔
139
        for (let file of files) {
880✔
140
            if (file.substr(-6) === '.index') continue;
1,100✔
141
            if (file.substr(-7) === '.branch') continue;
552!
142
            if (file.substr(-5) === '.lock') continue;
552✔
143
            if (file.substr(0, this.storageFile.length) !== this.storageFile) continue;
468✔
144

145
            const partition = this.createPartition(file, this.partitionConfig);
88✔
146
            this.partitions[partition.id] = partition;
88✔
147
        }
148
    }
149

150
    /**
151
     * Open the storage and indexes and create read and write buffers eagerly.
152
     * Will emit an 'opened' event if finished.
153
     *
154
     * @api
155
     * @returns {boolean}
156
     */
157
    open() {
158
        this.index.open();
824✔
159

160
        this.forEachSecondaryIndex(index => index.open());
824✔
161

162
        this.emit('opened');
824✔
163
        return true;
824✔
164
    }
165

166
    /**
167
     * Close the storage and frees up all resources.
168
     * Will emit a 'closed' event when finished.
169
     *
170
     * @api
171
     * @returns void
172
     */
173
    close() {
174
        this.index.close();
1,364✔
175
        this.forEachSecondaryIndex(index => index.close());
1,364✔
176
        for (let index of Object.values(this.readonlyIndexes)) {
1,364✔
177
            index.close();
44✔
178
        }
179
        this.forEachPartition(partition => partition.close());
1,376✔
180
        this.emit('closed');
1,364✔
181
    }
182

183
    /**
184
     * Get a partition either by name or by id.
185
     * If a partition with the given name does not exist, a new one will be created.
186
     * If a partition with the given id does not exist, an error is thrown.
187
     *
188
     * @protected
189
     * @param {string|number} partitionIdentifier The partition name or the partition Id
190
     * @returns {ReadablePartition}
191
     * @throws {Error} If an id is given and no such partition exists.
192
     */
193
    getPartition(partitionIdentifier) {
194
        assert(partitionIdentifier in this.partitions, `Partition #${partitionIdentifier} does not exist.`);
3,716✔
195

196
        this.partitions[partitionIdentifier].open();
3,716✔
197
        return this.partitions[partitionIdentifier];
3,716✔
198
    }
199

200
    /**
201
     * Register a handler that is called before a document is read from a partition.
202
     * The handler receives the position and the partition metadata and may throw to abort the read.
203
     * Multiple handlers can be registered; all run on every read in registration order.
204
     * Equivalent to `storage.on('preRead', hook)`.
205
     *
206
     * @api
207
     * @param {function(number, object): void} hook A function receiving (position, partitionMetadata).
208
     */
209
    preRead(hook) {
210
        this.on('preRead', hook);
12✔
211
    }
212

213
    /**
214
     * @protected
215
     * @param {number} partitionId The partition to read from.
216
     * @param {number} position The file position to read from.
217
     * @param {number} [size] The expected byte size of the document at the given position.
218
     * @returns {object} The document stored at the given position.
219
     * @throws {Error} if the document at the given position can not be deserialized.
220
     */
221
    readFrom(partitionId, position, size) {
222
        const partition = this.getPartition(partitionId);
3,676✔
223
        if (this.listenerCount('preRead') > 0) {
3,676✔
224
            this.emit('preRead', position, partition.metadata);
64✔
225
        }
226
        const data = partition.readFrom(position, size);
3,668✔
227
        return this.serializer.deserialize(data);
3,668✔
228
    }
229

230
    /**
231
     * Read a single document from the given position, in the full index or in the provided index.
232
     *
233
     * @api
234
     * @param {number} number The 1-based document number (inside the given index) to read.
235
     * @param {ReadableIndex} [index] The index to use for finding the document position.
236
     * @returns {object} The document at the given position inside the index.
237
     */
238
    read(number, index) {
239
        index = index || this.index;
176✔
240

241
        if (!index.isOpen()) {
176✔
242
            index.open();
4✔
243
        }
244

245
        const entry = index.get(number);
176✔
246
        if (entry === false) {
176✔
247
            return false;
4✔
248
        }
249

250
        return this.readFrom(entry.partition, entry.position, entry.size);
172✔
251
    }
252

253
    /**
254
     * Read a range of documents from the given position range, in the full index or in the provided index.
255
     * Returns a generator in order to reduce memory usage and be able to read lots of documents with little latency.
256
     *
257
     * @api
258
     * @param {number} from The 1-based document number (inclusive) to start reading from.
259
     * @param {number} [until] The 1-based document number (inclusive) to read until. Defaults to index.length.
260
     * @param {ReadableIndex|false} [index] The index to use for finding the documents in the range.
261
     *   Pass `false` to skip the global index and iterate all partitions directly in sequenceNumber order
262
     *   (useful when the global index is unavailable or corrupted).
263
     * @returns {Generator<object>} A generator that will read each document in the range one by one.
264
     */
265
    *readRange(from, until = -1, index = null) {
72✔
266
        const lengthSource = index || this.index;
524✔
267
        if (!lengthSource.isOpen()) {
524✔
268
            lengthSource.open();
4✔
269
        }
270

271
        const readFrom = wrapAndCheck(from, lengthSource.length);
524✔
272
        const readUntil = wrapAndCheck(until, lengthSource.length);
524✔
273
        assert(readFrom > 0 && readUntil > 0, `Range scan error for range ${from} - ${until}.`);
524✔
274

275
        if (readFrom > readUntil) {
508✔
276
            const batchSize = 10;
48✔
277
            let batchUntil = readFrom;
48✔
278
            while (batchUntil >= readUntil) {
48✔
279
                const batchFrom = Math.max(readUntil, batchUntil - batchSize);
68✔
280
                yield* reverse(this.iterateRange(batchFrom, batchUntil, index));
68✔
281
                batchUntil = batchFrom - 1;
68✔
282
            }
283
            return undefined;
48✔
284
        }
285

286
        yield* this.iterateRange(readFrom, readUntil, index);
460✔
287
    }
288

289
    /**
290
     * Iterate all documents in this storage in range from to until inside the index.
291
     * If index is false, iterates all partitions directly in sequenceNumber order.
292
     * @private
293
     * @param {number} from
294
     * @param {number} until
295
     * @param {ReadableIndex|false|null} index
296
     * @returns {Generator<object>}
297
     */
298
    *iterateRange(from, until, index) {
299
        if (index === false) {
528✔
300
            // Explicitly disabled index: iterate all partitions and merge by sequenceNumber.
301
            // Document header sequenceNumber is 0-based; from/until are 1-based index positions.
302
            yield* this.iteratePartitionsBySequenceNumber(from - 1, until - 1);
12✔
303
            return;
12✔
304
        }
305

306
        const idx = index || this.index;
516✔
307
        const entries = idx.range(from, until);
516✔
308
        for (let entry of entries) {
516✔
309
            const document = this.readFrom(entry.partition, entry.position, entry.size);
1,760✔
310
            yield document;
1,756✔
311
        }
312
    }
313

314
    /**
315
     * Iterate documents across all partitions in sequenceNumber order using a k-way merge.
316
     * SequenceNumbers stored in document headers are 0-based.
317
     * @private
318
     * @param {number} fromSeq The 0-based sequenceNumber to start from (inclusive).
319
     * @param {number} untilSeq The 0-based sequenceNumber to read until (inclusive).
320
     * @returns {Generator<object>}
321
     */
322
    *iteratePartitionsBySequenceNumber(fromSeq, untilSeq) {
323
        const iterators = [];
12✔
324

325
        for (const partition of Object.values(this.partitions)) {
12✔
326
            if (!partition.isOpen()) {
36!
327
                partition.open();
36✔
328
            }
329
            const headerOut = {};
36✔
330
            const gen = partition.readAll(0, headerOut);
36✔
331

332
            // Advance to the first document with sequenceNumber >= fromSeq
333
            let result = gen.next();
36✔
334
            while (!result.done && headerOut.sequenceNumber < fromSeq) {
36✔
335
                result = gen.next();
8✔
336
            }
337

338
            if (!result.done && headerOut.sequenceNumber <= untilSeq) {
36!
339
                iterators.push({ gen, headerOut, data: result.value, sequenceNumber: headerOut.sequenceNumber });
36✔
340
            }
341
        }
342

343
        // K-way merge: at each step, yield the document with the smallest sequenceNumber
344
        while (iterators.length > 0) {
12✔
345
            let minIdx = 0;
92✔
346
            for (let i = 1; i < iterators.length; i++) {
92✔
347
                if (iterators[i].sequenceNumber < iterators[minIdx].sequenceNumber) {
148✔
348
                    minIdx = i;
72✔
349
                }
350
            }
351

352
            yield this.serializer.deserialize(iterators[minIdx].data);
92✔
353

354
            const next = iterators[minIdx].gen.next();
92✔
355
            if (!next.done && iterators[minIdx].headerOut.sequenceNumber <= untilSeq) {
92✔
356
                iterators[minIdx].data = next.value;
56✔
357
                iterators[minIdx].sequenceNumber = iterators[minIdx].headerOut.sequenceNumber;
56✔
358
            } else {
359
                iterators.splice(minIdx, 1);
36✔
360
            }
361
        }
362
    }
363

364
    /**
365
     * Open an existing readonly index for reading, without registering it in the secondary indexes write path.
366
     * Use this for indexes whose files carry a status marker (e.g. `stream-foo.closed.index`).
367
     *
368
     * @api
369
     * @param {string} name The readonly index name (e.g. 'stream-foo.closed').
370
     * @returns {ReadableIndex}
371
     * @throws {Error} if the readonly index does not exist.
372
     */
373
    openReadonlyIndex(name) {
374
        if (name in this.readonlyIndexes) {
44!
UNCOV
375
            return this.readonlyIndexes[name];
×
376
        }
377
        const indexName = this.storageFile + '.' + name + '.index';
44✔
378
        assert(fs.existsSync(path.join(this.indexDirectory, indexName)), `Index "${name}" does not exist.`);
44✔
379
        const { index } = this.createIndex(indexName, Object.assign({}, this.indexOptions));
44✔
380
        index.open();
44✔
381
        this.readonlyIndexes[name] = index;
44✔
382
        return index;
44✔
383
    }
384

385
    /**
386
     * Open an existing index.
387
     *
388
     * @api
389
     * @param {string} name The index name.
390
     * @param {Matcher} [matcher] The matcher object or function that the index needs to have been defined with. If not given it will not be validated.
391
     * @returns {ReadableIndex}
392
     * @throws {Error} if the index with that name does not exist.
393
     * @throws {Error} if the HMAC for the matcher does not match.
394
     */
395
    openIndex(name, matcher) {
396
        if (name === '_all') {
680✔
397
            return this.index;
8✔
398
        }
399
        if (name in this.secondaryIndexes) {
672✔
400
            return this.secondaryIndexes[name].index;
600✔
401
        }
402

403
        const indexName = this.storageFile + '.' + name + '.index';
72✔
404
        assert(fs.existsSync(path.join(this.indexDirectory, indexName)), `Index "${name}" does not exist.`);
72✔
405

406
        const metadata = buildMetadataForMatcher(matcher, this.hmac);
68✔
407
        let { index } = this.secondaryIndexes[name] = this.createIndex(indexName, Object.assign({}, this.indexOptions, { metadata }));
68✔
408

409
        index.open();
56✔
410
        return index;
56✔
411
    }
412

413
    /**
414
     * Helper method to iterate over all documents.
415
     *
416
     * @protected
417
     * @param {function(object, EntryInterface)} iterationHandler
418
     */
419
    forEachDocument(iterationHandler) {
420
        /* istanbul ignore if  */
421
        if (typeof iterationHandler !== 'function') {
804✔
422
            return;
423
        }
424

425
        const entries = this.index.all();
804✔
426

427
        for (let entry of entries) {
804✔
428
            const document = this.readFrom(entry.partition, entry.position, entry.size);
1,732✔
429
            iterationHandler(document, entry);
1,732✔
430
        }
431
    }
432

433
    /**
434
     * Helper method to iterate over all secondary indexes.
435
     *
436
     * @protected
437
     * @param {function(ReadableIndex, string)} iterationHandler
438
     * @param {object} [matchDocument] If supplied, only indexes the document matches on will be iterated.
439
     */
440
    forEachSecondaryIndex(iterationHandler, matchDocument) {
441
        /* istanbul ignore if  */
442
        if (typeof iterationHandler !== 'function') {
4,816✔
443
            return;
444
        }
445

446
        for (let indexName of Object.keys(this.secondaryIndexes)) {
4,816✔
447
            if (!matchDocument || matches(matchDocument, this.secondaryIndexes[indexName].matcher)) {
4,648✔
448
                iterationHandler(this.secondaryIndexes[indexName].index, indexName);
2,408✔
449
            }
450
        }
451
    }
452

453
    /**
454
     * Helper method to iterate over all partitions.
455
     *
456
     * @protected
457
     * @param {function(ReadablePartition)} iterationHandler
458
     */
459
    forEachPartition(iterationHandler) {
460
        /* istanbul ignore if  */
461
        if (typeof iterationHandler !== 'function') {
1,432✔
462
            return;
463
        }
464

465
        for (let partition of Object.keys(this.partitions)) {
1,432✔
466
            iterationHandler(this.partitions[partition]);
1,436✔
467
        }
468
    }
469

470
}
471

472
module.exports = ReadableStorage;
4✔
473
module.exports.matches = matches;
4✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc