event-storage 1.3.4 → 1.4.0

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.
@@ -1,97 +1,157 @@
1
1
  import EventStream from './EventStream.js';
2
- import { assert, kWayMerge } from './utils/util.js';
3
- import { normalizeRevision } from './utils/apiHelpers.js';
4
-
5
- /** Reusable sentinel used for missing or empty per-stream iterators. */
6
- const emptyIterator = Object.freeze({ next() { return { done: true }; } });
2
+ import {assert, iterate} from './utils/util.js';
3
+ import {intersect, normalizeSelector, union} from './utils/indexUtil.js';
4
+ import {normalizeRevision} from './utils/apiHelpers.js';
7
5
 
8
6
  /**
9
- * An event stream is a simple wrapper around an iterator over storage documents.
10
- * It implements a node readable stream interface.
7
+ * JoinEventStream is a virtual stream over one or multiple physical stream indexes.
8
+ *
9
+ * It is the canonical implementation behind `EventStore.fromStreams(...)` and supports
10
+ * nested selector algebra with alternating operators by depth:
11
+ *
12
+ * - depth 0 (top-level array): OR
13
+ * - depth 1: AND
14
+ * - depth 2: OR
15
+ * - ... alternating by depth parity
16
+ *
17
+ * Flat arrays (e.g. `['a', 'b']`) therefore keep the legacy join semantics (OR).
18
+ *
19
+ * @extends EventStream
11
20
  */
