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

albe / node-event-storage / 26478795255

26 May 2026 10:28PM UTC coverage: 98.342% (+0.2%) from 98.106%
26478795255

push

github

web-flow
Merge pull request #316 from albe/copilot/add-event-storage-http-api-layer

Raw buffer streaming, backwards iteration fixes, Consumer progress event, and EventStore.consumers registry

1212 of 1260 branches covered (96.19%)

Branch coverage included in aggregate %.

663 of 677 new or added lines in 11 files covered. (97.93%)

5847 of 5918 relevant lines covered (98.8%)

841.02 hits per line

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

97.56
/src/EventStore.js
1
import EventStream from './EventStream.js';
4✔
2
import JoinEventStream from './JoinEventStream.js';
4✔
3
import fs from 'fs';
4✔
4
import path from 'path';
4✔
5
import events from 'events';
4✔
6
import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from './Storage.js';
4✔
7
import Index from './Index.js';
4✔
8
import Consumer from './Consumer.js';
4✔
9
import { assert, getPropertyAtPath } from './util.js';
4✔
10
import { ensureDirectory, scanForFiles } from './fsUtil.js';
4✔
11
import { buildTypeMatcherFn } from './metadataUtil.js';
4✔
12

4✔
13
const ExpectedVersion = {
4✔
14
    Any: -1,
4✔
15
    EmptyStream: 0
4✔
16
};
4✔
17

4✔
18
/**
4✔
19
 * Default matcher property paths mirroring the Storage default, used for index optimization.
4✔
20
 */
