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

albe / node-event-storage / 23361017298

20 Mar 2026 08:19PM UTC coverage: 97.391% (-0.4%) from 97.826%
23361017298

Pull #107

github

web-flow
Merge b56a2679a into 28d4e34f0
Pull Request #107: Start implementing auto-repair

606 of 644 branches covered (94.1%)

Branch coverage included in aggregate %.

18 of 24 new or added lines in 5 files covered. (75.0%)

2 existing lines in 1 file now uncovered.

1447 of 1464 relevant lines covered (98.84%)

1200.29 hits per line

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

96.7
/src/Storage/WritableStorage.js
1
const fs = require('fs');
4✔
2
const path = require('path');
4✔
3
const WritablePartition = require('../Partition/WritablePartition');
4✔
4
const WritableIndex = require('../Index/WritableIndex');
4✔
5
const ReadableStorage = require('./ReadableStorage');
4✔
6
const { assert, matches, buildMetadataForMatcher, buildMatcherFromMetadata, ensureDirectory } = require('../util');
4✔
7

8
const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
4✔
9

10
const LOCK_RECLAIM = 0x1;
4✔
11
const LOCK_THROW = 0x2;
4✔
12

13
class StorageLockedError extends Error {}
14

15
/**
16
 * @typedef {object|function(object):boolean} Matcher
17
 */
18

19
/**
20
 * An append-only storage with highly performant positional range scans.
21
 * It's highly optimized for an event-store and hence does not support compaction or data-rewrite, nor any querying
22
 */
23
class WritableStorage extends ReadableStorage {
24

25
    /**
26
     * @param {string} [storageName] The name of the storage.
27
     * @param {object} [config] An object with storage parameters.
28
     * @param {object} [config.serializer] A serializer object with methods serialize(document) and deserialize(data).
29
     * @param {function(object): string} config.serializer.serialize Default is JSON.stringify.
30
     * @param {function(string): object} config.serializer.deserialize Default is JSON.parse.
31
     * @param {string} [config.dataDirectory] The path where the storage data should reside. Default '.'.
32
     * @param {string} [config.indexDirectory] The path where the indexes should be stored. Defaults to dataDirectory.
33
     * @param {string} [config.indexFile] The name of the primary index. Default '{storageName}.index'.
34
     * @param {number} [config.readBufferSize] Size of the read buffer in bytes. Default 4096.
35
     * @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
36
     * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
37
     * @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
38
     * @param {boolean} [config.dirtyReads] If dirty reads should be allowed. This means that writes that are in write buffer but not yet flushed can be read. Defaults to true.
39
     * @param {function(object, number): string} [config.partitioner] A function that takes a document and sequence number and returns a partition name that the document should be stored in. Defaults to write all documents to the primary partition.
40
     * @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
41
     * @param {string} [config.hmacSecret] A private key that is used to verify matchers retrieved from indexes.
42
     * @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled.
43
     */
44
    constructor(storageName = 'storage', config = {}) {
404!
45
        if (typeof storageName !== 'string') {
664✔
46
            config = storageName;
404✔
47
            storageName = undefined;
404✔
48
        }
49
        const defaults = {
664✔
50
            partitioner: (document, number) => '',
1,380✔
51
            writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
52
            maxWriteBufferDocuments: 0,
53
            syncOnFlush: false,
54
            dirtyReads: true,
55
            dataDirectory: '.'
56
        };
57
        config = Object.assign(defaults, config);
664✔
58
        config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush }, config.indexOptions);
664✔
59
        ensureDirectory(config.dataDirectory);
664✔
60
        super(storageName, config);
664✔
61

62
        this.lockFile = path.resolve(this.dataDirectory, this.storageFile + '.lock');
664✔
63
        if (config.lock === LOCK_RECLAIM) {
664✔
64
            this.unlock();
4✔
65
        }
66
        this.partitioner = config.partitioner;
664✔
67
    }
68

69
    /**
70
     * @inheritDoc
71
     * @returns {boolean}
72
     * @throws {StorageLockedError} If this storage is locked by another process.
73
     */
74
    open() {
75
        if (!this.lock()) {
596✔
76
            return true;
4✔
77
        }
78
        return super.open();
588✔
79
    }
80

