event-storage 1.4.0 → 1.5.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,144 +1,90 @@
1
1
  import { assert, compileAccessor } from './util.js';
2
2
  import { buildMatcherFn } from './metadataUtil.js';
3
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).
4
+ /*
5
+ * `union` and `intersect` combine two lazy ranges of index entries, as returned by `index.range()`, into a new
6
+ * lazy range in the same direction. A range may reuse its entry object, so an entry is only read before the range
7
+ * that yielded it is advanced.
7
8
  *
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.
9
+ * Calling `next(number)` on a range skips ahead to the first entry that does not come before `number`.
10
+ * `intersect` uses that to jump over long stretches without a match instead of stepping through them.
11
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
12
 
51
- merged.length = count;
52
- return merged;
13
+ /**
14
+ * @param {boolean} forwards
15
+ * @returns {function(number, number): boolean} Whether the first number comes before the second in that direction.
16
+ */
17
+ function comesBefore(forwards) {
18
+ return forwards ? (left, right) => left < right : (left, right) => left > right;
53
19
  }
54
20
 
55
21
  /**
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).
22
+ * Continue yielding the entries of a range, passing skip targets through.
59
23
  *
60
- * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
61
- * @returns {Array<Array<number>>} A new union range.
24
+ * @param {IteratorResult} current The current, not yet yielded result of the range.
25
+ * @param {Generator} range
62
26
  */
63
- function union(...ranges) {
64
- if (ranges.length === 0) {
65
- return [];
66
- }
67
- if (ranges.length === 1) {
68
- return ranges[0].slice();
27
+ function* drain(current, range) {
28
+ while (!current.done) {
29
+ current = range.next(yield current.value);
69
30
  }
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
31
  }
77
32
 
78
33
  /**
79
- * Intersect two sorted index-entry ranges by global number.
80
- * Assumes each range is sorted and contains no duplicates (by entry number).
34
+ * Merge two ranges into one ordered range without duplicates.
81
35
  *
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.
36
+ * @param {Generator} left
37
+ * @param {Generator} right
38
+ * @param {boolean} [forwards=true]
39
+ * @returns {Generator}
85
40
  */
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++;
41
+ function* union(left, right, forwards = true) {
42
+ const before = comesBefore(forwards);
43
+ let a = left.next();
44
+ let b = right.next();
45
+ while (!a.done && !b.done) {
46
+ const leftNumber = a.value.number;
47
+ const rightNumber = b.value.number;
48
+ const leftFirst = !before(rightNumber, leftNumber);
49
+ const rightFirst = !before(leftNumber, rightNumber);
50
+ const target = yield leftFirst ? a.value : b.value;
51
+ // Advance the side that was yielded, and also the other side when a skip target leaves it behind.
52
+ if (leftFirst || (target !== undefined && before(leftNumber, target))) {
53
+ a = left.next(target);
54
+ }
55
+ if (rightFirst || (target !== undefined && before(rightNumber, target))) {
56
+ b = right.next(target);
110
57
  }
111
58
  }
112
-
113
- selected.length = count;
114
- return selected;
59
+ yield* drain(a, left);
60
+ yield* drain(b, right);
115
61
  }
116
62
 
117
63
  /**
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).
64
+ * Yield the entries that are contained in both ranges.
121
65
  *
122
- * @param {...Array<Array<number>>} ranges Sorted index-entry ranges.
123
- * @returns {Array<Array<number>>} A new intersection range.
66
+ * @param {Generator} left
67
+ * @param {Generator} right
68
+ * @param {boolean} [forwards=true]
69
+ * @returns {Generator}
124
70
  */
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]);
71
+ function* intersect(left, right, forwards = true) {
72
+ const before = comesBefore(forwards);
73
+ let a = left.next();
74
+ let b = right.next();
75
+ while (!a.done && !b.done) {
76
+ const leftNumber = a.value.number;
77
+ const rightNumber = b.value.number;
78
+ if (leftNumber === rightNumber) {
79
+ const target = yield a.value;
80
+ a = left.next(target);
81
+ b = right.next(target);
82
+ } else if (before(leftNumber, rightNumber)) {
83
+ a = left.next(rightNumber);
84
+ } else {
85
+ b = right.next(leftNumber);
86
+ }
140
87
  }
141
- return selected;
142
88
  }
143
89
 
