event-storage 1.3.5 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,6 +35,7 @@ npm install event-storage
35
35
  > **CommonJS / `require()` users:** version 1.0 is ESM-only. If your project uses `require()` and migrating to ESM is not an option, install the 0.x series (`npm install event-storage@0`) which is functionally equivalent and retains full CJS support.
36
36
 
37
37
 
38
+ ## Quick Start
38
39
 
39
40
  ```javascript
40
41
  import { EventStore } from 'event-storage';
@@ -55,14 +56,22 @@ eventstore.on('ready', () => {
55
56
  });
56
57
  ```
57
58
 
59
+ ## Common Usage at a Glance
60
+
61
+ - **Append events** with optimistic concurrency via `commit(stream, events, expectedVersion, cb)`.
62
+ - **Read streams** with `getEventStream()` and fluent options for revision/range/direction.
63
+ - **Run cross-stream queries** with `query(types, matcher)` and commit with its returned `condition` for DCB.
64
+ - **Build projections** with `fromStreams()` (joined streams) and `createStream()` for persistent filtered streams.
65
+ - **Consume reliably** with `createConsumer()` for durable at-least-once (or exactly-once with state) processing.
66
+
58
67
  ## Key Features
59
68
 
60
69
  | Feature | Summary |
61
70
  |---------|---------|
62
71
  | **Optimistic concurrency** | Pass `expectedVersion` to `commit()` to guarantee conflict-free writes. |
63
72
  | **Flexible stream reading** | Range queries, reverse iteration, and a fluent builder API. |
64
- | **Derived streams** | Filter or combine events into new read-only streams. |
65
- | **Object matchers** | Support nested equality, array values (OR semantics), and scalar operators like `$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`, while still benefiting from O(1) discriminant routing on writes. |
73
+ | **Joined and derived streams** | Combine any number of streams with a nested OR/AND selector tree into one globally-ordered virtual stream; filter events into reusable derived projection streams. |
74
+ | **Object matchers** | Support nested equality, array values (OR semantics), scalar operators (`$gt` / `$gte` / `$lt` / `$lte` / `$eq` / `$ne`), plus array-containment operators (`$has` / `$hasAny`), while still benefiting from O(1) discriminant routing on writes. |
66
75
  | **DCB** | Configure `typeAccessor` to have per-type stream indexes maintained automatically, and use `query()` / `Condition` for fine-grained, query-scoped optimistic concurrency (Dynamic Consistency Boundaries). |
67
76
  | **Stream categories** | Name streams `<category>-<id>` and query the whole category at once. |
68
77
  | **Durable consumers** | At-least-once (and exactly-once with `setState`) event delivery with automatic position tracking. |