81
    /**
82
     * Check all partitions torn writes and truncate the storage to the position before the first torn write.
83
     * This might delete correctly written events in partitions, if their sequence number is higher than the
84
     * torn write in another partition.
85
     */
86
    checkTornWrites() {
87
        let lastValidSequenceNumber = Number.MAX_SAFE_INTEGER;
4✔
88
        this.forEachPartition(partition => {
4✔
89
            partition.open();
4✔
90
            const tornSequenceNumber = partition.checkTornWrite();
4✔
91
            if (tornSequenceNumber >= 0) {
4!
92
                lastValidSequenceNumber = Math.min(lastValidSequenceNumber, tornSequenceNumber);
4✔
93
            }
94
        });
95
        if (lastValidSequenceNumber < Number.MAX_SAFE_INTEGER) {
4!
96
            this.truncate(lastValidSequenceNumber);
4✔
97
        }
98
        this.forEachPartition(partition => partition.close());
4✔
99
    }
100

101
    /**
102
     * Attempt to lock this storage by means of a lock directory.
103
     * @returns {boolean} True if the lock was created or false if the lock is already in place.
104
     * @throws {StorageLockedError} If this storage is already locked by another process.
105
     * @throws {Error} If the lock could not be created.
106
     */
107
    lock() {
108
        if (this.locked) {
596✔
109
            return false;
4✔
110
        }
111
        try {
592✔
112
            fs.mkdirSync(this.lockFile);
592✔
113
            this.locked = true;
588✔
114
        } catch (e) {
115
            /* istanbul ignore if */
116
            if (e.code !== 'EEXIST') {
4✔
117
                throw new Error(`Error creating lock for storage ${this.storageFile}: ` + e.message);
118
            }
119
            throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
4✔
120
        }
121
        return true;
588✔
122
    }
123

124
    /**
125
     * Unlock this storage, no matter if it was previously locked by this writer.
126
     * Only use this if you are sure there is no other process still having a writer open.
127
     * Current implementation just deletes a lock file that is named like the storage.
128
     */
129
    unlock() {
130
        if (fs.existsSync(this.lockFile)) {
592✔
131
            if (!this.locked) {
588✔
132
                this.checkTornWrites();
4✔
133
            }
134
            fs.rmdirSync(this.lockFile);
588✔
135
        }
136
        this.locked = false;
592✔
137
    }
138

139
    /**
140
     * @inheritDoc
141
     */
142
    close() {
143
        if (this.locked) {
1,032✔
144
            this.unlock();
588✔
145
        }
146
        super.close();
1,032✔
147
    }
148

149
    /**
150
     * Add an index entry for the given document at the position and size.
151
     *
152
     * @private
153
     * @param {number} partitionId The partition where the document is stored.
154
     * @param {number} position The file offset where the document is stored.
155
     * @param {number} size The size of the stored document.
156
     * @param {object} document The document to add to the index.
157
     * @param {function} [callback] The callback to call when the index is written to disk.
158
     * @returns {EntryInterface} The index entry item.
159
     */
160
    addIndex(partitionId, position, size, document, callback) {
161
        if (!this.index.isOpen()) {
2,264✔
162
            this.index.open();
4✔
163
        }
164

165
        /*if (this.index.lastEntry.position + this.index.lastEntry.size !== position) {
166
         this.emit('index-corrupted');
167
         throw new Error('Corrupted index, needs to be rebuilt!');
168
         }*/
169

170
        const entry = new WritableIndex.Entry(this.index.length + 1, position, size, partitionId);
2,264✔
171
        this.index.add(entry, (indexPosition) => {
2,264✔
172
            this.emit('wrote', document, entry, indexPosition);
2,264✔
173
            /* istanbul ignore if  */
174
            if (typeof callback === 'function') {
2,264✔
175
                return callback(indexPosition);
176
            }
177
        });
178
        return entry;
2,264✔
179
    }
180

181
    /**
182
     * Get a partition either by name or by id.
183
     * If a partition with the given name does not exist, a new one will be created.
184
     * If a partition with the given id does not exist, an error is thrown.
185
     *
186
     * @protected
187
     * @param {string|number} partitionIdentifier The partition name or the partition Id
188
     * @returns {ReadablePartition}
189
     * @throws {Error} If an id is given and no such partition exists.
190
     */
