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.
@@ -1,6 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import events from 'events';
3
3
  import Entry, { assertValidEntryClass } from '../IndexEntry.js';
4
+ import FileHandlePool from '../FileHandlePool.js';
4
5
  import { assert, wrapAndCheck, binarySearch } from '../utils/util.js';
5
6
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
6
7
  import { resolvePath } from "../utils/fsUtil.js";
@@ -42,9 +43,11 @@ class ReadableIndex extends events.EventEmitter {
42
43
  * @param {number} [options.writeBufferSize] The number of bytes to use for the write buffer. Default 4096.
43
44
  * @param {number} [options.flushDelay] How many ms to delay the write buffer flush to optimize throughput. Default 100.
44
45
  * @param {object} [options.metadata] An object containing the metadata information for this index. Will be written on initial creation and checked on subsequent openings.
46
+ * @param {object} [options.fileHandlePool] Shared file-handle pool used to reopen evicted handles on demand.
45
47
  */
46
48
  constructor(name = '.index', options = {}) {
47
49
  super();
50
+ this.setMaxListeners(0);
48
51
  ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
49
52
  let defaults = {
50
53
  dataDirectory: '.',
@@ -65,8 +68,9 @@ class ReadableIndex extends events.EventEmitter {
65
68
  initialize(options) {
66
69
  /* @type Array<Entry> */
67
70
  this.data = [];
68
- this.fd = null;
71
+ this.opened = false;
69
72
  this.fileMode = 'r';
73
+ this.fileHandlePool = options.fileHandlePool || new FileHandlePool();
70
74
  this.EntryClass = options.EntryClass;
71
75
  this.dataDirectory = options.dataDirectory;
72
76
  this.fileName = resolvePath(options.dataDirectory, this.name);
@@ -109,7 +113,21 @@ class ReadableIndex extends events.EventEmitter {
109
113
  * @returns {boolean}
110
114
  */
111
115
  isOpen() {
112
- return !!this.fd;
116
+ return this.opened;
117
+ }
118
+
119
+ /**
120
+ * @returns {boolean}
121
+ */
122
+ hasFileHandle() {
123
+ return this.fileHandlePool.has(this);
124
+ }
125
+
126
+ /**
127
+ * @returns {number}
128
+ */
129
+ getFileHandle() {
130
+ return this.fileHandlePool.get(this);
113
131
  }
114
132
 
115
133
  /**
@@ -120,7 +138,7 @@ class ReadableIndex extends events.EventEmitter {
120
138
  * @throws {Error} If the file is corrupt or can not be read correctly.
121
139
  */
122
140
  checkFile() {
123
- const stat = fs.fstatSync(this.fd);
141
+ const stat = fs.fstatSync(this.getFileHandle());
124
142
  if (stat.size === 0) {
125
143
  return -1;
126
144
  }
@@ -145,11 +163,10 @@ class ReadableIndex extends events.EventEmitter {
145
163
  * @throws {Error} if the file can not be opened.
146
164
  */
147
165
  open() {
148
- if (this.fd) {
166
+ if (this.opened) {
149
167
  return false;
150
168
  }
151
-
152
- this.fd = fs.openSync(this.fileName, this.fileMode);
169
+ this.opened = this.getFileHandle() !== null;
153
170
 
154
171
  this.readUntil = -1;
155
172
 
@@ -209,8 +226,9 @@ class ReadableIndex extends events.EventEmitter {
209
226
  */
210
227
  readMetadata() {
211
228
  if (this.headerSize > 0) return this.headerSize;
229
+ const fd = this.getFileHandle();
212
230
  const headerBuffer = Buffer.allocUnsafe(8 + 4);
213
- fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
231
+ fs.readSync(fd, headerBuffer, 0, 8 + 4, 0);
214
232
  const headerMagic = headerBuffer.toString('utf8', 0, 8);
215
233
 
216
234
  assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), 'Invalid file header.');
@@ -221,7 +239,7 @@ class ReadableIndex extends events.EventEmitter {
221
239
 
222
240
  const metadataBuffer = Buffer.allocUnsafe(metadataSize - 1);
223
241
  metadataBuffer.fill(" ");
224
- fs.readSync(this.fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
242
+ fs.readSync(fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
225
243
  const metadata = metadataBuffer.toString('utf8').trim();
226
244
  this.verifyAndSetMetadata(metadata);
227
245
  this.headerSize = 8 + 4 + metadataSize;
@@ -236,10 +254,8 @@ class ReadableIndex extends events.EventEmitter {
236
254
  this.data = [];
237
255
  this.readUntil = -1;
238
256
  this.readBuffer.fill(0);
239
- if (this.fd) {
240
- fs.closeSync(this.fd);
241
- this.fd = null;
242
- }
257
+ this.fileHandlePool.evict(this, false);
258
+ this.opened = false;
243
259
  }
244
260
 
245
261
  /**
@@ -253,7 +269,8 @@ class ReadableIndex extends events.EventEmitter {
253
269
  read(index) {
254
270
  index = Number(index) - 1;
255
271
 
256
- fs.readSync(this.fd, this.readBuffer, 0, this.EntryClass.size, this.headerSize + index * this.EntryClass.size);
272
+ const fd = this.getFileHandle();
273
+ fs.readSync(fd, this.readBuffer, 0, this.EntryClass.size, this.headerSize + index * this.EntryClass.size);
257
274
  if (index === this.readUntil + 1) {
258
275
  this.readUntil++;
259
276
  }
@@ -286,7 +303,8 @@ class ReadableIndex extends events.EventEmitter {
286
303
  const readBuffer = bufferSize <= this.readBuffer.byteLength
287
304
  ? this.readBuffer
288
305
  : Buffer.allocUnsafe(bufferSize);
289
- let readSize = fs.readSync(this.fd, readBuffer, 0, bufferSize, this.headerSize + readFrom * this.EntryClass.size);
306
+ const fd = this.getFileHandle();
307
+ let readSize = fs.readSync(fd, readBuffer, 0, bufferSize, this.headerSize + readFrom * this.EntryClass.size);
290
308
  let index = 0;
291
309
  while (index < amount && readSize > 0) {
292
310
  this.data[index + readFrom] = this.EntryClass.fromBuffer(readBuffer, index * this.EntryClass.size);
@@ -89,7 +89,7 @@ class WritableIndex extends ReadableIndex {
89
89
  * @throws {Error} if the file can not be opened.
90
90
  */
91
91
  open() {
92
- if (this.fd) {
92
+ if (this.opened) {
93
93
  return false;
94
94
  }
95
95
  this.writeBufferCursor = 0;
@@ -108,20 +108,21 @@ class WritableIndex extends ReadableIndex {
108
108
  this.metadata = {entryClass: this.EntryClass.name, entrySize: this.EntryClass.size};
109
109
  }
110
110
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
111
- fs.writeSync(this.fd, metadataBuffer, 0, metadataBuffer.byteLength, 0);
111
+ fs.writeSync(this.getFileHandle(), metadataBuffer, 0, metadataBuffer.byteLength, 0);
112
112
  this.headerSize = metadataBuffer.byteLength;
113
113
  }
114
114
 
115
115
  /**
116
- * Close the index and release the file handle.
117
- * @api
116
+ * Flush pending buffered writes before the pool closes the descriptor.
117
+ *
118
+ * @param {number} fd
118
119
  */
119
- close() {
120
- if (this.fd) {
121
- this.flush();
122
- fs.fdatasyncSync(this.fd);
120
+ onBeforeClose(fd) {
121
+ if (!this.writeBuffer) {
122
+ return;
123
123
  }
124
- super.close();
124
+ this.flush();
125
+ fs.fdatasyncSync(fd);
125
126
  }
126
127
 
127
128
  /**
@@ -139,7 +140,7 @@ class WritableIndex extends ReadableIndex {
139
140
  * @returns {boolean} If a flush actually was executed.
140
141
  */
141
142
  flush() {
142
- if (!this.fd) {
143
+ if (!this.isOpen()) {
143
144
  return false;
144
145
  }
145
146
  if (this.flushTimeout) {
@@ -150,9 +151,10 @@ class WritableIndex extends ReadableIndex {
150
151
  return false;
151
152
  }
152
153
 
153
- fs.writeSync(this.fd, this.writeBuffer, 0, this.writeBufferCursor);
154
+ const fd = this.getFileHandle();
155
+ fs.writeSync(fd, this.writeBuffer, 0, this.writeBufferCursor);
154
156
  if (this.syncOnFlush) {
155
- fs.fsyncSync(this.fd);
157
+ fs.fsyncSync(fd);
156
158
  }
157
159
 
158
160
  this.writeBufferCursor = 0;
@@ -215,9 +217,10 @@ class WritableIndex extends ReadableIndex {
215
217
  * @param {number} after The index entry number to truncate after.
216
218
  */
217
219
  truncate(after) {
218
- if (!this.fd) {
220
+ if (!this.isOpen()) {
219
221
  return;
220
222
  }
223
+ this.getFileHandle();
221
224
  if (after < 0) {
222
225
  after = 0;
223
226
  }
@@ -1,6 +1,38 @@
1
1
  import { getPropertyAtPath } from './utils/util.js';
2
2
  import { matches } from './utils/metadataUtil.js';
3
3
 
4
+ /**
5
+ * @param {any} value Candidate matcher value at a discriminant path.
6
+ * @param {string} operator Operator key to check for (e.g. `'$has'`).
7
+ * @returns {boolean} True when `value` is a plain object with exactly one key equal to `operator`
8
+ * and the operator value is non-null and non-undefined.
9
+ */
10
+ function isLoneOperator(value, operator) {
11
+ if (Array.isArray(value)) return false;
12
+ const keys = Object.keys(value);
13
+ if (keys.length !== 1 || keys[0] !== operator) return false;
14
+ const operand = value[operator];
15
+ return operand !== null && operand !== undefined;
16
+ }
17
+
18
+ /**
19
+ * @param {any} value Candidate matcher value at a discriminant path.
20
+ * @returns {boolean} True when `value` is `{ $has: scalar }` (lone $has with a non-object value).
21
+ */
22
+ function isLoneHasScalar(value) {
23
+ return isLoneOperator(value, '$has') && typeof value.$has !== 'object';
24
+ }
25
+
26
+ /**
27
+ * @param {any} value Candidate matcher value at a discriminant path.
28
+ * @returns {boolean} True when `value` is `{ $hasAny: [scalar, ...] }` (lone $hasAny with a non-empty scalar array).
29
+ */
30
+ function isLoneHasAnyArray(value) {
31
+ return isLoneOperator(value, '$hasAny') &&
32
+ Array.isArray(value.$hasAny) && value.$hasAny.length > 0 &&
33
+ value.$hasAny.every(v => v !== null && v !== undefined && typeof v !== 'object');
34
+ }
35
+
4
36
  /**
5
37
  * @typedef {object|function(object):boolean} Matcher
6
38
  */
@@ -143,7 +175,30 @@ class IndexMatcher {
143
175
 
144
176
  for (const propPath of this.properties) {
145
177
  const docValue = getPropertyAtPath(document, propPath);
146
- if (docValue === undefined || docValue === null || typeof docValue === 'object') {
178
+ if (docValue === undefined || docValue === null) {
179
+ continue;
180
+ }
181
+
182
+ if (Array.isArray(docValue)) {
183
+ // Multi-value document property: each array element is a potential discriminant.
184
+ // A dedup set prevents calling iterationHandler twice when two elements map to
185
+ // the same index (e.g. duplicate tags, or a single index registered for both).
186
+ const called = new Set();
187
+ for (const item of docValue) {
188
+ if (item === null || item === undefined || typeof item === 'object') continue;
189
+ const indexSet = this.table.get(propPath)?.get(String(item));
190
+ if (!indexSet) continue;
191
+ for (const indexName of indexSet) {
192
+ if (!called.has(indexName) && matches(document, this.matchers.get(indexName))) {
193
+ called.add(indexName);
194
+ iterationHandler(indexName);
195
+ }
196
+ }
197
+ }
198
+ continue;
199
+ }
200
+
201
+ if (typeof docValue === 'object') {
147
202
  continue;
148
203
  }
149
204
 
@@ -195,6 +250,16 @@ class IndexMatcher {
195
250
  value.every(v => v !== null && v !== undefined && typeof v !== 'object')) {
196
251
  return { propPath, values: value.map(String) };
197
252
  }
253
+ // Lone $has operator: array-containment matcher (e.g. tag streams). Treat the
254
+ // has-value as the discriminant so array-valued documents route in O(1).
255
+ if (isLoneHasScalar(value)) {
256
+ return { propPath, values: [String(value.$has)] };
257
+ }
258
+ // Lone $hasAny: register one matcher under each expected value so any of them
259
+ // can trigger O(1) routing when the document array contains that value.
260
+ if (isLoneHasAnyArray(value)) {
261
+ return { propPath, values: value.$hasAny.map(String) };
262
+ }
198
263
  }
199
264
  }
200
265
  return null;
@@ -1,115 +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
- * In raw mode `storage.readFrom` returns a `buffer` that is a transient view into a shared read/write
10
- * buffer, only valid until the next read on that partition. The k-way merge holds the head of every
11
- * per-stream iterator at once, so advancing one stream would otherwise clobber another stream's pending
12
- * head when they read from the same partition. Copy each raw buffer into its own memory as it is produced
13
- * so every held head stays valid across reads.
7
+ * JoinEventStream is a virtual stream over one or multiple physical stream indexes.
14
8
  *
15
- * @param {Iterator<{ buffer: Buffer }>} iterator
16
- * @returns {Generator<{ buffer: Buffer }>}
17
- */
18
- function* detachRawBuffers(iterator) {
19
- for (const entry of iterator) {
20
- entry.buffer = Buffer.from(entry.buffer);
21
- yield entry;
22
- }
23
- }
24
-
25
- /**
26
- * An event stream is a simple wrapper around an iterator over storage documents.
27
- * It implements a node readable stream interface.
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
28
20
  */
29
21
  class JoinEventStream extends EventStream {
30
22
 
31
23
  /**
32
- * @param {string} name The name of the stream.
33
- * @param {Array<string>} streams The name of the streams to join together.
34
- * @param {EventStore} eventStore The event store to get the stream from.
35
- * @param {number} [minRevision] The 1-based minimum revision to include in the events (inclusive).
36
- * @param {number} [maxRevision] The 1-based maximum revision to include in the events (inclusive).
37
- * @param {function|object|null} [predicate] Optional matcher (see {@link EventStream}).
38
- * @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.
39
31
  */
40
- 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) {
41
33
  super(name, eventStore, minRevision, maxRevision, predicate, raw);
42
- 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}.`);
43
35
 
36
+ this.eventStore = eventStore;
37
+ this.selector = normalizeSelector(selector);
44
38
  this.streamIndex = eventStore.storage.index;
45
- // Translate revisions to index numbers (1-based) and wrap around negatives
46
39
  this.minRevision = normalizeRevision(minRevision, eventStore.length);
47
40
  this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
48
- this.fetch = function() {
49
- return streams.map(streamName => {
50
- const streamIndex = eventStore.streams[streamName]?.index;
51
- if (!streamIndex || streamIndex.length === 0) {
52
- return emptyIterator;
53
- }
54
- const ascending = this.minRevision <= this.maxRevision;
55
- const from = streamIndex.find(this.minRevision, ascending);
56
- const until = streamIndex.find(this.maxRevision, !ascending);
57
- if (
58
- from === 0 ||
59
- until === 0 ||
60
- (ascending ? from > until : from < until)
61
- ) {
62
- // find() returns 0 when the requested revision is outside the stream's range
63
- // (e.g. minRevision > all entries, or maxRevision < all entries).
64
- return emptyIterator;
65
- }
66
- // Raw mode: get { buffer, time64, sequenceNumber } for binary-header ordering.
67
- // Object mode: storage deserializes for us and we order by metadata.commitId.
68
- const range = eventStore.storage.readRange(from, until, streamIndex, this.raw);
69
- return this.raw ? detachRawBuffers(range) : range;
70
- });
71
- }
41
+ this.version = this.streamIndex.length;
42
+
43
+ this._combinedRanges = null;
44
+
45
+ this.fetch = () => this.iterateDocuments();
72
46
  this._iterator = null;
73
47
  }
74
48
 
49
+
75
50
  /**
76
- * @returns {Generator<object>}
51
+ * Resolve and cache the combined index-entry ranges for the full selector.
52
+ *
53
+ * @private
54
+ * @returns {Array<Array<number>>}
77
55
  */
78
- createMergedIterator() {
79
- const ascending = this.minRevision <= this.maxRevision;
80
- const raw = this.raw;
81
- return kWayMerge(
82
- this.fetch(),
83
- entry => raw ? entry.sequenceNumber : entry.metadata.commitId,
84
- ascending
85
- );
56
+ resolveCombinedRanges() {
57
+ if (this._combinedRanges) {
58
+ return this._combinedRanges;
59
+ }
60
+
61
+ this._combinedRanges = this.resolveSelectorRanges(this.selector);
62
+ return this._combinedRanges;
86
63
  }
87
64
 
88
65
  /**
89
- * 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.
90
68
  *
91
- * In raw mode: returns `{ buffer, time64, sequenceNumber }` from the binary header — no JSON
92
- * deserialization. In object mode: returns a deserialized `{ stream, payload, metadata }` document
93
- * produced by the storage layer.
94
- * @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>>}
95
73
  */
96
- next() {
97
- if (!this._iterator) {
98
- 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 [];
99
94
  }
100
- while (true) {
101
- const step = this._iterator.next();
102
- if (step.done) {
103
- return false;
104
- }
105
- const next = step.value;
106
95
 
107
- if (this.matchesPredicate(next)) {
108
- 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;
109
142
  }
110
143
  }
111
144
  }
112
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
+ }
113
155
  }
114
156
 
115
157
  export default JoinEventStream;
@@ -19,7 +19,7 @@ class ReadOnlyPartition extends WatchesFile(ReadablePartition) {
19
19
  */
20
20
  onChange(filename) {
21
21
  /* c8 ignore next 3 */
22
- if (!this.fd) {
22
+ if (!this.isOpen()) {
23
23
  return;
24
24
  }
25
25
  const prevSize = this.size;