4✔
21
const DEFAULT_MATCHER_PROPERTIES = ['stream', 'payload.type'];
4✔
22
const STREAM_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_]*(?:[\/:@~+=\-#.][A-Za-z0-9_]+)*$/;
4✔
23

4✔
24
class OptimisticConcurrencyError extends Error {}
4✔
25

4✔
26
/**
4✔
27
 * An accept condition that captures the global event-log position at the time a {@link EventStore#query}
4✔
28
 * call was made.  Pass it as the `expectedVersion` argument to {@link EventStore#commit} to enforce
4✔
29
 * DCB-style (Dynamic Consistency Boundary) optimistic concurrency: the commit is rejected only when
4✔
30
 * one or more events that match the original query (types + optional matcher) have been appended to
4✔
31
 * the store between the `query` call and the `commit` call.
4✔
32
 *
4✔
33
 * @property {string[]} types   The event types included in the query.
4✔
34
 * @property {function(object, object): boolean|null} matcher An optional function `(payload, metadata) => boolean`
4✔
35
 *   used to narrow the conflict check.  When `null`, any new event of a listed type causes a conflict.
4✔
36
 * @property {number}   noneMatchAfter The global store length (total event count) at the time the query was made.
4✔
37
 */
4✔
38
class CommitCondition {
4✔
39
    /**
4✔
40
     * @param {string[]} types
4✔
41
     * @param {function(object, object): boolean|object|null} [matcher]
4✔
42
     * @param {number}   noneMatchAfter
4✔
43
     * @param {boolean}  [raw=false]
4✔
44
     */
4✔
45
    constructor(types, matcher = null, noneMatchAfter, raw = false) {
4✔
46
        this.types = types;
96✔
47
        this.matcher = matcher;
96✔
48
        this.raw = raw;
96✔
49
        this.noneMatchAfter = noneMatchAfter;
96✔
50
    }
96✔
51
}
4✔
52

4✔
53
/**
4✔
54
 * An event store optimized for working with many streams.
4✔
55
 * An event stream is implemented as an iterator over an index on the storage, therefore indexes need to be lightweight
4✔
56
 * and highly performant in read-only mode.
4✔
57
 */
4✔
58
class EventStore extends events.EventEmitter {
4✔
59

4✔
60
    /**
4✔
61
     * @param {string} [storeName] The name of the store which will be used as storage prefix. Default 'eventstore'.
4✔
62
     * @param {object} [config] An object with config options.
4✔
63
     * @param {string} [config.storageDirectory] The directory where the data should be stored. Default './data'.
4✔
64
     * @param {string} [config.streamsDirectory] The directory where the streams should be stored. Default '{storageDirectory}/streams'.
4✔
65
     * @param {object} [config.storageConfig] Additional config options given to the storage backend. See `Storage`.
4✔
66
     * @param {boolean} [config.readOnly] If the storage should be mounted in read-only mode.
4✔
67
     * @param {string|function(object): string} [config.typeAccessor] Dot-notation path (e.g. `'type'`) or
4✔
68
     *   function `(event) => string` identifying the event type. Enables type-based queries via
4✔
69
     *   {@link EventStore#query} and ensures proper index routing for those queries.
4✔
70
     * @param {object|function(string): object} [config.streamMetadata] A metadata object or a function `(streamName) => object`
4✔
71
     *   that is called whenever a new stream partition is created. The returned object is stored once in the partition
4✔
72
     *   file header and surfaced to `preCommit` / `preRead` hooks. Takes precedence only when
4✔
73
     *   `config.storageConfig.metadata` is not also set.
4✔
74
     */
4✔
75
    constructor(storeName = 'eventstore', config = {}) {
4✔
76
        super();
652✔
77
        if (typeof storeName !== 'string') {
652✔
78
            config = storeName;
648✔
79
            storeName = 'eventstore';
648✔
80
        }
648✔
81

652✔
82
        if (typeof config.typeAccessor === 'string' && config.typeAccessor) {
652✔
83
            const accessorPath = config.typeAccessor;
24✔
84
            this.typeAccessor = (event) => getPropertyAtPath(event, accessorPath);
24✔
85
            this.typeMatcherFn = buildTypeMatcherFn(accessorPath);
24✔
86
        } else {
652✔
87
            this.typeAccessor = typeof config.typeAccessor === 'function' ? config.typeAccessor : null;
628✔
88
            this.typeMatcherFn = null;
628✔
89
        }
628✔
90

652✔
91
        this.storageDirectory = path.resolve(config.storageDirectory || /* istanbul ignore next */ './data');
652!
92
        let defaults = {
652✔
93
            dataDirectory: this.storageDirectory,
652✔
94
            indexDirectory: config.streamsDirectory || path.join(this.storageDirectory, 'streams'),
652✔
95
            partitioner: (event) => event.stream,
652✔
96
            readOnly: config.readOnly || false
652✔
97
        };
652✔
98
        const storageConfig = Object.assign(defaults, config.storageConfig);
652✔
99

652✔
100
        // When typeAccessor is a string path, ensure the corresponding full document path
652✔
101
        // (payload.<path>) is present in matcherProperties so the IndexMatcher discriminant
652✔
102
        // table can route type-stream lookups in O(1) on every write.
652✔
103
        if (this.typeMatcherFn) {
652✔
104
            const fullPath = `payload.${config.typeAccessor}`;
24✔
105
            const currentProps = storageConfig.matcherProperties || DEFAULT_MATCHER_PROPERTIES;
24✔
106
            if (!currentProps.includes(fullPath)) {
24✔
107
                storageConfig.matcherProperties = [...currentProps, fullPath];
8✔
108
            }
8✔
109
        }
24✔
110

652✔
111
        // Translate the high-level streamMetadata option into the storage-level metadata function,
652✔
112
        // but only when the caller has not already provided a lower-level storageConfig.metadata.
652✔
113
        if (config.streamMetadata !== undefined && storageConfig.metadata === undefined) {
652✔
114
            if (typeof config.streamMetadata === 'function') {
76✔
115
                storageConfig.metadata = config.streamMetadata;
4✔
116
            } else {
76✔
117
                storageConfig.metadata = (streamName) => config.streamMetadata[streamName] || {};
72✔
118
            }
72✔
119
        }
76✔
120

652✔
121
        this.initialize(storeName, storageConfig);
652✔
122
    }
652✔
123

4✔
124
    /**
4✔
125
     * @private
4✔
126
     * @param {string} storeName
4✔
127
     * @param {object} storageConfig
4✔
128
     */
4✔
129
    initialize(storeName, storageConfig) {
4✔
130
        this.streamsDirectory = path.resolve(storageConfig.indexDirectory);
652✔
131

652✔
132
        this.storeName = storeName;
652✔
133
        this.storage = (storageConfig.readOnly === true) ?
652✔
134
                        new ReadOnlyStorage(storeName, storageConfig)
44✔
135
                        : new Storage(storeName, storageConfig);
652✔
136
        this.streams = Object.create(null);
652✔
137
        this.streams._all = { index: this.storage.index };
652✔
138
        this.consumers = new Map();
652✔
139

652✔
140
        this.storage.on('index-created', this.registerStream.bind(this));
652✔
141

652✔
142
        this.storage.on('opened', () => {
652✔
143
            this.checkUnfinishedCommits();
128✔
144
            this.emit('ready');
128✔
145
        });
652✔
146

652✔
147
        this.storage.open();
652✔
148
    }
652✔
149

4✔
150
    /**
4✔
151
     * Check if the last commit in the store was unfinished, which is the case if not all events of the commit have been written.
4✔
152
     * Torn writes are handled at the storage level, so this method only deals with unfinished commits.
4✔
153
     * @private
4✔
154
     */
4✔
155
    checkUnfinishedCommits() {
4✔
156
        let position = this.storage.length;
128✔
157
        let lastEvent;
128✔
158
        let truncateIndex = false;
128✔
159
        while (position > 0) {
128✔
160
            try {
80✔
161
                lastEvent = this.storage.read(position);
80✔
162
            } catch (e) {
80!
163
                // A preRead hook may throw (e.g. access control). Stop repair check.
×
164
                return;
×
165
            }
×
166
            if (lastEvent !== false) break;
80✔
167
            truncateIndex = true;
16✔
168
            position--;
16✔
169
        }
16✔
170

128✔
171
        if (lastEvent && lastEvent.metadata.commitSize && lastEvent.metadata.commitVersion !== lastEvent.metadata.commitSize - 1) {
128✔
172
            this.emit('unfinished-commit', lastEvent);
8✔
173
            // commitId = global sequence number at which the commit started
8✔
174
            this.storage.truncate(lastEvent.metadata.commitId);
8✔
175
        } else if (truncateIndex) {
128✔
176
            // The index contained items that are not in the storage file; truncate everything
4✔
177
            // after `position`, the last sequence number that was successfully read.
4✔
178
            this.storage.truncate(position);
4✔
179
        }
4✔
180
    }
128✔
181

4✔
182
    /**
4✔
183
     * @private
4✔
184
     * @param {string} name The full stream name, including the `stream-` prefix (and optional `.closed` suffix).
4✔
185
     */
4✔
186
    registerStream(name) {
4✔
187
        /* istanbul ignore if */
1,064✔
188
        if (!name.startsWith('stream-')) {
1,064!
189
            return;
×
190
        }
×
191
        let streamName = name.slice(7);
1,064✔
192
        // Detect the `.closed` suffix — present both in the initial scan and when the directory
1,064✔
193
        // watcher emits 'index-created' after a writer renames the file (e.g. 'stream-foo-bar.closed').
1,064✔
194
        let isClosed = false;
1,064✔
195
        if (streamName.endsWith('.closed')) {
1,064✔
196
            streamName = streamName.slice(0, -7);
8✔
197
            isClosed = true;
8✔
198
        }
8✔
199
        if (streamName in this.streams) {
1,064✔
200
            if (isClosed && !this.streams[streamName].closed) {
44✔
201
                // The stream was renamed to .closed while this instance had it open.
4✔
202
                // The old ReadOnlyIndex was already closed via onRename, so we open the new one.
4✔
203
                const closedIndexName = 'stream-' + streamName + '.closed';
4✔
204
                const closedIndex = this.storage.openReadonlyIndex(closedIndexName);
4✔
205
                // deepcode ignore PrototypePollutionFunctionParams: streams is a Map
4✔
206
                this.streams[streamName] = { index: closedIndex, closed: true };
4✔
207
                this.emit('stream-closed', streamName);
4✔
208
            }
4✔
209
            return;
44✔
210
        }
44✔
211
        const index = isClosed
1,020✔
212
            ? this.storage.openReadonlyIndex(name)
1,064✔
213
            : this.storage.openIndex(name);
1,064✔
214
        // deepcode ignore PrototypePollutionFunctionParams: streams is a Map
1,064✔
215
        this.streams[streamName] = { index, closed: isClosed };
1,064✔
216
        this.emit('stream-available', streamName);
1,064✔
217
    }
1,064✔
218

4✔
219
    /**
4✔
220
     * Close the event store and free up all resources.
4✔
221
     * Stops all registered consumers before closing storage.
4✔
222
     *
4✔
223
     * @api
4✔
224
     */
4✔
225
    close() {
4✔
226
        for (const consumer of this.consumers.values()) {
644✔
227
            consumer.stop();
20✔
228
        }
20✔
229
        this.consumers.clear();
644✔
230
        this.storage.close();
644✔
231
    }
644✔
232

4✔
233
    /**
4✔
234
     * Override EventEmitter.on() to delegate 'preCommit' and 'preRead' event registrations
4✔
235
     * to the underlying storage, so that `eventstore.on('preCommit', handler)` works naturally.
4✔
236
     * All other events are handled by the default EventEmitter.
4✔
237
     *
4✔
238
     * @param {string} event
4✔
239
     * @param {function} listener
4✔
240
     * @returns {this}
4✔
241
     */
4✔
242
    on(event, listener) {
4✔
243
        if (event === 'preCommit' || event === 'preRead') {
208✔
244
            if (event === 'preCommit') {
76✔
245
                assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not register a preCommit handler on it.');
40✔
246
            }
40✔
247
            this.storage.on(event, listener);
68✔
248
            return this;
68✔
249
        }
68✔
250
        return super.on(event, listener);
132✔
251
    }
208✔
252

4✔
253
    /**
4✔
254
     * @inheritDoc
4✔
255
     */
4✔
256
    addListener(event, listener) {
4✔
257
        return this.on(event, listener);
4✔
258
    }
4✔
259

4✔
260
    /**
4✔
261
     * Override EventEmitter.once() to delegate 'preCommit' and 'preRead' to the underlying storage.
4✔
262
     *
4✔
263
     * @param {string} event
4✔
264
     * @param {function} listener
4✔
265
     * @returns {this}
4✔
266
     */
4✔
267
    once(event, listener) {
4✔
268
        if (event === 'preCommit' || event === 'preRead') {
12✔
269
            if (event === 'preCommit') {
8✔
270
                assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not register a preCommit handler on it.');
4✔
271
            }
4✔
272
            this.storage.once(event, listener);
8✔
273
            return this;
8✔
274
        }
8✔
275
        return super.once(event, listener);
4✔
276
    }
12✔
277

4✔
278
    /**
4✔
279
     * Override EventEmitter.off() / removeListener() to delegate 'preCommit' and 'preRead'
4✔
280
     * to the underlying storage.
4✔
281
     *
4✔
282
     * @param {string} event
4✔
283
     * @param {function} listener
4✔
284
     * @returns {this}
4✔
285
     */
4✔
286
    off(event, listener) {
4✔
287
        if (event === 'preCommit' || event === 'preRead') {
24✔
288
            this.storage.off(event, listener);
12✔
289
            return this;
12✔
290
        }
12✔
291
        return super.off(event, listener);
12✔
292
    }
24✔
293

4✔
294
    /**
4✔
295
     * @inheritDoc
4✔
296
     */
4✔
297
    removeListener(event, listener) {
4✔
298
        return this.off(event, listener);
12✔
299
    }
12✔
300

4✔
301
    /**
4✔
302
     * Convenience method to register a handler called before an event is committed to storage.
4✔
303
     * Equivalent to `eventstore.on('preCommit', hook)`.
4✔
304
     * The handler receives `(event, partitionMetadata)` and may throw to abort the write.
4✔
305
     * Multiple handlers can be registered; all run on every write in registration order.
4✔
306
     * The handler is invoked on every write, so its logic should be cheap, fast, and synchronous.
4✔
307
     *
4✔
308
     * @api
4✔
309
     * @param {function(object, object): void} hook A function receiving (event, partitionMetadata).
4✔
310
     * @throws {Error} If the storage was opened in read-only mode.
4✔
311
     */
4✔
312
    preCommit(hook) {
4✔
313
        this.on('preCommit', hook);
20✔
314
    }
20✔
315

4✔
316
    /**
4✔
317
     * Convenience method to register a handler called before an event is read from storage.
4✔
318
     * Equivalent to `eventstore.on('preRead', hook)`.
4✔
319
     * The handler receives `(position, partitionMetadata)` and may throw to abort the read.
4✔
320
     * Multiple handlers can be registered; all run on every read in registration order.
4✔
321
     * The handler is invoked on every read, so its logic should be cheap, fast, and synchronous.
4✔
322
     *
4✔
323
     * @api
4✔
324
     * @param {function(number, object): void} hook A function receiving (position, partitionMetadata).
4✔
325
     */
4✔
326
    preRead(hook) {
4✔
327
        this.on('preRead', hook);
12✔
328
    }
12✔
329

4✔
330
    /**
4✔
331
     * Get the number of events stored.
4✔
332
     *
4✔
333
     * @api
4✔
334
     * @returns {number}
4✔
335
     */
4✔
336
    get length() {
4✔
337
        return this.storage.length;
1,464✔
338
    }
1,464✔
339

4✔
340
    /**
4✔
341
     * This method makes it so the last three arguments can be given either as:
4✔
342
     *  - expectedVersion, metadata, callback
4✔
343
     *  - expectedVersion, callback
4✔
344
     *  - metadata, callback
4✔
345
     *  - callback
4✔
346
     *
4✔
347
     * @private
4✔
348
     * @param {Array<object>|object} events
4✔
349
     * @param {number|CommitCondition} [expectedVersion]
4✔
350
     * @param {object|function} [metadata]
4✔
351
     * @param {function} [callback]
4✔
352
     * @returns {{events: Array<object>, metadata: object, callback: function, expectedVersion: number|CommitCondition}}
4✔
353
     */
4✔
354
    static fixArgumentTypes(events, expectedVersion, metadata, callback) {
4✔
355
        if (!(events instanceof Array)) {
1,228✔
356
            events = [events];
108✔
357
        }
108✔
358
        if (typeof expectedVersion !== 'number' && !(expectedVersion instanceof CommitCondition)) {
1,228✔
359
            callback = metadata;
352✔
360
            metadata = expectedVersion;
352✔
361
            expectedVersion = ExpectedVersion.Any;
352✔
362
        }
352✔
363
        if (typeof metadata !== 'object') {
1,228✔
364
            callback = metadata;
360✔
365
            metadata = {};
360✔
366
        }
360✔
367
        if (typeof callback !== 'function') {
1,228✔
368
            callback = () => {};
856✔
369
        }
856✔
370
        return { events, expectedVersion, metadata, callback };
1,228✔
371
    }
1,228✔
372

4✔
373
    /**
4✔
374
     * Check a {@link CommitCondition} against the current state of the store.
4✔
375
     * Iterates a join stream over all condition type streams starting from
4✔
376
     * `condition.noneMatchAfter` (the global position captured at query time), and throws an
4✔
377
     * {@link OptimisticConcurrencyError} when a new event of a listed type satisfies
4✔
378
     * `condition.matcher(payload, metadata)` (or any such event when no matcher is provided).
4✔
379
     *
4✔
380
     * @param {CommitCondition} condition
4✔
381
     * @throws {OptimisticConcurrencyError}
4✔
382
     */
4✔
383
    checkCondition(condition) {
4✔
384
        if (this.storage.length <= condition.noneMatchAfter) return; // no new events since condition was obtained
28✔
385

16✔
386
        const existingTypes = condition.types.filter(t => t in this.streams);
16✔
387
        if (existingTypes.length === 0) return;
28!
388

16✔
389
        // Only events after condition.noneMatchAfter can be conflicts.
16✔
390
        // Pass the original matcher and raw flag so the stream filters at the source.
16✔
391
        const stream = this.fromStreams(
16✔
392
            '_check_' + condition.types.join('_'),
16✔
393
            existingTypes,
16✔
394
            condition.noneMatchAfter + 1,
16✔
395
            -1,
16✔
396
            condition.matcher,
16✔
397
            condition.raw
16✔
398
        );
16✔
399

16✔
400
        if (stream.next() !== false) {
28✔
401
            throw new OptimisticConcurrencyError(
12✔
402
                `Optimistic Concurrency error. A conflicting event was committed since the condition was obtained.`
12✔
403
            );
12✔
404
        }
12✔
405
    }
28✔
406

4✔
407
    /**
4✔
408
     * Ensure a dedicated type stream exists for each event's type, creating it if needed.
4✔
409
     * Must be called before the entity stream is created to guarantee correct index routing.
4✔
410
     *
4✔
411
     * @param {Array<object>} events The events to process.
4✔
412
     */
4✔
413
    ensureTypeStreams(events) {
4✔
414
        if (!this.typeAccessor) return;
1,216✔
415
        for (const event of events) {
1,216✔
416
            const type = this.resolveValidatedTypeStreamName(event);
148✔
417
            if (type && !(type in this.streams)) {
148✔
418
                const matcher = this.typeMatcherFn
112✔
419
                    ? this.typeMatcherFn(type)
112✔
420
                    : (doc) => this.typeAccessor(doc.payload) === type;
112✔
421
                this.createEventStream(type, matcher, false);
112✔
422
            }
112✔
423
        }
148✔
424
    }
1,216✔
425

4✔
426
    resolveValidatedTypeStreamName(event) {
4✔
427
        const type = this.typeAccessor(event);
148✔
428
        if (type === undefined || type === null || type === '') {
148✔
429
            return null;
8✔
430
        }
8✔
431
        assert(typeof type === 'string', 'typeAccessor must return a string.');
140✔
432
        assert(STREAM_NAME_PATTERN.test(type), `typeAccessor must return a valid stream name. Got: "${type}"`);
140✔
433
        return type;
140✔
434
    }
148✔
435

4✔
436
    /**
4✔
437
     * Commit a list of events for the given stream name, which is expected to be at the given version.
4✔
438
     * Note that the events committed may still appear in other streams too - the given stream name is only
4✔
439
     * relevant for optimistic concurrency checks with the given expected version.
4✔
440
     *
4✔
441
     * @api
4✔
442
     * @param {string} streamName The name of the stream to commit the events to.
4✔
443
     * @param {Array<object>|object} events The events to commit or a single event.
4✔
444
     * @param {number|CommitCondition} [expectedVersion] One of the `ExpectedVersion` constants, a positive
4✔
445
     *   stream version number, or a {@link CommitCondition} obtained from {@link EventStore#query}.
4✔
446
     * @param {object} [metadata] The commit metadata to use as base. Useful for replication and adding storage metadata.
4✔
447
     * @param {function} [callback] A function that will be executed when all events have been committed.
4✔
448
     * @throws {OptimisticConcurrencyError} if the stream is not at the expected version, or if a
4✔
449
     *   {@link CommitCondition} was provided and conflicting events have been committed since it was obtained.
4✔
450
     */
4✔
451
    commit(streamName, events, expectedVersion = ExpectedVersion.Any, metadata = {}, callback = null) {
4✔
452
        assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not commit to it.');
1,240✔
453
        assert(typeof streamName === 'string' && streamName !== '', 'Must specify a stream name for commit.');
1,240✔
454
        assert(typeof events !== 'undefined' && events !== null, 'No events specified for commit.');
1,240✔
455

1,240✔
456
        ({ events, expectedVersion, metadata, callback } = EventStore.fixArgumentTypes(events, expectedVersion, metadata, callback));
1,240✔
457

1,240✔
458
        // Perform DCB-style concurrency check when a CommitCondition is provided.
1,240✔
459
        if (expectedVersion instanceof CommitCondition) {
1,240✔
460
            this.checkCondition(expectedVersion);
28✔
461
            expectedVersion = ExpectedVersion.Any;
28✔
462
        }
28✔
463

1,216✔
464
        // When typeAccessor is configured, ensure a dedicated type stream exists for each event
1,216✔
465
        // before the entity stream write so the type stream index is never incomplete.
1,216✔
466
        this.ensureTypeStreams(events);
1,216✔
467

1,216✔
468
        if (!(streamName in this.streams)) {
1,240✔
469
            this.createEventStream(streamName, { stream: streamName }, false);
760✔
470
        }
760✔
471
        assert(!this.streams[streamName].closed, `Stream "${streamName}" is closed and cannot be written to.`);
1,208✔
472
        let streamVersion = this.streams[streamName].index.length;
1,208✔
473
        if (expectedVersion !== ExpectedVersion.Any && streamVersion !== expectedVersion) {
1,240✔
474
            throw new OptimisticConcurrencyError(`Optimistic Concurrency error. Expected stream "${streamName}" at version ${expectedVersion} but is at version ${streamVersion}.`);
12✔
475
        }
12✔
476

1,188✔
477
        if (events.length > 1) {
1,240✔
478
            delete metadata.commitVersion;
68✔
479
        }
68✔
480

1,188✔
481
        const commitId = this.length;
1,188✔
482
        let commitVersion = 0;
1,188✔
483
        const commitSize = events.length;
1,188✔
484
        const committedAt = Date.now();
1,188✔
485
        const commit = Object.assign({
1,188✔
486
            commitId,
1,188✔
487
            committedAt
1,188✔
488
        }, metadata, {
1,188✔
489
            streamName,
1,188✔
490
            streamVersion,
1,188✔
491
            events: []
1,188✔
492
        });
1,188✔
493
        const commitCallback = () => {
1,188✔
494
            this.emit('commit', commit);
1,184✔
495
            callback(commit);
1,184✔
496
        };
1,188✔
497
        for (let event of events) {
1,240✔
498
            const eventMetadata = Object.assign({ commitId, committedAt, commitVersion, commitSize }, metadata, { streamVersion });
1,284✔
499
            const storedEvent = { stream: streamName, payload: event, metadata: eventMetadata };
1,284✔
500
            commitVersion++;
1,284✔
501
            streamVersion++;
1,284✔
502
            commit.events.push(event);
1,284✔
503
            this.storage.write(storedEvent, commitVersion !== events.length ? undefined : commitCallback);
1,284✔
504
        }
1,284✔
505
    }
1,240✔
506

4✔
507
    /**
4✔
508
     * @api
4✔
509
     * @param {string} streamName The name of the stream to get the version for.
4✔
510
     * @returns {number} The version that the given stream is at currently, or -1 if the stream does not exist.
4✔
511
     */
4✔
512
    getStreamVersion(streamName) {
4✔
513
        if (!(streamName in this.streams)) {
116✔
514
            return -1;
20✔
515
        }
20✔
516
        return this.streams[streamName].index.length;
96✔
517
    }
116✔
518

4✔
519
    /**
4✔
520
     * Query the event store for events matching a set of event types and an optional filter function.
4✔
521
     * Returns a pre-filtered event stream and a {@link CommitCondition} that can be passed to
4✔
522
     * {@link EventStore#commit} to enforce optimistic concurrency.
4✔
523
     *
4✔
524
     * A conflict occurs when at least one event appended between the `query` call and the `commit` call
4✔
525
     * belongs to one of the listed types and (when `matcher` is provided) also satisfies
4✔
526
     * `matcher(payload, metadata)`.  Events written before the `query` call are never treated as conflicts.
4✔
527
     *
4✔
528
     * **Behaviour when a type stream does not exist:**
4✔
529
     * - Without `typeAccessor` configured: throws an error, because the store cannot guarantee that no
4✔
530
     *   events of that type exist (the stream was never created).  Create the stream explicitly first,
4✔
531
     *   or configure `typeAccessor` to have streams created automatically on commit.
4✔
532
     * - With `typeAccessor` configured: treats the missing stream as empty (0-length).  The stream will
4✔
533
     *   be created automatically the first time an event of that type is committed.
4✔
534
     *
4✔
535
     * @api
4✔
536
     * @param {string[]} types A non-empty array of event-type names to query.
4✔
537
     * @param {function|object|null} [matcher] Optional matcher used for stream pre-filtering.
4✔
538
     *   In object mode, function predicates receive `(payload, metadata)`.
4✔
539
     * @param {number} [minRevision=1] The 1-based minimum global revision to include in the returned stream (inclusive).
4✔
540
     * @param {boolean} [raw=false] If true, return NDJSON buffers from the query stream.
4✔
541
     * @returns {{ condition: CommitCondition, stream: EventStream }} An object with:
4✔
542
     *   - `condition` — the {@link CommitCondition} to pass to {@link EventStore#commit}.
4✔
543
     *   - `stream` — a read-only event stream containing all matching events.
4✔
544
     * @throws {Error} if `types` is not a non-empty array.
4✔
545
     * @throws {Error} if `typeAccessor` is not configured and any of the listed type streams do not exist.
4✔
546
     */
4✔
547
    query(types, matcher = null, minRevision = 1, raw = false) {
4✔
548
        assert(Array.isArray(types) && types.length > 0, 'Must specify a non-empty array of event types for query.');
108✔
549

108✔
550
        const queryTypes = [];
108✔
551
        for (const type of types) {
108✔
552
            if (!(type in this.streams)) {
112✔
553
                if (this.typeAccessor) {
52✔
554
                    // typeAccessor is configured: type streams are created on commit, so a missing
48✔
555
                    // stream simply means no event of this type has been committed yet — treat as empty.
48✔
556
                    continue;
48✔
557
                }
48✔
558
                // No typeAccessor: the stream was never created; we cannot know whether events of
4✔
559
                // this type exist in the store, so throw to avoid an unintentional full-store scan.
4✔
560
                throw new Error(`Type stream "${type}" does not exist. Create it with createEventStream() first, or configure typeAccessor to have type streams created automatically on commit.`);
4✔
561
            }
4✔
562
            queryTypes.push(type);
60✔
563
        }
60✔
564

96✔
565
        const condition = new CommitCondition(types, matcher, this.storage.length, raw);
96✔
566
        const stream = this.fromStreams('_query_' + types.join('_'), queryTypes, minRevision, -1, matcher, raw);
96✔
567
        return { stream, condition };
96✔
568
    }
108✔
569

4✔
570
    /**
4✔
571
     * Get an event stream for the given stream name within the revision boundaries.
4✔
572
     *
4✔
573
     * @api
4✔
574
     * @param {string} streamName The name of the stream to get.
4✔
575
     * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
4✔
576
     * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
4✔
577
     * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
4✔
578
     * @param {boolean} [raw=false] If true, return NDJSON buffers.
4✔
579
     * @returns {EventStream|boolean} The event stream or false if a stream with the name doesn't exist.
4✔
580
     */
4✔
581
    getEventStream(streamName, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
4✔
582
        if (typeof predicate === 'boolean' && raw === false) {
204✔
583
            raw = predicate;
4✔
584
            predicate = null;
4✔
585
        }
4✔
586
        if (!(streamName in this.streams)) {
204✔
587
            return false;
4✔
588
        }
4✔
589
        return new EventStream(streamName, this, minRevision, maxRevision, predicate, raw);
200✔
590
    }
204✔
591

4✔
592
    /**
4✔
593
     * Get a stream for all events within the revision boundaries.
4✔
594
     * This is the same as `getEventStream('_all', ...)`.
4✔
595
     *
4✔
596
     * @api
4✔
597
     * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
4✔
598
     * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
4✔
599
     * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
4✔
600
     * @param {boolean} [raw=false] If true, return NDJSON buffers.
4✔
601
     * @returns {EventStream} The event stream.
4✔
602
     */
4✔
603
    getAllEvents(minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
4✔
604
        if (typeof predicate === 'boolean' && raw === false) {
12✔
605
            raw = predicate;
4✔
606
            predicate = null;
4✔
607
        }
4✔
608
        return this.getEventStream('_all', minRevision, maxRevision, predicate, raw);
12✔
609
    }
12✔
610

4✔
611
    /**
4✔
612
     * Create a virtual event stream from existing streams by joining them.
4✔
613
     *
4✔
614
     * @param {string} streamName The (transient) name of the joined stream.
4✔
615
     * @param {Array<string>} streamNames An array of the stream names to join.
4✔
616
     * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
4✔
617
     * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
4✔
618
     * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
4✔
619
     * @param {boolean} [raw=false] If true, return NDJSON buffers.
4✔
620
     * @returns {EventStream} The joined event stream.
4✔
621
     * @throws {Error} if any of the streams doesn't exist.
4✔
622
     */
4✔
623
    fromStreams(streamName, streamNames, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
4✔
624
        if (typeof predicate === 'boolean' && raw === false) {
172✔
625
            raw = predicate;
4✔
626
            predicate = null;
4✔
627
        }
4✔
628
        assert(streamNames instanceof Array, 'Must specify an array of stream names.');
172✔
629

172✔
630
        if (streamNames.length === 0) {
172✔
631
            return new EventStream(streamName, this);
44✔
632
        }
44✔
633

120✔
634
        for (let stream of streamNames) {
172✔
635
            assert(stream in this.streams, `Stream "${stream}" does not exist.`);
288✔
636
        }
288✔
637

116✔
638
        if (streamNames.length === 1) {
172✔
639
            const stream = new EventStream(streamNames[0], this, minRevision, maxRevision, predicate, raw);
60✔
640
            stream.name = streamName;
60✔
641
            return stream;
60✔
642
        }
60✔
643

56✔
644
        return new JoinEventStream(streamName, streamNames, this, minRevision, maxRevision, predicate, raw);
56✔
645
    }
172✔
646

4✔
647
    /**
4✔
648
     * Get a stream for a category of streams. This will effectively return a joined stream of all streams that start
4✔
649
     * with the given `categoryName` followed by a dash (flat layout, e.g. `users-123`) or a slash (hierarchical
4✔
650
     * layout, e.g. `users/123`).
4✔
651
     * If you frequently use this for a category consisting of a lot of streams (e.g. `users`), consider creating a
4✔
652
     * dedicated physical stream for the category:
4✔
653
     *
4✔
654
     *    `eventstore.createEventStream('users', e => e.stream.startsWith('users-') || e.stream.startsWith('users/'))`
4✔
655
     *
4✔
656
     * @api
4✔
657
     * @param {string} categoryName The name of the category to get a stream for. A category is a stream name prefix.
4✔
658
     * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
4✔
659
     * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
4✔
660
     * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
4✔
661
     * @param {boolean} [raw=false] If true, return NDJSON buffers.
4✔
662
     * @returns {EventStream} The joined event stream for all streams of the given category.
4✔
663
     * @throws {Error} If no stream for this category exists.
4✔
664
     */
4✔
665
    getEventStreamForCategory(categoryName, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
4✔
666
        if (typeof predicate === 'boolean' && raw === false) {
40✔
667
            raw = predicate;
4✔
668
            predicate = null;
4✔
669
        }
4✔
670
        if (categoryName in this.streams) {
40✔
671
            return this.getEventStream(categoryName, minRevision, maxRevision, predicate, raw);
4✔
672
        }
4✔
673
        const categoryStreams = Object.keys(this.streams).filter(streamName =>
36✔
674
            streamName.startsWith(categoryName + '-') ||
224✔
675
            streamName.startsWith(categoryName + '/')
128✔
676
        );
36✔
677

36✔
678
        if (categoryStreams.length === 0) {
40✔
679
            throw new Error(`No streams for category '${categoryName}' exist.`);
4✔
680
        }
4✔
681
        return this.fromStreams(categoryName, categoryStreams, minRevision, maxRevision, predicate, raw);
32✔
682
    }
40✔
683

4✔
684
    /**
4✔
685
     * Create a new stream with the given matcher.
4✔
686
     *
4✔
687
     * @api
4✔
688
     * @param {string} streamName The name of the stream to create.
4✔
689
     * @param {object|function(event)} matcher A matcher object, denoting the properties that need to match on an event a function that takes the event and returns true if the event should be added.
4✔
690
     * @param {boolean} [reindex=true] Whether to scan existing documents and populate the new index. Set to false when it is known that no existing documents can match the matcher (e.g. when creating a brand-new write stream).
4✔
691
     * @returns {EventStream} The EventStream with all existing events matching the matcher.
4✔
692
     * @throws {Error} If a stream with that name already exists.
4✔
693
     * @throws {Error} If the stream could not be created.
4✔
694
     */
4✔
695
    createEventStream(streamName, matcher, reindex = true) {
4✔
696
        assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not create new stream on it.');
952✔
697
        assert(!(streamName in this.streams), 'Can not recreate stream!');
952✔
698

952✔
699
        const streamIndexName = 'stream-' + streamName;
952✔
700
        if (streamName.includes('/')) {
952✔
701
            const subDir = path.join(this.streamsDirectory, this.storeName + '.stream-' + path.dirname(streamName));
88✔
702
            ensureDirectory(subDir);
88✔
703
        }
88✔
704
        const index = this.storage.ensureIndex(streamIndexName, matcher, reindex);
936✔
705
        assert(index !== null, `Error creating stream index ${streamName}.`);
936✔
706

936✔
707
        // deepcode ignore PrototypePollutionFunctionParams: streams is a Map
936✔
708
        this.streams[streamName] = { index, matcher };
936✔
709
        this.emit('stream-created', streamName);
936✔
710
        return new EventStream(streamName, this);
936✔
711
    }
952✔
712

4✔
713
    /**
4✔
714
     * Delete an event stream. Will do nothing if the stream with the name doesn't exist.
4✔
715
     *
4✔
716
     * Note that you can delete a write stream, but that will not delete the events written to it.
4✔
717
     * Also, on next write, that stream will be rebuilt from all existing events, which might take some time.
4✔
718
     *
4✔
719
     * @api
4✔
720
     * @param {string} streamName The name of the stream to delete.
4✔
721
     * @returns void
4✔
722
     */
4✔
723
    deleteEventStream(streamName) {
4✔
724
        assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not delete a stream on it.');
12✔
725

12✔
726
        if (!(streamName in this.streams)) {
12✔
727
            return;
4✔
728
        }
4✔
729
        this.streams[streamName].index.destroy();
4✔
730
        delete this.streams[streamName];
4✔
731
        this.emit('stream-deleted', streamName);
4✔
732
    }
12✔
733

4✔
734
    /**
4✔
735
     * Close a stream so that no new events are indexed into it.
4✔
736
     * The stream will still be readable, but any attempt to write to it will throw an error.
4✔
737
     * A closed stream is persisted by renaming its index file to include a `.closed` marker
4✔
738
     * (e.g. `stream-X.closed.index`), so it will be recognized as closed when the store is reopened.
4✔
739
     *
4✔
740
     * @api
4✔
741
     * @param {string} streamName The name of the stream to close.
4✔
742
     * @returns void
4✔
743
     * @throws {Error} If the storage is read-only.
4✔
744
     * @throws {Error} If the stream does not exist.
4✔
745
     * @throws {Error} If the stream is already closed.
4✔
746
     */
4✔
747
    closeEventStream(streamName) {
4✔
748
        assert(!(this.storage instanceof ReadOnlyStorage), 'The storage was opened in read-only mode. Can not close a stream on it.');
48✔
749
        assert(streamName in this.streams, `Stream "${streamName}" does not exist.`);
48✔
750
        assert(!this.streams[streamName].closed, `Stream "${streamName}" is already closed.`);
48✔
751

48✔
752
        const indexName = 'stream-' + streamName;
48✔
753
        const { index } = this.streams[streamName];
48✔
754

48✔
755
        // Flush and close the index before renaming the file
48✔
756
        index.close();
48✔
757

48✔
758
        // Rename the index file to mark it as closed (e.g. stream-foo.index -> stream-foo.closed.index)
48✔
759
        const closedFileName = index.fileName.replace(/\.index$/, '.closed.index');
48✔
760
        fs.renameSync(index.fileName, closedFileName);
48✔
761

48✔
762
        // Remove from secondary indexes so that new writes are no longer indexed into this stream
48✔
763
        this.storage.removeSecondaryIndex(indexName);
48✔
764

48✔
765
        // Reopen the renamed index for read access, outside the secondary indexes write path
48✔
766
        const closedIndexName = indexName + '.closed';
48✔
767
        const closedIndex = this.storage.openReadonlyIndex(closedIndexName);
48✔
768

48✔
769
        // deepcode ignore PrototypePollutionFunctionParams: streams is a Map
48✔
770
        this.streams[streamName] = { index: closedIndex, closed: true };
48✔
771
        this.emit('stream-closed', streamName);
48✔
772
    }
48✔
773

4✔
774
    /**
4✔
775
     * Get a durable consumer for the given stream, or look up an existing consumer by identifier.
4✔
776
     *
4✔
777
     * When called with a single argument, returns the running consumer registered under that
4✔
778
     * identifier, or `null` if none is found — useful for read endpoints that need the live
4✔
779
     * in-memory instance without creating a new one.
4✔
780
     *
4✔
781
     * When called with two or more arguments, creates (or re-uses) a Consumer for the given
4✔
782
     * stream and identifier, registers it in `this.consumers`, and returns it.
4✔
783
     *
4✔
784
     * @param {string} streamNameOrIdentifier The stream name, or the consumer identifier when used as a registry lookup.
4✔
785
     * @param {string} [identifier] The unique identifying name of this consumer. Omit for registry-only lookup.
4✔
786
     * @param {object} [initialState] The initial state of the consumer.
4✔
787
     * @param {number} [since] The stream revision to start consuming from.
4✔
788
     * @returns {Consumer|null} A durable consumer, or `null` when looking up by identifier and none is registered.
4✔
789
     */
4✔
790
    getConsumer(streamNameOrIdentifier, identifier, initialState = {}, since = 0) {
4✔
791
        if (identifier === undefined) {
20!
NEW
792
            return this.consumers.get(streamNameOrIdentifier) ?? null;
×
NEW
793
        }
×
794
        const streamName = streamNameOrIdentifier;
20✔
795
        if (this.consumers.has(identifier)) {
20!
NEW
796
            return this.consumers.get(identifier);
×
NEW
797
        }
×
798
        const consumer = new Consumer(this.storage, streamName === '_all' ? '_all' : 'stream-' + streamName, identifier, initialState, since);
20✔
799
        consumer.streamName = streamName;
20✔
800
        this.consumers.set(identifier, consumer);
20✔
801
        return consumer;
20✔
802
    }
20✔
803

4✔
804
    /**
4✔
805
     * Scan the existing consumers on this EventStore and asynchronously invoke a callback with the parsed list.
4✔
806
     *
4✔
807
     * Each consumer entry provides `{ name, stream, identifier }` parsed from the on-disk filename.
4✔
808
     * Pass `autoStart = true` to eagerly open every discovered consumer and register it in
4✔
809
     * `this.consumers` so that it is immediately available for registry lookups.
4✔
810
     *
4✔
811
     * @param {function(error: Error|null, consumers: Array<{name: string, stream: string, identifier: string}>)} callback
4✔
812
     * @param {boolean} [autoStart=false] When true, calls `getConsumer(stream, identifier)` for each discovered consumer.
4✔
813
     */
4✔
814
    scanConsumers(callback, autoStart = false) {
4✔
815
        const consumersPath = path.join(this.storage.indexDirectory, 'consumers');
8✔
816
        if (!fs.existsSync(consumersPath)) {
8✔
817
            callback(null, []);
4✔
818
            return;
4✔
819
        }
4✔
820
        const regex = new RegExp(`^${this.storage.storageFile}\\.([^.]*\\..*)$`);
4✔
821
        const consumerNames = [];
4✔
822
        scanForFiles(consumersPath, regex, consumerNames.push.bind(consumerNames), /* istanbul ignore next */ (err) => {
4✔
823
            if (err) {
4!
824
                return callback(err, []);
×
825
            }
×
826
            const consumers = consumerNames.map(name => {
4✔
827
                const splitIndex = name.lastIndexOf('.');
8✔
828
                const indexName = name.slice(0, splitIndex);
8✔
829
                const identifier = name.slice(splitIndex + 1);
8✔
830
                const stream = parseStreamFromIndexName(indexName);
8✔
831
                return { name, stream, identifier };
8✔
832
            });
4✔
833
            if (autoStart) {
4!
NEW
834
                for (const { stream, identifier } of consumers) {
×
NEW
835
                    this.getConsumer(stream, identifier);
×
NEW
836
                }
×
NEW
837
            }
×
838
            callback(null, consumers);
4✔
839
        });
4✔
840
    }
8✔
841
}
4✔
842

4✔
843
function parseStreamFromIndexName(indexName) {
8✔
844
    if (indexName === '_all') {
8✔
845
        return '_all';
4✔
846
    }
4✔
847
    if (indexName.startsWith('stream-')) {
4✔
848
        return indexName.slice(7);
4✔
849
    }
4✔
NEW
850
    return indexName;
×
851
}
8✔
852

4✔
853
EventStore.Storage = Storage;
4✔
854
EventStore.Index = Index;
4✔
855

4✔
856
export default EventStore;
4✔
857
export { ExpectedVersion, OptimisticConcurrencyError, CommitCondition, LOCK_THROW, 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