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.
@@ -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
+ };
@@ -9,7 +9,8 @@ import {
9
9
  compareNumeric
10
10
  } from './jsonUtil.js';
11
11
 
12
- const compiledOperatorMatcherCache = new WeakMap();
12
+ const compiledMatcherCache = new WeakMap();
13
+ const rawBufferMatcherCache = new WeakMap();
13
14
 
14
15
  /**
15
16
  * @param {any} value Value to classify.
@@ -37,24 +38,71 @@ function isOperatorObject(obj) {
37
38
  }
38
39
 
39
40
  /**
40
- * Dispatch between array (OR), operator object, nested object, and scalar equality matching
41
- * so callers don't need to know the shape of `matcherValue`.
41
+ * @typedef {object|function(object):boolean} Matcher
42
+ */
43
+
44
+ /**
45
+ * Pre-compile an object matcher into an array of per-property closure checks so the hot path
46
+ * avoids repeated `Object.getOwnPropertyNames` allocation and per-property type dispatch.
42
47
  *
43
- * @param {any} documentValue Value from the document.
44
- * @param {any} matcherValue Value from the matcher definition.
45
- * @returns {boolean} True when both values match under matcher semantics.
48
+ * @param {object} matcher Plain object matcher to compile.
49
+ * @returns {function(any): boolean} Compiled predicate over documents.
46
50
  */