@@ -75,6 +84,28 @@ eventstore.on('ready', () => {
75
84
 
76
85
  ---
77
86
 
87
+ ## Joining Streams
88
+
89
+ Merge events from multiple streams in global insertion order with `fromStreams`. The selector tree alternates: OR at even depths, AND at odd depths:
90
+
91
+ ```javascript
92
+ // OR: all events from either stream, in insertion order
93
+ const joined = eventstore.fromStreams('view', ['orders', 'payments']);
94
+
95
+ // AND: only events indexed in both streams (intersection)
96
+ const matched = eventstore.fromStreams('view', [['customer-42', 'OrderPlaced']]);
97
+
98
+ // Nested — (stream-a AND stream-b) OR (stream-c AND stream-d)
99
+ const complex = eventstore.fromStreams('view', [
100
+ ['stream-a', 'stream-b'],
101
+ ['stream-c', 'stream-d']
102
+ ]);
103
+ ```
104
+
105
+ See [Event Streams](https://node-event-storage.readthedocs.io/en/latest/streams/) for the full selector algebra, categories, and derived projection streams.
106
+
107
+ ---
108
+
78
109
  ## DCB Example
79
110
 
80
111
  ```javascript
@@ -90,11 +121,18 @@ if (!hasOpenOrder) {
90
121
 
91
122
  ## Object Matcher Syntax
92
123
 
93
- Object matchers support nested equality, array values, and scalar operators like `$gt`, `$gte`, `$lt`, `$lte`, `$eq`, and `$ne`.
124
+ Object matchers support nested equality, array values, scalar operators (`$gt`, `$gte`, `$lt`, `$lte`, `$eq`, `$ne`), and array-containment operators (`$has`, `$hasAny`).
125
+
126
+ - Scalar operators can be combined on one field (AND semantics), e.g. `{ $gte: 100, $lt: 1000 }`.
127
+ - `$has` / `$hasAny` target array-valued fields and must be used on their own for that field.
128
+
129
+ For hot paths, reuse the same matcher object reference across calls when possible (instead of recreating equivalent objects each time) so matcher compilation and cache-based optimization paths can be reused.
94
130
 
95
131
  ```javascript
96
132
  { payload: { type: ['OrderPlaced', 'OrderCancelled'] } }
97
133
  { payload: { amount: { $gte: 100, $lt: 1000 } } }
134
+ { payload: { tags: { $has: 'featured' } } }
135
+ { payload: { tags: { $hasAny: ['featured', 'priority'] } } }
98
136
  ```
99
137
 
100
138
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.3.5",
3
+ "version": "1.4.1",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -39,6 +39,7 @@
39
39
  "src/JoinEventStream*.js",
40
40
  "src/Partition*.js",
41
41
  "src/Storage*.js",
42
+ "src/FileHandlePool.js",
42
43
  "src/Watcher*.js",
43
44
  "src/Clock*.js",
44
45
  "src/Index/*.js",
@@ -63,10 +64,10 @@
63
64
  "mkdirp": "^3.0.1"
64
65
  },
65
66
  "devDependencies": {
66
- "c8": "^11.0.0",
67
+ "c8": "^12.0.0",
67
68
  "coveralls-next": "^6.0.1",
68
69
  "expect.js": "^0.3.1",
69
70
  "fs-extra": "^11.3.4",
70
- "mocha": "^11.7.5"
71
+ "mocha": "^12.0.0"
71
72
  }
72
73
  }
package/src/EventStore.js CHANGED
@@ -6,10 +6,11 @@ import events from 'events';
6
6
  import Storage, { ReadOnly as ReadOnlyStorage, LOCK_THROW, LOCK_RECLAIM } from './Storage.js';
7
7
  import Index from './Index.js';
8
8
  import Consumer from './Consumer.js';
9
- import { assert, getPropertyAtPath } from './utils/util.js';
9
+ import { assert } from './utils/util.js';
10
10
  import { ensureDirectory, resolvePath, scanForFiles } from './utils/fsUtil.js';
11
- import { buildTypeMatcherFn } from './utils/metadataUtil.js';
12
11
  import { fixCommitArgumentTypes, parseStreamFromIndexName, normalizePredicateRaw } from './utils/apiHelpers.js';
12
+ import { normalizeSelector, buildStreamSource } from "./utils/indexUtil.js";
13
+ import { isDcbQuery, compileDcbQuery } from "./utils/dcbUtil.js";
13
14
 
14
15
  const ExpectedVersion = {
15
16
  Any: -1,
@@ -23,29 +24,46 @@ const DEFAULT_MATCHER_PROPERTIES = ['stream', 'payload.type'];
23
24
  const STREAM_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_]*(?:[\/:@~+=\-#.][A-Za-z0-9_]+)*$/;
24
25
  const STORAGE_HOOK_EVENTS = new Set(['preCommit', 'preRead']);
25
26
 
27
+
26
28
  class OptimisticConcurrencyError extends Error {}
27
29
 
30
+ /**
31
+ * @typedef {string | SelectorNode[]} SelectorNode
32
+ */
33
+
34
+ /**
35
+ * @typedef {object} QueryItem
36
+ * @property {string[]} [types] Event type names to match (OR within the group).
37
+ * @property {string[]} [tags] Tag values to match (each tag is ANDed with the others and with types).
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} DcbQuery
42
+ * @property {QueryItem[]} items Non-empty array of query items combined with OR semantics at the top level.
43
+ */
44
+
28
45
  /**
29
46
  * An accept condition that captures the global event-log position at the time a {@link EventStore#query}
30
47
  * call was made. Pass it as the `expectedVersion` argument to {@link EventStore#commit} to enforce
31
48
  * DCB-style (Dynamic Consistency Boundary) optimistic concurrency: the commit is rejected only when
32
- * one or more events that match the original query (types + optional matcher) have been appended to
49
+ * one or more events that match the original query (selector + optional matcher) have been appended to
33
50
  * the store between the `query` call and the `commit` call.
34
51
  *
35
- * @property {string[]} types The event types included in the query.
52
+ * @property {SelectorNode[]|string} selector The normalized stream selector used in the query.
53
+ * @property {string[]} types Backwards-compatible alias for the leaf stream names of the selector.
36
54
  * @property {function(object, object): boolean|null} matcher An optional function `(payload, metadata) => boolean`
37
55
  * used to narrow the conflict check. When `null`, any new event of a listed type causes a conflict.
38
56
  * @property {number} noneMatchAfter The global store length (total event count) at the time the query was made.
39
57
  */
40
58
  class CommitCondition {
41
59
  /**
42
- * @param {string[]} types
60
+ * @param {SelectorNode[]|string} selector The (normalized) stream selector.
43
61
  * @param {(function(object, object): boolean)|object|null} [matcher]
44
- * @param {number} noneMatchAfter
45
- * @param {boolean} [raw=false]
62
+ * @param {number} noneMatchAfter
63
+ * @param {boolean} [raw=false]
46
64
  */
47
- constructor(types, matcher = null, noneMatchAfter, raw = false) {
48
- this.types = types;
65
+ constructor(selector, matcher = null, noneMatchAfter, raw = false) {
66
+ this.selector = selector;
49
67
  this.matcher = matcher;
50
68
  this.raw = raw;
51
69
  this.noneMatchAfter = noneMatchAfter;
@@ -66,9 +84,20 @@ class EventStore extends events.EventEmitter {
66
84
  * @param {string} [config.streamsDirectory] The directory where the streams should be stored. Default '{storageDirectory}/streams'.
67
85
  * @param {object} [config.storageConfig] Additional config options given to the storage backend. See `Storage`.
68
86
  * @param {boolean} [config.readOnly] If the storage should be mounted in read-only mode.
69
- * @param {string|function(object): string} [config.typeAccessor] Dot-notation path (e.g. `'type'`) or
70
- * function `(event) => string` identifying the event type. Enables type-based queries via
71
- * {@link EventStore#query} and ensures proper index routing for those queries.
87
+ * @param {Array<{path: string, nameBuilder: function(string): string}>} [config.streamSources] Generic
88
+ * stream-index definitions. Each entry specifies a dot-notation `path` into the event payload and a
89
+ * `nameBuilder(value) => streamName` function. On every {@link EventStore#commit} each entry is
90
+ * evaluated: scalar values are passed directly to `nameBuilder`; array values are iterated so each
91
+ * element produces its own stream. Non-string and empty values are skipped silently. The resulting
92
+ * stream names must satisfy the stream-name pattern. Each entry's `path` is automatically registered
93
+ * in `matcherProperties` for O(1) IndexMatcher routing.
94
+ * @param {string} [config.typeAccessor] Shorthand for a `streamSources` entry with `nameBuilder = v => v`.
95
+ * Dot-notation path to the event type field (e.g. `'type'`). Enables type-based
96
+ * {@link EventStore#query} selectors and {@link DcbQuery} `types` items.
97
+ * @param {string} [config.tagsAccessor] Shorthand for a `streamSources` entry with
98
+ * `nameBuilder = v => \`tags/${v}\``. Dot-notation path to an array field of tag values (e.g.
99
+ * `'tags'`). Enables tag-scoped {@link DcbQuery} `tags` items. Values are recommended to use `/`
100
+ * as a hierarchy separator (e.g. `'course/jdsj4'` → stream `tags/course/jdsj4`).
72
101
  * @param {object|function(string): object} [config.streamMetadata] A metadata object or a function `(streamName) => object`
73
102
  * that is called whenever a new stream partition is created. The returned object is stored once in the partition
74
103
  * file header and surfaced to `preCommit` / `preRead` hooks. Takes precedence only when
@@ -76,18 +105,32 @@ class EventStore extends events.EventEmitter {
76
105
  */
77
106
  constructor(storeName = 'eventstore', config = {}) {
78
107
  super();
108
+ this.setMaxListeners(0);
79
109
  if (typeof storeName !== 'string') {
80
110
  config = storeName;
81
111
  storeName = 'eventstore';
82
112
  }
83
113
 
84
- if (typeof config.typeAccessor === 'string' && config.typeAccessor) {
85
- const accessorPath = config.typeAccessor;
86
- this.typeAccessor = (event) => getPropertyAtPath(event, accessorPath);
87
- this.typeMatcherFn = buildTypeMatcherFn(accessorPath);
88
- } else {
89
- this.typeAccessor = typeof config.typeAccessor === 'function' ? config.typeAccessor : null;
90
- this.typeMatcherFn = null;
114
+ this.streamSources = [];
115
+ this.typeSource = null;
116
+ this.tagsSource = null;
117
+
118
+ if (config.typeAccessor) {
119
+ assert(typeof config.typeAccessor === 'string', 'typeAccessor must be a dot-notation string path (e.g. \'type\').');
120
+ this.typeSource = buildStreamSource(config.typeAccessor, (v) => v);
121
+ this.streamSources.push(this.typeSource);
122
+ }
123
+
124
+ if (config.tagsAccessor) {
125
+ assert(typeof config.tagsAccessor === 'string', 'tagsAccessor must be a dot-notation string path (e.g. \'tags\').');
126
+ this.tagsSource = buildStreamSource(config.tagsAccessor, (v) => `tags/${v}`);
127
+ this.streamSources.push(this.tagsSource);
128
+ }
129
+
130
+ for (const { path, nameBuilder } of config.streamSources ?? []) {
131
+ assert(typeof path === 'string' && path, 'Each streamSources entry must have a non-empty string path.');
132
+ assert(typeof nameBuilder === 'function', 'Each streamSources entry must have a nameBuilder function.');
133
+ this.streamSources.push(buildStreamSource(path, nameBuilder));
91
134
  }
92
135
 
93
136
  this.storageDirectory = resolvePath(config.storageDirectory || /* istanbul ignore next */ './data');
@@ -99,11 +142,10 @@ class EventStore extends events.EventEmitter {
99
142
  };
100
143
  const storageConfig = Object.assign(defaults, config.storageConfig);
101
144
 
102
- // When typeAccessor is a string path, ensure the corresponding full document path
103
- // (payload.<path>) is present in matcherProperties so the IndexMatcher discriminant
104
- // table can route type-stream lookups in O(1) on every write.
105
- if (this.typeMatcherFn) {
106
- const fullPath = `payload.${config.typeAccessor}`;
145
+ // Register each source's payload path in matcherProperties so the IndexMatcher
146
+ // discriminant table can route stream lookups in O(1) on every write.
147
+ for (const source of this.streamSources) {
148
+ const fullPath = `payload.${source.path}`;
107
149
  const currentProps = storageConfig.matcherProperties || DEFAULT_MATCHER_PROPERTIES;
108
150
  if (!currentProps.includes(fullPath)) {
109
151
  storageConfig.matcherProperties = [...currentProps, fullPath];
@@ -398,14 +440,13 @@ class EventStore extends events.EventEmitter {
398
440
  checkCondition(condition) {
399
441
  if (this.storage.length <= condition.noneMatchAfter) return; // no new events since condition was obtained
400
442
 
401
- const existingTypes = condition.types.filter(t => t in this.streams);
402
- if (existingTypes.length === 0) return;
443
+ const selector = condition.selector || condition.types;
403
444
 
404
445
  // Only events after condition.noneMatchAfter can be conflicts.
405
446
  // Pass the original matcher and raw flag so the stream filters at the source.
406
447
  const stream = this.fromStreams(
407
- '_check_' + condition.types.join('_'),
408
- existingTypes,
448
+ '_check_' + Date.now(),
449
+ selector,
409
450
  condition.noneMatchAfter + 1,
410
451
  -1,
411
452
  condition.matcher,
@@ -416,57 +457,30 @@ class EventStore extends events.EventEmitter {
416
457
  }
417
458
 
418
459
  /**
419
- * Ensure a dedicated type stream exists for each event's type, creating it if needed.
420
- * Must be called before the entity stream is created to guarantee correct index routing.
460
+ * Ensure a dedicated stream exists for each indexed property value across all stream sources.
461
+ * Must be called before the entity stream write so those indexes are never incomplete.
421
462
  *
422
463
  * @private
423
- * @param {Array<object>} events The events to process.
424
- */
425
- ensureTypeStreams(events) {
426
- if (!this.typeAccessor) return;
427
- for (const event of events) {
428
- const type = this.resolveValidatedTypeStreamName(event);
429
- if (type && !(type in this.streams)) {
430
- const matcher = this.typeMatcherFn
431
- ? this.typeMatcherFn(type)
432
- : (doc) => this.typeAccessor(doc.payload) === type;
433
- this.createEventStream(type, matcher, false);
434
- }
435
- }
436
- }
437
-
438
- /**
439
- * @private
440
- * @param {object} event
441
- * @returns {string|null}
442
- */
443
- resolveValidatedTypeStreamName(event) {
444
- const type = this.typeAccessor(event);
445
- if (type === undefined || type === null || type === '') {
446
- return null;
447
- }
448
- assert(typeof type === 'string', 'typeAccessor must return a string.');
449
- assert(STREAM_NAME_PATTERN.test(type), `typeAccessor must return a valid stream name. Got: "${type}"`);
450
- return type;
451
- }
452
-
453
- /**
454
- * @private
455
- * @param {string[]} types
456
- * @returns {string[]}
457
- */
458
- getExistingQueryTypes(types) {
459
- const queryTypes = [];
460
- for (const type of types) {
461
- if (type in this.streams) {
462
- queryTypes.push(type);
463
- continue;
464
- }
465
- if (!this.typeAccessor) {
466
- 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.`);
464
+ * @param {Array<object>} events
465
+ */
466
+ ensureStreams(events) {
467
+ if (this.streamSources.length === 0) return;
468
+ for (const { accessor, nameBuilder, matcherFn, path } of this.streamSources) {
469
+ for (const event of events) {
470
+ const raw = accessor(event);
471
+ const isArrayValue = Array.isArray(raw);
472
+ const values = isArrayValue ? raw : (raw != null && raw !== '' ? [raw] : []);
473
+ const buildMatcher = matcherFn(isArrayValue ? '$has' : undefined);
474
+ for (const value of values) {
475
+ if (typeof value !== 'string' || !value) continue;
476
+ const streamName = nameBuilder(value);
477
+ assert(STREAM_NAME_PATTERN.test(streamName), `Invalid stream name "${streamName}" derived from path "${path}".`);
478
+ if (!(streamName in this.streams)) {
479
+ this.createEventStream(streamName, buildMatcher(value), false);
480
+ }
481
+ }
467
482
  }
468
483
  }
469
- return queryTypes;
470
484
  }
471
485
 
472
486
  /**
@@ -504,9 +518,8 @@ class EventStore extends events.EventEmitter {
504
518
  expectedVersion = ExpectedVersion.Any;
505
519
  }
506
520
 
507
- // When typeAccessor is configured, ensure a dedicated type stream exists for each event
508
- // before the entity stream write so the type stream index is never incomplete.
509
- this.ensureTypeStreams(events);
521
+ // Ensure all indexed streams exist before the entity stream write so those indexes are never incomplete.
522
+ this.ensureStreams(events);
510
523
 
511
524
  if (!(streamName in this.streams)) {
512
525
  this.createEventStream(streamName, { stream: streamName }, false);
@@ -569,15 +582,12 @@ class EventStore extends events.EventEmitter {
569
582
  * belongs to one of the listed types and (when `matcher` is provided) also satisfies
570
583
  * `matcher(payload, metadata)`. Events written before the `query` call are never treated as conflicts.
571
584
  *
572
- * **Behaviour when a type stream does not exist:**
573
- * - Without `typeAccessor` configured: throws an error, because the store cannot guarantee that no
574
- * events of that type exist (the stream was never created). Create the stream explicitly first,
575
- * or configure `typeAccessor` to have streams created automatically on commit.
576
- * - With `typeAccessor` configured: treats the missing stream as empty (0-length). The stream will
577
- * be created automatically the first time an event of that type is committed.
585
+ * Missing stream references are treated as empty sets. In OR groups they have no effect;
586
+ * in AND groups they collapse that branch to an empty result.
578
587
  *
579
588
  * @api
580
- * @param {string[]} types A non-empty array of event-type names to query.
589
+ * @param {SelectorNode[]|object} selectorOrDcbQuery A non-empty selector array, or a {@link DcbQuery} object
590
+ * with an `items` property (compiled automatically to selector algebra).
581
591
  * @param {function|object|null} [matcher] Optional matcher used for stream pre-filtering.
582
592
  * In object mode, function predicates receive `(payload, metadata)`.
583
593
  * @param {number} [minRevision=1] The 1-based minimum global revision to include in the returned stream (inclusive).
@@ -585,17 +595,52 @@ class EventStore extends events.EventEmitter {
585
595
  * @returns {{ condition: CommitCondition, stream: EventStream }} An object with:
586
596
  * - `condition` — the {@link CommitCondition} to pass to {@link EventStore#commit}.
587
597
  * - `stream` — a read-only event stream containing all matching events.
588
- * @throws {Error} if `types` is not a non-empty array.
589
- * @throws {Error} if `typeAccessor` is not configured and any of the listed type streams do not exist.
590
- */
591
- query(types, matcher = null, minRevision = 1, raw = false) {
592
- assert(Array.isArray(types) && types.length > 0, 'Must specify a non-empty array of event types for query.');
593
- const queryTypes = this.getExistingQueryTypes(types);
594
- const condition = new CommitCondition(types, matcher, this.storage.length, raw);
595
- const stream = this.fromStreams('_query_' + types.join('_'), queryTypes, minRevision, -1, matcher, raw);
598
+ * Nested selector example (items=OR, per-item=AND, inner=OR):
599
+ * `[[courseTag, ['CourseCreated', 'CourseCapacityChanged']], [studentTag, ['StudentCreated']]]`
600
+ * @throws {Error} if `selector` is not a non-empty array.
601
+ */
602
+ query(selectorOrDcbQuery, matcher = null, minRevision = 1, raw = false) {
603
+ let selector = selectorOrDcbQuery;
604
+ if (isDcbQuery(selectorOrDcbQuery)) {
605
+ selector = compileDcbQuery(
606
+ selectorOrDcbQuery,
607
+ (type) => this.resolveTypeStream(type),
608
+ (tag) => this.resolveTagStream(tag)
609
+ );
610
+ }
611
+ assert(Array.isArray(selector) && selector.length > 0, 'Must specify a non-empty array of stream selectors for query.');
612
+ // Normalize the selector once here; both the condition and the stream use
613
+ // the normalized form. Wrap a string result (single-stream reduction) in
614
+ // an array so fromStreams always receives an array.
615
+ const normalized = normalizeSelector(selector);
616
+ const querySelector = Array.isArray(normalized) ? normalized : [normalized];
617
+ const condition = new CommitCondition(querySelector, matcher, this.storage.length, raw);
618
+ const stream = this.fromStreams('_query_' + Date.now(), querySelector, minRevision, -1, matcher, raw);
596
619
  return { stream, condition };
597
620
  }
598
621
 
622
+ /**
623
+ * @private
624
+ * @param {string} type
625
+ * @returns {string} Stream name for the given event type.
626
+ * @throws {Error} When typeAccessor is not configured.
627
+ */
628
+ resolveTypeStream(type) {
629
+ assert(this.typeSource !== null, 'DcbQuery references "types" but typeAccessor not configured.');
630
+ return this.typeSource.nameBuilder(type);
631
+ }
632
+
633
+ /**
634
+ * @private
635
+ * @param {string} tag
636
+ * @returns {string} Stream name for the given tag value.
637
+ * @throws {Error} When tagsAccessor is not configured.
638
+ */
639
+ resolveTagStream(tag) {
640
+ assert(this.tagsSource !== null, 'DcbQuery references "tags" but tagsAccessor not configured.');
641
+ return this.tagsSource.nameBuilder(tag);
642
+ }
643
+
599
644
  /**
600
645
  * Get an event stream for the given stream name within the revision boundaries.
601
646
  *
@@ -632,29 +677,23 @@ class EventStore extends events.EventEmitter {
632
677
  }
633
678
 
634
679
  /**
635
- * Create a virtual event stream from existing streams by joining them.
680
+ * Create a virtual event stream from existing streams.
681
+ *
682
+ * Uses selector algebra with alternating operator levels (depth 0 = OR, depth 1 = AND, ...).
636
683
  *
637
684
  * @param {string} streamName The (transient) name of the joined stream.
638
- * @param {Array<string>} streamNames An array of the stream names to join.
685
+ * @param {Array<string|Array<string>>} streamNames Stream selector input.
639
686
  * @param {number} [minRevision=1] The 1-based minimum revision to include in the events (inclusive).
640
687
  * @param {number} [maxRevision=-1] The 1-based maximum revision to include in the events (inclusive).
641
688
  * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
642
689
  * @param {boolean} [raw=false] If true, return NDJSON buffers.
643
- * @returns {EventStream} The joined event stream.
644
- * @throws {Error} if any of the streams doesn't exist.
690
+ * @returns {EventStream|JoinEventStream}
691
+ * @throws {Error} if any selected stream doesn't exist.
645
692
  */
646
693
  fromStreams(streamName, streamNames, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
647
694
  ({ predicate, raw } = normalizePredicateRaw(predicate, raw));
648
695
  assert(streamNames instanceof Array, 'Must specify an array of stream names.');
649
696
 
650
- if (streamNames.length === 0) {
651
- return new EventStream(streamName, this);
652
- }
653
-
654
- for (let stream of streamNames) {
655
- assert(stream in this.streams, `Stream "${stream}" does not exist.`);
656
- }
657
-
658
697
  return new JoinEventStream(streamName, streamNames, this, minRevision, maxRevision, predicate, raw);
659
698
  }
660
699
 
@@ -0,0 +1,105 @@
1
+ import fs from 'fs';
2
+
3
+ /**
4
+ * LRU pool for file descriptors shared across multiple file-backed objects.
5
+ *
6
+ * Targets are expected to expose `fileName` and `fileMode` and may implement
7
+ * `onBeforeClose(fd, evicted)` to flush state before their descriptor closes.
8
+ */
9
+ class FileHandlePool {
10
+
11
+ /**
12
+ * @param {number} [maxOpen=0] Maximum number of simultaneously open handles. 0 disables eviction.
13
+ */
14
+ constructor(maxOpen = 0) {
15
+ this.maxOpen = maxOpen;
16
+ this.handles = new Map();
17
+ }
18
+
19
+ /**
20
+ * @param {object} target
21
+ * @returns {number}
22
+ */
23
+ get(target) {
24
+ const handle = this.handles.get(target);
25
+ if (handle) {
26
+ this.touch(target);
27
+ return handle.fd;
28
+ }
29
+
30
+ this.evictLeastRecentlyUsedIfNeeded(target);
31
+ const fd = fs.openSync(target.fileName, target.fileMode);
32
+ this.handles.set(target, { fd });
33
+ return fd;
34
+ }
35
+
36
+ /**
37
+ * @param {object} target
38
+ * @returns {boolean}
39
+ */
40
+ has(target) {
41
+ return this.handles.has(target);
42
+ }
43
+
44
+ /**
45
+ * @param {object} target
46
+ * @param {boolean} [evicted=true]
47
+ * @returns {boolean}
48
+ */
49
+ evict(target, evicted = true) {
50
+ const handle = this.handles.get(target);
51
+ if (!handle) {
52
+ return false;
53
+ }
54
+ try {
55
+ target.onBeforeClose?.(handle.fd, evicted);
56
+ } finally {
57
+ this.handles.delete(target);
58
+ fs.closeSync(handle.fd);
59
+ }
60
+ return true;
61
+ }
62
+
63
+ /**
64
+ * @param {object} target
65
+ * @returns {void}
66
+ */
67
+ touch(target) {
68
+ const handle = this.handles.get(target);
69
+ if (!handle) {
70
+ return;
71
+ }
72
+ this.handles.delete(target);
73
+ this.handles.set(target, handle);
74
+ }
75
+
76
+ /**
77
+ * Evict the least-recently-used descriptor before opening another one.
78
+ *
79
+ * @param {object} target
80
+ */
81
+ evictLeastRecentlyUsedIfNeeded(target) {
82
+ if (this.maxOpen <= 0) {
83
+ return;
84
+ }
85
+ this.handles.delete(target);
86
+ if (this.handles.size < this.maxOpen) {
87
+ return;
88
+ }
89
+ const lruTarget = this.handles.keys().next().value;
90
+ if (!lruTarget) {
91
+ return;
92
+ }
93
+ this.evict(lruTarget);
94
+ }
95
+
96
+ /**
97
+ * @returns {number}
98
+ */
99
+ get openCount() {
100
+ return this.handles.size;
101
+ }
102
+
103
+ }
104
+
105
+ export default FileHandlePool;
@@ -34,7 +34,7 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
34
34
  */
35
35
  onChange(filename) {
36
36
  /* c8 ignore next 3 */
37
- if (!this.fd) {
37
+ if (!this.isOpen()) {
38
38
  return;
39
39
  }
40
40
  const prevLength = this.data.length;