191
    getPartition(partitionIdentifier) {
192
        if (typeof partitionIdentifier === 'string') {
5,988✔
193
            const partitionName = this.storageFile + (partitionIdentifier.length ? '.' + partitionIdentifier : '');
2,276✔
194
            partitionIdentifier = WritablePartition.idFor(partitionName);
2,276✔
195
            if (!this.partitions[partitionIdentifier]) {
2,276✔
196
                this.partitions[partitionIdentifier] = this.createPartition(partitionName, this.partitionConfig);
652✔
197
                this.emit('partition-created', partitionIdentifier);
652✔
198
            }
199
            this.partitions[partitionIdentifier].open();
2,276✔
200
            return this.partitions[partitionIdentifier];
2,276✔
201
        }
202
        return super.getPartition(partitionIdentifier);
3,712✔
203
    }
204

205
    /**
206
     * @api
207
     * @param {object} document The document to write to storage.
208
     * @param {function} [callback] A function that will be called when the document is written to disk.
209
     * @returns {number} The 1-based document sequence number in the storage.
210
     */
211
    write(document, callback) {
212
        const data = this.serializer.serialize(document).toString();
2,264✔
213
        const dataSize = Buffer.byteLength(data, 'utf8');
2,264✔
214

215
        const partitionName = this.partitioner(document, this.index.length + 1);
2,264✔
216
        const partition = this.getPartition(partitionName);
2,264✔
217
        const position = partition.write(data, this.length, callback);
2,264✔
218

219
        assert(position !== false, 'Error writing document.');
2,264✔
220

221
        const indexEntry = this.addIndex(partition.id, position, dataSize, document);
2,264✔
222
        this.forEachSecondaryIndex((index, name) => {
2,264✔
223
            if (!index.isOpen()) {
1,324✔
224
                index.open();
4✔
225
            }
226
            index.add(indexEntry);
1,324✔
227
            this.emit('index-add', name, index.length, document);
1,324✔
228
        }, document);
229

230
        return this.index.length;
2,264✔
231
    }
232

233
    /**
234
     * Ensure that an index with the given name and document matcher exists.
235
     * Will create the index if it doesn't exist, otherwise return the existing index.
236
     *
237
     * @api
238
     * @param {string} name The index name.
239
     * @param {Matcher} [matcher] An object that describes the document properties that need to match to add it this index or a function that receives a document and returns true if the document should be indexed.
240
     * @returns {ReadableIndex} The index containing all documents that match the query.
241
     * @throws {Error} if the index doesn't exist yet and no matcher was specified.
242
     */
243
    ensureIndex(name, matcher) {
244
        if (name === '_all') {
752✔
245
            return this.index;
4✔
246
        }
247
        if (name in this.secondaryIndexes) {
748✔
248
            return this.secondaryIndexes[name].index;
4✔
249
        }
250

251
        const indexName = this.storageFile + '.' + name + '.index';
744✔
252
        if (fs.existsSync(path.join(this.indexDirectory, indexName))) {
744✔
253
            return this.openIndex(name, matcher);
16✔
254
        }
255

256
        assert((typeof matcher === 'object' || typeof matcher === 'function') && matcher !== null, 'Need to specify a matcher.');
728✔
257

258
        const metadata = buildMetadataForMatcher(matcher, this.hmac);
724✔
259
        const { index } = this.createIndex(indexName, Object.assign({}, this.indexOptions, { metadata }));
724✔
260
        try {
724✔
261
            this.forEachDocument((document, indexEntry) => {
724✔
262
                if (matches(document, matcher)) {
1,728✔
263
                    index.add(indexEntry);
16✔
264
                }
265
            });
266
        } catch (e) {
267
            index.destroy();
4✔
268
            throw e;
4✔
269
        }
270

271
        this.secondaryIndexes[name] = { index, matcher };
720✔
272
        this.emit('index-created', name);
720✔
273
        return index;
720✔
274
    }
275

276
    /**
277
     * Flush all write buffers to disk.
278
     * This is a sync method and will invoke all previously registered flush callbacks.
279
     *
280
     * @api
281
     * @returns {boolean} Returns true if a flush on any partition or the main index was executed.
282
     */
283
    flush() {
284
        let result = this.index.flush();
52✔
285
        this.forEachPartition(partition => result = result | partition.flush());
52✔
286
        this.forEachSecondaryIndex(index => index.flush());
52✔
287
        return result;
52✔
288
    }