47
- function propertyMatchesValue(documentValue, matcherValue) {
48
- if (isObject(matcherValue)) {
49
- if (Array.isArray(matcherValue)) {
50
- return matcherValue.includes(documentValue);
51
- } else if (isOperatorObject(matcherValue)) {
52
- const operatorChecks = getCompiledOperatorChecks(matcherValue);
53
- return matchesCompiledOperators(documentValue, operatorChecks);
51
+ function compileMatcher(matcher) {
52
+ const checks = [];
53
+ for (const prop of Object.getOwnPropertyNames(matcher)) {
54
+ const matcherValue = matcher[prop];
55
+ if (isObject(matcherValue)) {
56
+ if (Array.isArray(matcherValue)) {
57
+ checks.push(doc => matcherValue.includes(doc[prop]));
58
+ } else if (isOperatorObject(matcherValue)) {
59
+ const operatorChecks = buildOperatorChecks(matcherValue);
60
+ checks.push(doc => matchesCompiledOperators(doc[prop], operatorChecks));
61
+ } else {
62
+ const nestedCheck = getCompiledMatcher(matcherValue);
63
+ checks.push(doc => nestedCheck(doc[prop]));
64
+ }
65
+ } else if (typeof matcherValue !== 'undefined') {
66
+ checks.push(doc => doc[prop] === matcherValue);
54
67
  }
55
- return matches(documentValue, matcherValue);
56
68
  }
57
- return typeof matcherValue === 'undefined' || documentValue === matcherValue;
69
+ if (checks.length === 0) {
70
+ return () => true;
71
+ }
72
+ return function matchesCompiled(doc) {
73
+ // The undefined guard is needed for nested matchers where doc[prop] may be undefined.
74
+ if (typeof doc === 'undefined') return false;
75
+ for (const check of checks) {
76
+ if (!check(doc)) return false;
77
+ }
78
+ return true;
79
+ };
80
+ }
81
+
82
+ /**
83
+ * Return a cached compiled predicate for `matcher`, compiling and caching on first access.
84
+ *
85
+ * @param {object} matcher Plain object matcher.
86
+ * @returns {function(any): boolean} Cached or freshly compiled predicate.
87
+ */
88
+ function getCompiledMatcher(matcher) {
89
+ const cached = compiledMatcherCache.get(matcher);
90
+ if (cached) return cached;
91
+ const compiled = compileMatcher(matcher);
92
+ compiledMatcherCache.set(matcher, compiled);
93
+ return compiled;
94
+ }
95
+
96
+ /**
97
+ * @param {object} document The document to check against the matcher.
98
+ * @param {Matcher} matcher An object of properties and their values that need to match in the object or a function that checks if the document matches.
99
+ * @returns {boolean} True if the document matches the matcher or false otherwise.
100
+ */
101
+ function matches(document, matcher) {
102
+ if (typeof document === 'undefined') return false;
103
+ if (typeof matcher === 'undefined') return true;
104
+ if (typeof matcher === 'function') return matcher(document);
105
+ return getCompiledMatcher(matcher)(document);
58
106
  }
59
107
 
60
108
  /**
@@ -86,6 +134,12 @@ function buildOperatorChecks(operatorObj) {
86
134
  case '$ne':
87
135
  checks.push(value => value !== expectedValue);
88
136
  break;
137
+ case '$has':
138
+ checks.push(value => Array.isArray(value) && value.includes(expectedValue));
139
+ break;
140
+ case '$hasAny':
141
+ checks.push(value => Array.isArray(value) && expectedValue.some(v => value.includes(v)));
142
+ break;
89
143
  default:
90
144
  throw new TypeError(`Unknown operator: ${operator}`);
91
145
  }
@@ -93,23 +147,6 @@ function buildOperatorChecks(operatorObj) {
93
147
  return checks;
94
148
  }
95
149
 
96
- /**
97
- * Return cached compiled checks for `operatorObj`, compiling and caching on first access.
98
- * Using WeakMap keeps operator objects GC-eligible and avoids mutating user-supplied objects.
99
- *
100
- * @param {object} operatorObj Object containing operator/value pairs.
101
- * @returns {Array<function(any): boolean>} Cached or newly compiled operator checks.
102
- */
103
- function getCompiledOperatorChecks(operatorObj) {
104
- const cachedChecks = compiledOperatorMatcherCache.get(operatorObj);
105
- if (cachedChecks) {
106
- return cachedChecks;
107
- }
108
- const checks = buildOperatorChecks(operatorObj);
109
- compiledOperatorMatcherCache.set(operatorObj, checks);
110
- return checks;
111
- }
112
-
113
150
  /**
114
151
  * @param {any} documentValue Parsed scalar value from the document.
115
152
  * @param {Array<function(any): boolean>} checks Compiled operator checks.
@@ -159,29 +196,6 @@ const createHmac = secret => string => {
159
196
  return hmac.digest('hex');
160
197
  };
161
198
 
162
- /**
163
- * @typedef {object|function(object):boolean} Matcher
164
- */
165
-
166
- /**
167
- * @param {object} document The document to check against the matcher.
168
- * @param {Matcher} matcher An object of properties and their values that need to match in the object or a function that checks if the document matches.
169
- * @returns {boolean} True if the document matches the matcher or false otherwise.
170
- */
171
- function matches(document, matcher) {
172
- if (typeof document === 'undefined') return false;
173
- if (typeof matcher === 'undefined') return true;
174
-
175
- if (typeof matcher === 'function') return matcher(document);
176
-
177
- for (let prop of Object.getOwnPropertyNames(matcher)) {
178
- if (!propertyMatchesValue(document[prop], matcher[prop])) {
179
- return false;
180
- }
181
- }
182
- return true;
183
- }
184
-
185
199
  /**
186
200
  * @param {Matcher} matcher The matcher object or function that should be serialized.
187
201
  * @param {function(string)} hmac A function that calculates a HMAC of the given string.
@@ -218,16 +232,22 @@ function buildMatcherFromMetadata(matcherMetadata, hmac) {
218
232
  }
219
233
 
220
234
  /**
221
- * Builds a factory function that, given a type string, returns an object matcher for
222
- * documents whose payload contains that type at the given dot-notation path.
235
+ * Builds a factory function that, given a scalar value, returns an object matcher targeting
236
+ * the given dot-notation payload path. Without an operator (or with `'$eq'`) the leaf is a
237
+ * plain scalar equality check; with an operator like `'$has'` the leaf is wrapped as
238
+ * `{[operator]: value}` so array-containment or other single-operator checks are produced.
223
239
  *
224
- * @param {string} payloadPath Dot-notation path relative to the event payload (e.g. `'type'`, `'meta.kind'`).
225
- * @returns {function(string): object} A function `(typeValue) => objectMatcher`.
240
+ * @param {string} payloadPath Dot-notation path relative to the event payload (e.g. `'type'`, `'tags'`).
241
+ * @param {string} [operator] Optional matcher operator (e.g. `'$has'`). Missing or `'$eq'` produces a scalar matcher.
242
+ * @returns {function(any): object} A function `(value) => objectMatcher`.
226
243
  */
227
- function buildTypeMatcherFn(payloadPath) {
244
+ function buildMatcherFn(payloadPath, operator) {
228
245
  const parts = payloadPath.split('.');
229
- return function (typeValue) {
230
- let obj = typeValue;
246
+ const wrapLeaf = (!operator || operator === '$eq')
247
+ ? (value) => value
248
+ : (value) => ({[operator]: value});
249
+ return function (value) {
250
+ let obj = wrapLeaf(value);
231
251
  for (let i = parts.length - 1; i >= 0; i--) {
232
252
  obj = {[parts[i]]: obj};
233
253
  }
@@ -245,6 +265,12 @@ function buildTypeMatcherFn(payloadPath) {
245
265
  */
246
266
  function buildRawBufferMatcher(matcher = {}, options = {}) {
247
267
  assert(isPlainObject(matcher), 'Matcher must be an object.', TypeError);
268
+
269
+ const cached = rawBufferMatcherCache.get(matcher);
270
+ if (cached) {
271
+ return cached;
272
+ }
273
+
248
274
  const enableOperatorBufferMatcher = options.enableOperatorBufferMatcher !== false;
249
275
 
250
276
  const root = buildMatcherTree(matcher, enableOperatorBufferMatcher);
@@ -253,7 +279,7 @@ function buildRawBufferMatcher(matcher = {}, options = {}) {
253
279
  return () => true;
254
280
  }
255
281
 
256
- return function matchesRawBuffer(buffer) {
282
+ const matchesRawBuffer = function (buffer) {
257
283
  if (!isOpeningObject(buffer[0])) {
258
284
  return false;
259
285
  }
@@ -262,6 +288,8 @@ function buildRawBufferMatcher(matcher = {}, options = {}) {
262
288
  }
263
289
  return matchesNode(buffer, 1, root);
264
290
  };
291
+ rawBufferMatcherCache.set(matcher, matchesRawBuffer);
292
+ return matchesRawBuffer;
265
293
  }
266
294
 
267
295
  /**
@@ -325,6 +353,22 @@ function buildMatcherTreeChild(key, value) {
325
353
  child.pattern = keyPrefix;
326
354
  const nePattern = [Buffer.from(JSON.stringify(value['$ne']), 'utf8')];
327
355
  child.matches = (buffer, valueStart) => !matchesAnyValuePattern(buffer, valueStart, nePattern);
356
+ } else if ('$has' in value && Object.keys(value).length === 1) {
357
+ // A lone $has is a same-level array-containment check. The pattern locates the array
358
+ // opener (`"key":[`) and the follow-up scans array elements for the serialized scalar
359
+ // at the array's element level (skipping nested objects/arrays).
360
+ child.isKeyPattern = true;
361
+ child.pattern = Buffer.concat([keyPrefix, Buffer.from('[', 'utf8')]);
362
+ const valuePattern = Buffer.from(JSON.stringify(value['$has']), 'utf8');
363
+ child.matches = (buffer, valueStart) => indexOfSameLevel(buffer, valuePattern, valueStart) !== -1;
364
+ } else if ('$hasAny' in value && Object.keys(value).length === 1) {
365
+ // A lone $hasAny is an any-of array-containment check: matches when the document
366
+ // array contains at least one of the expected values.
367
+ child.isKeyPattern = true;
368
+ child.pattern = Buffer.concat([keyPrefix, Buffer.from('[', 'utf8')]);
369
+ const hasAnyPatterns = value['$hasAny'].map(v => Buffer.from(JSON.stringify(v), 'utf8'));
370
+ child.matches = (buffer, valueStart) =>
371
+ hasAnyPatterns.some(vp => indexOfSameLevel(buffer, vp, valueStart) !== -1);
328
372
  } else if (isOperatorObject(value)) {
329
373
  child.isKeyPattern = true;
330
374
  child.pattern = keyPrefix;
@@ -502,7 +546,7 @@ function buildOperatorBufferMatcher(operatorObj) {
502
546
  }
503
547
 
504
548
  // Non-numeric expected value: use generic operator checks.
505
- const operatorChecks = getCompiledOperatorChecks(operatorObj);
549
+ const operatorChecks = buildOperatorChecks(operatorObj);
506
550
  return (buffer, startOffset) => matchesOperatorInBuffer(buffer, startOffset, operatorChecks);
507
551
  }
508
552
 
@@ -512,6 +556,6 @@ export {
512
556
  buildMetadataHeader,
513
557
  buildMetadataForMatcher,
514
558
  buildMatcherFromMetadata,
515
- buildTypeMatcherFn,
559
+ buildMatcherFn,
516
560
  buildRawBufferMatcher
517
561
  };
package/src/utils/util.js CHANGED
@@ -192,6 +192,28 @@ function getPropertyAtPath(obj, dotPath) {
192
192
  return current;
193
193
  }
194
194
 
195
+ /**
196
+ * Compiles a dot-notation path string into a reusable accessor function,
197
+ * avoiding repeated string splitting and iteration on every call.
198
+ *
199
+ * @param {string} dotPath
200
+ * @returns {function(object): *}
201
+ */
202
+ function compileAccessor(dotPath) {
203
+ const parts = dotPath.split('.');
204
+ if (parts.length === 1) {
205
+ return (obj) => obj == null ? undefined : obj[dotPath];
206
+ }
207
+ return (obj) => {
208
+ let cur = obj;
209
+ for (const part of parts) {
210
+ if (cur == null || typeof cur !== 'object') return undefined;
211
+ cur = cur[part];
212
+ }
213
+ return cur;
214
+ };
215
+ }
216
+
195
217
  export {
196
218
  assert,
197
219
  assertEqual,
@@ -201,5 +223,6 @@ export {
201
223
  binarySearch,
202
224
  alignTo,
203
225
  kWayMerge,
204
- getPropertyAtPath
226
+ getPropertyAtPath,
227
+ compileAccessor
205
228
  };
@@ -1,149 +0,0 @@
1
- /**
2
- * A fixed-capacity registry of partitions with LRU eviction of open file handles.
3
- *
4
- * All partitions are stored by their numeric id and may be queried at any time.
5
- * The pool additionally tracks which partitions currently have an open file descriptor
6
- * in LRU (least-recently-used) order. When the pool is asked to open a partition and
7
- * doing so would exceed the configured cap, the least-recently-used open partition is
8
- * closed first to stay within the limit.
9
- *
10
- * Setting the cap to 0 disables eviction: all partitions are allowed to remain open
11
- * simultaneously, which matches the uncapped behaviour of the original implementation.
12
- */
13
- class PartitionPool {
14
-
15
- /**
16
- * @param {number} [maxOpen=0] Maximum number of simultaneously open partition file
17
- * handles. 0 disables the limit (no eviction).
18
- */
19
- constructor(maxOpen = 0) {
20
- this.maxOpen = maxOpen;
21
- /** Registry of all known partitions keyed by id. */
22
- this.registry = Object.create(null);
23
- /**
24
- * Insertion-order map used for LRU tracking of open file handles.
25
- * Key = partition id, value = true.
26
- * Oldest (least-recently-used) entry is first; newest (most-recently-used) is last.
27
- */
28
- this.handles = new Map();
29
- }
30
-
31
- /**
32
- * Register a partition under the given id.
33
- *
34
- * @param {number|string} id
35
- * @param {object} partition
36
- */
37
- add(id, partition) {
38
- this.registry[id] = partition;
39
- }
40
-
41
- /**
42
- * Retrieve a registered partition without opening it.
43
- *
44
- * @param {number|string} id
45
- * @returns {object|undefined}
46
- */
47
- get(id) {
48
- return this.registry[id];
49
- }
50
-
51
- /**
52
- * Check whether a partition with the given id is registered in the pool.
53
- *
54
- * @param {number|string} id
55
- * @returns {boolean}
56
- */
57
- has(id) {
58
- return id in this.registry;
59
- }
60
-
61
- /**
62
- * Open the partition with the given id, applying LRU eviction if necessary.
63
- *
64
- * If the partition is not yet open and adding it would exceed `maxOpen`, the
65
- * least-recently-used open partition is closed first. Stale entries (partitions
66
- * that were closed externally) are discarded from the LRU map as they are
67
- * encountered; if all tracked entries turn out to be stale the loop exits without
68
- * closing any partition — the handle count stays temporarily inflated (bounded by
69
- * the number of external closes since the last `open()` call) but correctness is
70
- * preserved.
71
- *
72
- * @param {number|string} id
73
- * @returns {object} The opened partition.
74
- */
75
- open(id) {
76
- const partition = this.registry[id];
77
-
78
- if (this.maxOpen > 0) {
79
- // Remove id first — this may already bring the handle count below the cap.
80
- this.handles.delete(id);
81
- if (this.handles.size >= this.maxOpen) {
82
- for (const [lruId] of this.handles) {
83
- this.handles.delete(lruId);
84
- const lruPartition = this.registry[lruId];
85
- if (lruPartition && lruPartition.isOpen()) {
86
- lruPartition.close();
87
- break;
88
- }
89
- }
90
- }
91
- // (Re-)add id at the MRU end of the map.
92
- this.handles.set(id, true);
93
- }
94
-
95
- partition.open();
96
- return partition;
97
- }
98
-
99
- /**
100
- * Invoke `callback` for every registered partition.
101
- *
102
- * @param {function(object): void} callback
103
- */
104
- forEach(callback) {
105
- for (const id of Object.keys(this.registry)) {
106
- callback(this.registry[id]);
107
- }
108
- }
109
-
110
- /**
111
- * Yield every registered partition object.
112
- *
113
- * @returns {Generator<object>}
114
- */
115
- *values() {
116
- for (const id of Object.keys(this.registry)) {
117
- yield this.registry[id];
118
- }
119
- }
120
-
121
- /**
122
- * The total number of registered partitions.
123
- * @returns {number}
124
- */
125
- get count() {
126
- return Object.keys(this.registry).length;
127
- }
128
-
129
- /**
130
- * The number of open partition file handles currently tracked by the pool.
131
- * @returns {number}
132
- */
133
- get openCount() {
134
- return this.handles.size;
135
- }
136
-
137
- /**
138
- * Reset the open-handle tracking without closing any partitions.
139
- *
140
- * Call this after externally closing all partitions (e.g. after
141
- * `checkTornWrites`) to keep the pool's LRU state consistent with reality.
142
- */
143
- clearOpenHandles() {
144
- this.handles.clear();
145
- }
146
-
147
- }
148
-
149
- export default PartitionPool;