12
21
  class JoinEventStream extends EventStream {
13
22
 
14
23
  /**
15
- * @param {string} name The name of the stream.
16
- * @param {Array<string>} streams The name of the streams to join together.
17
- * @param {EventStore} eventStore The event store to get the stream from.
18
- * @param {number} [minRevision] The 1-based minimum revision to include in the events (inclusive).
19
- * @param {number} [maxRevision] The 1-based maximum revision to include in the events (inclusive).
20
- * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
21
- * @param {boolean} [raw=false] If true, emit NDJSON Buffers.
24
+ * @param {string} name The name of this virtual stream.
25
+ * @param {Array<string|Array>} selector Stream selector as flat or nested arrays.
26
+ * @param {EventStore} eventStore The event store instance.
27
+ * @param {number} [minRevision=1] Global minimum revision (inclusive).
28
+ * @param {number} [maxRevision=-1] Global maximum revision (inclusive).
29
+ * @param {function|object|null} [predicate] Optional matcher (same semantics as EventStream).
30
+ * @param {boolean} [raw=false] If true, emit NDJSON buffers.
22
31
  */
23
- constructor(name, streams, eventStore, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
32
+ constructor(name, selector, eventStore, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
24
33
  super(name, eventStore, minRevision, maxRevision, predicate, raw);
25
- assert(streams instanceof Array && streams.length > 0, `Invalid list of streams supplied to JoinStream ${name}.`);
34
+ assert(Array.isArray(selector) && selector.length > 0, `Invalid selector supplied to JoinEventStream ${name}.`);
26
35
 
36
+ this.eventStore = eventStore;
37
+ this.selector = normalizeSelector(selector);
27
38
  this.streamIndex = eventStore.storage.index;
28
- // Translate revisions to index numbers (1-based) and wrap around negatives
29
39
  this.minRevision = normalizeRevision(minRevision, eventStore.length);
30
40
  this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
31
- this.fetch = function() {
32
- return streams.map(streamName => {
33
- const streamIndex = eventStore.streams[streamName]?.index;
34
- if (!streamIndex || streamIndex.length === 0) {
35
- return emptyIterator;
36
- }
37
- const ascending = this.minRevision <= this.maxRevision;
38
- const from = streamIndex.find(this.minRevision, ascending);
39
- const until = streamIndex.find(this.maxRevision, !ascending);
40
- if (
41
- from === 0 ||
42
- until === 0 ||
43
- (ascending ? from > until : from < until)
44
- ) {
45
- // find() returns 0 when the requested revision is outside the stream's range
46
- // (e.g. minRevision > all entries, or maxRevision < all entries).
47
- return emptyIterator;
48
- }
49
- // Raw mode: get { buffer, time64, sequenceNumber } for binary-header ordering.
50
- // Object mode: storage deserializes for us and we order by metadata.commitId.
51
- return eventStore.storage.readRange(from, until, streamIndex, this.raw);
52
- });
53
- }
41
+ this.version = this.streamIndex.length;
42
+
43
+ this._combinedRanges = null;
44
+
45
+ this.fetch = () => this.iterateDocuments();
54
46
  this._iterator = null;
55
47
  }
56
48
 
49
+
57
50
  /**
58
- * @returns {Generator<object>}
51
+ * Resolve and cache the combined index-entry ranges for the full selector.
52
+ *
53
+ * @private
54
+ * @returns {Array<Array<number>>}
59
55
  */
60
- createMergedIterator() {
61
- const ascending = this.minRevision <= this.maxRevision;
62
- const raw = this.raw;
63
- return kWayMerge(
64
- this.fetch(),
65
- entry => raw ? entry.sequenceNumber : entry.metadata.commitId,
66
- ascending
67
- );
56
+ resolveCombinedRanges() {
57
+ if (this._combinedRanges) {
58
+ return this._combinedRanges;
59
+ }
60
+
61
+ this._combinedRanges = this.resolveSelectorRanges(this.selector);
62
+ return this._combinedRanges;
68
63
  }
69
64
 
70
65
  /**
71
- * Returns the next event in merge order.
66
+ * Resolve one selector node into a sorted index-entry range.
67
+ * Selector is already normalized and optimized from constructor, so we just traverse and collect ranges.
72
68
  *
73
- * In raw mode: returns `{ buffer, time64, sequenceNumber }` from the binary header — no JSON
74
- * deserialization. In object mode: returns a deserialized `{ stream, payload, metadata }` document
75
- * produced by the storage layer.
76
- * @returns {object|false} The next event, or `false` when the stream is exhausted.
69
+ * @private
70
+ * @param {string|Array<string|Array>} selectorNode
71
+ * @param {number} [depth=0]
72
+ * @returns {Array<Array<number>>}
77
73
  */
78
- next() {
79
- if (!this._iterator) {
80
- this._iterator = this.createMergedIterator();
74
+ resolveSelectorRanges(selectorNode, depth = 0) {
75
+ if (typeof selectorNode === 'string') {
76
+ const index = this.eventStore.streams[selectorNode]?.index;
77
+ return this.resolveIndexRange(index);
78
+ }
79
+
80
+ const childRanges = selectorNode.map(node => this.resolveSelectorRanges(node, depth + 1));
81
+ return depth % 2 === 0 ? union(...childRanges) : intersect(...childRanges);
82
+ }
83
+
84
+ /**
85
+ * Resolve one stream index to the global revision-bounded entry range.
86
+ *
87
+ * @private
88
+ * @param {object|undefined} index
89
+ * @returns {Array<Array<number>>}
90
+ */
91
+ resolveIndexRange(index) {
92
+ if (!index || index.length === 0) {
93
+ return [];
81
94
  }
82
- while (true) {
83
- const step = this._iterator.next();
84
- if (step.done) {
85
- return false;
86
- }
87
- const next = step.value;
88
95
 
89
- if (this.matchesPredicate(next)) {
90
- return next;
96
+ const ascending = this.minRevision <= this.maxRevision;
97
+ const from = index.find(this.minRevision, ascending);
98
+ const until = index.find(this.maxRevision, !ascending);
99
+ if (
100
+ from === 0 ||
101
+ until === 0 ||
102
+ (ascending ? from > until : from < until)
103
+ ) {
104
+ return [];
105
+ }
106
+
107
+ const rangeFrom = ascending ? from : until;
108
+ const rangeUntil = ascending ? until : from;
109
+ return index.range(rangeFrom, rangeUntil) || [];
110
+ }
111
+
112
+ /**
113
+ * Iterate matching index entries in requested direction.
114
+ *
115
+ * @private
116
+ * @returns {Generator<Array<number>>}
117
+ */
118
+ * iterateEntries() {
119
+ const entries = this.resolveCombinedRanges();
120
+ const forwards = this.minRevision <= this.maxRevision;
121
+ yield* iterate(entries, forwards);
122
+ }
123
+
124
+ /**
125
+ * Iterate storage documents lazily from combined index entries.
126
+ *
127
+ * @private
128
+ * @returns {Generator<object|{ buffer: Buffer, time64: number, sequenceNumber: number }>}
129
+ */
130
+ * iterateDocuments() {
131
+ const forwards = this.minRevision <= this.maxRevision;
132
+ for (const entry of this.iterateEntries()) {
133
+ const event = this.eventStore.storage.readFrom(
134
+ entry.partition,
135
+ entry.position,
136
+ entry.size,
137
+ this.raw,
138
+ !forwards
139
+ );
140
+ if (event) {
141
+ yield event;
91
142
  }
92
143
  }
93
144
  }
94
145
 
146
+ /**
147
+ * Reset fetch state and cached selector ranges when stream boundaries changed.
148
+ *
149
+ * @returns {JoinEventStream}
150
+ */
151
+ reset() {
152
+ this._combinedRanges = null;
153
+ return super.reset();
154
+ }
95
155
  }
96
156
 
97
157
  export default JoinEventStream;
@@ -414,21 +414,14 @@ class ReadablePartition extends events.EventEmitter {
414
414
  */
415
415
  findDocument(sequenceNumber, min = true) {
416
416
  const last = this.readLast();
417
- if (!last) {
418
- return null;
419
- }
420
-
421
- if (min && last.header.sequenceNumber < sequenceNumber) {
417
+ if (!last || (min && last.header.sequenceNumber < sequenceNumber)) {
422
418
  return null;
423
419
  }
424
420
 
425
421
  const [low, high] = binarySearch(
426
422
  sequenceNumber,
427
423
  this.size,
428
- (pos) => {
429
- const doc = this.readDocumentBefore(pos);
430
- return doc ? doc.header.sequenceNumber : Number.MIN_SAFE_INTEGER;
431
- }
424
+ (pos) => this.readDocumentBefore(pos)?.header.sequenceNumber ?? Number.MIN_SAFE_INTEGER
432
425
  );
433
426
 
434
427
  const position = this.findDocumentPositionBefore(min ? low : high);
@@ -503,24 +496,26 @@ class ReadablePartition extends events.EventEmitter {
503
496
  return;
504
497
  }
505
498
 
506
- const entry = { partition: this.id };
507
- const header = {};
499
+ const doc = {
500
+ entry: { partition: this.id },
501
+ header: {}
502
+ };
508
503
  const iterator = forwards
509
- ? this.readAll(found.position, header)
510
- : this.readAllBackwards(found.position + this.documentWriteSize(found.header.dataSize), header);
504
+ ? this.readAll(found.position, doc.header)
505
+ : this.readAllBackwards(found.position + this.documentWriteSize(found.header.dataSize), doc.header);
511
506
 
512
507
  for (const data of iterator) {
513
- if (header.sequenceNumber < lo || header.sequenceNumber > hi) {
508
+ if (doc.header.sequenceNumber < lo || doc.header.sequenceNumber > hi) {
514
509
  return;
515
510
  }
516
- entry.number = header.sequenceNumber;
517
- entry.position = header.position;
518
- entry.size = header.dataSize;
519
- yield { data, header, entry };
511
+ doc.entry.number = doc.header.sequenceNumber;
512
+ doc.entry.position = doc.header.position;
513
+ doc.entry.size = doc.header.dataSize;
514
+ doc.data = data;
515
+ yield doc;
520
516
  }
521
517
  }
522
518
 
523
-
524
519
  }
525
520
 
526
521
  export default ReadablePartition;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Determine whether a value is a DcbQuery object (plain object with an `items` property).
3
+ *
4
+ * @param {any} value
5
+ * @returns {boolean}
6
+ */
7
+ function isDcbQuery(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && 'items' in value;
9
+ }
10
+
11
+ /**
12
+ * Compile a {@link DcbQuery} into a selector-algebra array suitable for JoinEventStream.
13
+ *
14
+ * Each item in `query.items` produces one sub-selector (OR at the top level).
15
+ * Within an item, tags and types are combined with AND semantics; multiple types form a nested OR.
16
+ *
17
+ * @param {object} query - Object with a non-empty `items` array.
18
+ * @param {function(string): string} resolveType - Maps a type name to its stream name. Throws when
19
+ * `typeAccessor` is not configured.
20
+ * @param {function(string): string} resolveTag - Maps a tag value to its namespaced stream name
21
+ * (e.g. `'tags/' + tag`). Throws when `tagsAccessor` is not configured.
22
+ * @returns {Array} Selector-algebra array (non-empty).
23
+ * @throws {Error} When `items` is missing, null, or empty.
24
+ */
25
+ function compileDcbQuery(query, resolveType, resolveTag) {
26
+ if (!Array.isArray(query.items) || query.items.length === 0) {
27
+ throw new Error("DcbQuery.items must be a non-empty array. Use ['_all'] for an unconstrained read.");
28
+ }
29
+ return query.items.map(item => compileDcbItem(item, resolveType, resolveTag));
30
+ }
31
+
32
+ /**
33
+ * Compile a single DcbQuery item into a sub-selector.
34
+ *
35
+ * An item with no constraints (empty/missing `types` and `tags`) compiles to `'_all'`.
36
+ * Explicit `null` on `types` or `tags` throws — it is almost always a programming error.
37
+ *
38
+ * @param {object} item - QueryItem with optional `types: string[]` and `tags: string[]`.
39
+ * @param {function(string): string} resolveType
40
+ * @param {function(string): string} resolveTag
41
+ * @returns {string|Array} Sub-selector for this item.
42
+ * @throws {Error} When item is null/undefined, or when `types`/`tags` is non-null and non-array.
43
+ */
44
+ function compileDcbItem(item, resolveType, resolveTag) {
45
+ if (item === null || item === undefined) {
46
+ throw new Error('DcbQuery item must be an object, got ' + item);
47
+ }
48
+ if (item.tags !== undefined && !Array.isArray(item.tags)) {
49
+ throw new Error('DcbQuery item.tags must be an array or undefined, got ' + typeof item.tags);
50
+ }
51
+ if (item.types !== undefined && !Array.isArray(item.types)) {
52
+ throw new Error('DcbQuery item.types must be an array or undefined, got ' + typeof item.types);
53
+ }
54
+
55
+ const terms = [];
56
+
57
+ for (const tag of item.tags ?? []) {
58
+ terms.push(resolveTag(tag));
59
+ }
60
+ if (item.types?.length) {
61
+ const typeStreams = item.types.map(resolveType);
62
+ terms.push(typeStreams.length === 1 ? typeStreams[0] : typeStreams);
63
+ }
64
+
65
+ if (terms.length === 0) return '_all';
66
+ if (terms.length === 1 && typeof terms[0] === 'string') return terms[0];
67
+ return terms; // inner array = AND level
68
+ }
69
+
70
+ export {isDcbQuery, compileDcbQuery};
@@ -0,0 +1,225 @@
1
+ import { assert, compileAccessor } from './util.js';
2
+ import { buildMatcherFn } from './metadataUtil.js';
3
+
4
+ /**
5
+ * Merge two sorted index-entry ranges into one sorted union without duplicates.
6
+ * Assumes each range is sorted and contains no duplicates (by entry number).
7
+ *
8
+ * @param {Array<Array<number>>} left Sorted index-entry range.
9
+ * @param {Array<Array<number>>} right Sorted index-entry range.
10
+ * @returns {Array<Array<number>>} A new union range.
11
+ */
12
+ function unionTwoIndexEntryRanges(left, right) {
13
+ if (left.length === 0) {
14
+ return right.slice();
15
+ }
16
+ if (right.length === 0) {
17
+ return left.slice();
18
+ }
19
+
20
+ const merged = new Array(left.length + right.length);
21
+ let leftIndex = 0;
22
+ let rightIndex = 0;
23
+ let count = 0;
24
+
25
+ while (leftIndex < left.length && rightIndex < right.length) {
26
+ const leftEntry = left[leftIndex];
27
+ const rightEntry = right[rightIndex];
28
+ const leftNumber = leftEntry[0];
29
+ const rightNumber = rightEntry[0];
30
+
31
+ if (leftNumber < rightNumber) {
32
+ merged[count++] = leftEntry;
33
+ leftIndex++;
34
+ } else if (rightNumber < leftNumber) {
35
+ merged[count++] = rightEntry;
36
+ rightIndex++;
37
+ } else {
38
+ merged[count++] = leftEntry;
39
+ leftIndex++;
40
+ rightIndex++;
41
+ }
42
+ }
43
+
44
+ while (leftIndex < left.length) {
45
+ merged[count++] = left[leftIndex++];
46
+ }
47
+ while (rightIndex < right.length) {
48
+ merged[count++] = right[rightIndex++];
49
+ }
50
+
51
+ merged.length = count;
52
+ return merged;
53
+ }
54
+
55
+ /**
56
+ * Merge multiple sorted index-entry ranges into one sorted union without duplicates.
57
+ * Pairwise reduction via two-way merges, optimized for realistic data with moderate overlap.
58
+ * Assumes each range is sorted and contains no duplicates (by entry number).
59
+ *
60
+ * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
61
+ * @returns {Array<Array<number>>} A new union range.
62
+ */
63
+ function union(...ranges) {
64
+ if (ranges.length === 0) {
65
+ return [];
66
+ }
67
+ if (ranges.length === 1) {
68
+ return ranges[0].slice();
69
+ }
70
+
71
+ let merged = unionTwoIndexEntryRanges(ranges[0], ranges[1]);
72
+ for (let i = 2; i < ranges.length; i++) {
73
+ merged = unionTwoIndexEntryRanges(merged, ranges[i]);
74
+ }
75
+ return merged;
76
+ }
77
+
78
+ /**
79
+ * Intersect two sorted index-entry ranges by global number.
80
+ * Assumes each range is sorted and contains no duplicates (by entry number).
81
+ *
82
+ * @param {Array<Array<number>>} left Sorted index-entry range.
83
+ * @param {Array<Array<number>>} right Sorted index-entry range.
84
+ * @returns {Array<Array<number>>} A new intersection range.
85
+ */
86
+ function intersectTwoIndexEntryRanges(left, right) {
87
+ if (left.length === 0 || right.length === 0) {
88
+ return [];
89
+ }
90
+
91
+ const selected = new Array(Math.min(left.length, right.length));
92
+ let leftIndex = 0;
93
+ let rightIndex = 0;
94
+ let count = 0;
95
+
96
+ while (leftIndex < left.length && rightIndex < right.length) {
97
+ const leftEntry = left[leftIndex];
98
+ const rightEntry = right[rightIndex];
99
+ const leftNumber = leftEntry[0];
100
+ const rightNumber = rightEntry[0];
101
+
102
+ if (leftNumber < rightNumber) {
103
+ leftIndex++;
104
+ } else if (rightNumber < leftNumber) {
105
+ rightIndex++;
106
+ } else {
107
+ selected[count++] = leftEntry;
108
+ leftIndex++;
109
+ rightIndex++;
110
+ }
111
+ }
112
+
113
+ selected.length = count;
114
+ return selected;
115
+ }
116
+
117
+ /**
118
+ * Intersect multiple sorted index-entry ranges by global number.
119
+ * Pairwise reduction with size-order optimization, best for moderate to high overlap.
120
+ * Assumes each range is sorted and contains no duplicates (by entry number).
121
+ *
122
+ * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
123
+ * @returns {Array<Array<number>>} A new intersection range.
124
+ */
125
+ function intersect(...ranges) {
126
+ if (ranges.length === 0) {
127
+ return [];
128
+ }
129
+ if (ranges.length === 1) {
130
+ return ranges[0].slice();
131
+ }
132
+
133
+ ranges.sort((a, b) => a.length - b.length);
134
+ if (ranges[0].length === 0) {
135
+ return [];
136
+ }
137
+ let selected = intersectTwoIndexEntryRanges(ranges[0], ranges[1]);
138
+ for (let i = 2; i < ranges.length && selected.length > 0; i++) {
139
+ selected = intersectTwoIndexEntryRanges(selected, ranges[i]);
140
+ }
141
+ return selected;
142
+ }
143
+
144
+ /**
145
+ * Normalize selector shape for optimal evaluation.
146
+ *
147
+ * @param {string|Array<string|Array>} selector
148
+ * @param {number} [depth=0]
149
+ * @returns {string|Array<string|Array>}
150
+ */
151
+ function normalizeSelector(selector, depth = 0) {
152
+ if (typeof selector === 'string') {
153
+ assert(selector.length > 0, 'Stream names must be non-empty strings.');
154
+ return selector;
155
+ }
156
+
157
+ assert(Array.isArray(selector), 'Selector must be a string or an array.');
158
+ const normalized = selector.map(node => normalizeSelector(node, depth + 1));
159
+ return optimizeSelectorNode(normalized, depth);
160
+ }
161
+
162
+ /**
163
+ * Optimize one normalized selector node by depth-dependent rules.
164
+ *
165
+ * @param {Array<string|Array>} selectorNode
166
+ * @param {number} depth
167
+ * @returns {string|Array<string|Array>}
168
+ */
169
+ function optimizeSelectorNode(selectorNode, depth) {
170
+ if (selectorNode.length === 0) {
171
+ return [];
172
+ }
173
+ if (selectorNode.length === 1) {
174
+ const child = selectorNode[0];
175
+ // ['a'] -> 'a', [{ ... }] -> { ... }
176
+ if (!Array.isArray(child)) {
177
+ return selectorNode[0];
178
+ }
179
+ // [['a']] -> 'a', but never [['a']] -> ['a']
180
+ else if (child.length === 1) {
181
+ return child[0];
182
+ }
183
+ return selectorNode;
184
+ }
185
+ // ['a', 'a'] -> 'a'
186
+ if (selectorNode.every(node => node === selectorNode[0])) {
187
+ return selectorNode[0];
188
+ }
189
+
190
+ if (depth % 2 !== 0) {
191
+ return selectorNode.filter(node => node !== '_all');
192
+ }
193
+ if (selectorNode.some(node => node === '_all')) {
194
+ return '_all';
195
+ }
196
+ return selectorNode;
197
+ }
198
+
199
+ /**
200
+ * Pre-compile a stream source descriptor with a single curried matcher factory:
201
+ * `matcherFn(operator)(value) => objectMatcher`. The scalar and `$has` shapes are compiled
202
+ * once per source so callers can pick the correct one based on the event property type
203
+ * (scalar → no operator, array → `$has`) without rebuilding the closure per event.
204
+ *
205
+ * @param {string} sourcePath Dot-notation payload path (e.g. `'type'`, `'tags'`).
206
+ * @param {function(string): string} nameBuilder Maps each source value to a stream name.
207
+ * @returns {{path: string, accessor: function, nameBuilder: function, matcherFn: function(string|undefined): (function(any): object)}}
208
+ */
209
+ function buildStreamSource(sourcePath, nameBuilder) {
210
+ const scalarMatcher = buildMatcherFn(sourcePath);
211
+ const hasMatcher = buildMatcherFn(sourcePath, '$has');
212
+ return {
213
+ path: sourcePath,
214
+ accessor: compileAccessor(sourcePath),
215
+ nameBuilder,
216
+ matcherFn: (operator) => operator === '$has' ? hasMatcher : scalarMatcher
217
+ };
218
+ }
219
+
220
+ export {
221
+ union,
222
+ intersect,
223
+ normalizeSelector,
224
+ buildStreamSource
225
+ };