289

290
    /**
291
     * Iterate all distinct partitions in which the given iterable list of entries are stored.
292
     * @param {Iterable<Index.Entry>} entries
293
     * @param {function(Index.Entry)} iterationHandler
294
     */
295
    forEachDistinctPartitionOf(entries, iterationHandler) {
296
        const partitions = [];
24✔
297
        const numPartitions = Object.keys(this.partitions).length;
24✔
298
        for (let entry of entries) {
24✔
299
            if (partitions.indexOf(entry.partition) >= 0) {
36✔
300
                continue;
8✔
301
            }
302
            partitions.push(entry.partition);
28✔
303
            iterationHandler(entry);
28✔
304
            if (partitions.length === numPartitions) {
28✔
305
                break;
20✔
306
            }
307
        }
308
    }
309

310
    /**
311
     * Truncate all partitions after the given (global) sequence number.
312
     *
313
     * @private
314
     * @param {number} after The document sequence number to truncate after.
315
     */
316
    truncatePartitions(after) {
317
        if (after === 0) {
40✔
318
            this.forEachPartition(partition => partition.truncate(0));
12✔
319
            return;
12✔
320
        }
321

322
        const entries = this.index.range(after + 1);  // We need the first entry that is cut off
28✔
323
        if (entries === false || entries.length === 0) {
28✔
324
            return;
4✔
325
        }
326

327
        this.forEachDistinctPartitionOf(entries, entry => this.getPartition(entry.partition).truncate(entry.position));
28✔
328
    }
329

330
    /**
331
     * Truncate the storage after the given sequence number.
332
     *
333
     * @param {number} after The document sequence number to truncate after.
334
     */
335
    truncate(after) {
336
        /*
337
         To truncate the store following steps need to be done:
338

339
         1) find all partition positions after which their files should be truncated
340
         2) truncate all partitions accordingly
341
         3) truncate/rewrite all indexes
342
         */
343
        if (!this.index.isOpen()) {
40✔
344
            this.index.open();
4✔
345
        }
346
        if (after < 0) {
40!
NEW
347
            after += this.index.length;
×
348
        }
349

350
        this.truncatePartitions(after);
40✔
351

352
        this.index.truncate(after);
40✔
353
        this.forEachSecondaryIndex(index => {
40✔
354
            /* istanbul ignore if */
355
            if (!(index instanceof WritableIndex)) {
16✔
356
                return;
357
            }
358
            let closeIndex = false;
16✔
359
            if (!index.isOpen()) {
16✔
360
                index.open();
4✔
361
                closeIndex = true;
4✔
362
            }
363
            index.truncate(index.find(after));
16✔
364
            if (closeIndex) {
16✔
365
                index.close();
4✔
366
            }
367
        });
368
    }
369

370
    /**
371
     * @protected
372
     * @param {string} name
373
     * @param {object} [options]
374
     * @returns {{ index: WritableIndex, matcher: Matcher }}
375
     */
376
    createIndex(name, options = {}) {
×
377
        const index = new WritableIndex(name, options);
1,464✔
378
        let matcher;
379

380
        // If the index contains a matcher (possibly a serialized function) we check HMAC
381
        // to prevent evaluating unknown code.
382
        if (index.metadata.matcher) {
1,456✔
383
            try {
792✔
384
                matcher = buildMatcherFromMetadata(index.metadata, this.hmac);
792✔
385
            } catch (e) {
386
                index.destroy();
4✔
387
                throw e;
4✔
388
            }
389
        }
390

391
        return { index, matcher };
1,452✔
392
    }
393

394
    /**
395
     * @protected
396
     * @param {string} name
397
     * @param {object} [config]
398
     * @returns {WritablePartition}
399
     */
400
    createPartition(name, config = {}) {
×
401
        return new WritablePartition(name, config);
700✔
402
    }
403

404
}
405

406
module.exports = WritableStorage;
4✔
407
module.exports.StorageLockedError = StorageLockedError;
4✔
408
module.exports.CorruptFileError = ReadableStorage.CorruptFileError;
4✔
409
module.exports.LOCK_THROW = LOCK_THROW;
4✔
410
module.exports.LOCK_RECLAIM = LOCK_RECLAIM;
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