144
90
  /**
@@ -196,6 +142,28 @@ function optimizeSelectorNode(selectorNode, depth) {
196
142
  return selectorNode;
197
143
  }
198
144
 
145
+ /**
146
+ * Remove streams from a selector by treating them as empty: an OR level drops them, an AND level that contains one
147
+ * matches nothing anymore and is dropped as a whole. The result therefore never matches more than the input.
148
+ * `'_all'` is never removed.
149
+ *
150
+ * @param {string|Array} selector A selector in the algebra of `fromStreams()` (depth 0 = OR).
151
+ * @param {Set<string>} names The stream names to treat as empty.
152
+ * @param {number} [depth=0]
153
+ * @returns {string|Array|null} The reduced selector, or `null` if nothing is left.
154
+ */
155
+ function excludeStreams(selector, names, depth = 0) {
156
+ if (typeof selector === 'string') {
157
+ return names.has(selector) && selector !== '_all' ? null : selector;
158
+ }
159
+ const children = selector.map(node => excludeStreams(node, names, depth + 1));
160
+ if (depth % 2 === 0) {
161
+ const remaining = children.filter(node => node !== null);
162
+ return remaining.length > 0 ? remaining : null;
163
+ }
164
+ return children.includes(null) ? null : children;
165
+ }
166
+
199
167
  /**
200
168
  * Pre-compile a stream source descriptor with a single curried matcher factory:
201
169
  * `matcherFn(operator)(value) => objectMatcher`. The scalar and `$has` shapes are compiled
@@ -218,6 +186,7 @@ function buildStreamSource(sourcePath, nameBuilder) {
218
186
  }
219
187
 
220
188
  export {
189
+ excludeStreams,
221
190
  union,
222
191
  intersect,
223
192
  normalizeSelector,
@@ -11,6 +11,7 @@ import {
11
11
 
12
12
  const compiledMatcherCache = new WeakMap();
13
13
  const rawBufferMatcherCache = new WeakMap();
14
+ const ORDERING_OPERATORS = new Set(['$gt', '$gte', '$lt', '$lte', '$eq', '$ne']);
14
15
 
15
16
  /**
16
17
  * @param {any} value Value to classify.
@@ -140,6 +141,10 @@ function buildOperatorChecks(operatorObj) {
140
141
  case '$hasAny':
141
142
  checks.push(value => Array.isArray(value) && expectedValue.some(v => value.includes(v)));
142
143
  break;
144
+ case '$startsWith':
145
+ assert(typeof expectedValue === 'string', '$startsWith expects a string prefix.', TypeError);
146
+ checks.push(value => typeof value === 'string' && value.startsWith(expectedValue));
147
+ break;
143
148
  default:
144
149
  throw new TypeError(`Unknown operator: ${operator}`);
145
150
  }
@@ -369,6 +374,11 @@ function buildMatcherTreeChild(key, value) {
369
374
  const hasAnyPatterns = value['$hasAny'].map(v => Buffer.from(JSON.stringify(v), 'utf8'));
370
375
  child.matches = (buffer, valueStart) =>
371
376
  hasAnyPatterns.some(vp => indexOfSameLevel(buffer, vp, valueStart) !== -1);
377
+ } else if (isLoneStartsWith(value)) {
378
+ // The serialized prefix without its closing quote is a byte prefix of every JSON string
379
+ // that starts with it, so the key/value pattern alone decides the match.
380
+ child.isKeyPattern = true;
381
+ child.pattern = Buffer.concat([keyPrefix, Buffer.from(JSON.stringify(value['$startsWith']).slice(0, -1), 'utf8')]);
372
382
  } else if (isOperatorObject(value)) {
373
383
  child.isKeyPattern = true;
374
384
  child.pattern = keyPrefix;
@@ -384,6 +394,18 @@ function buildMatcherTreeChild(key, value) {
384
394
  return child;
385
395
  }
386
396
 
397
+ /**
398
+ * A prefix ending in a lone surrogate serializes as an escape sequence, while a document string
399
+ * continuing the surrogate pair serializes as raw UTF-8, so only well-formed prefixes are byte prefixes.
400
+ *
401
+ * @param {object} value Operator object.
402
+ * @returns {boolean} True when `value` is `{ $startsWith: string }` that can be matched as a byte prefix.
403
+ */
404
+ function isLoneStartsWith(value) {
405
+ const prefix = value['$startsWith'];
406
+ return typeof prefix === 'string' && prefix.isWellFormed() && Object.keys(value).length === 1;
407
+ }
408
+
387
409
  /**
388
410
  * @param {Buffer} keyPrefix Serialized key prefix (`"key":`).
389
411
  * @param {any} value Scalar value to append.
@@ -497,7 +519,7 @@ function matchesOrdering(operator, ordering) {
497
519
  function buildNumericOperatorComparisons(entries) {
498
520
  const comparisons = [];
499
521
  for (const [operator, expectedValue] of entries) {
500
- if (typeof expectedValue !== 'number') {
522
+ if (typeof expectedValue !== 'number' || !ORDERING_OPERATORS.has(operator)) {
501
523
  return null;
502
524
  }
503
525
  const expectedStr = JSON.stringify(expectedValue);
@@ -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;