event-storage 1.4.1 → 1.5.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.
@@ -14,6 +14,130 @@ function resolvePath(fileOrDirectory, ...directories) {
14
14
  return path.resolve(fileOrDirectory, ...directories);
15
15
  }
16
16
 
17
+ /**
18
+ * Unlink a file, ignoring the error if it does not exist.
19
+ * @param {string} fileName
20
+ * @throws {Error} For any error other than ENOENT.
21
+ */
22
+ function safeUnlink(fileName) {
23
+ try {
24
+ fs.unlinkSync(fileName);
25
+ } catch (e) {
26
+ if (e.code !== 'ENOENT') {
27
+ throw e;
28
+ }
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Replace a file atomically: write to a temporary file, then rename it over the target.
34
+ * A failed or interrupted write never leaves a partially written target file behind.
35
+ *
36
+ * @param {string} fileName Target file.
37
+ * @param {string|Buffer} data
38
+ * @param {string} [tmpFileName] Temporary file to write first. Defaults to `fileName + '.tmp'`.
39
+ * @throws {Error} When writing or renaming fails; the temporary file is removed in that case.
40
+ */
41
+ function writeFileAtomic(fileName, data, tmpFileName = fileName + '.tmp') {
42
+ try {
43
+ fs.writeFileSync(tmpFileName, data);
44
+ fs.renameSync(tmpFileName, fileName);
45
+ } catch (e) {
46
+ safeUnlink(tmpFileName);
47
+ throw e;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Sync a file to disk through its own descriptor, independent of whether and where the file is open otherwise.
53
+ * Without a callback this blocks until the file is on disk. With a callback it runs on the libuv thread pool, so the
54
+ * event loop goes on meanwhile and several files can be synced in parallel.
55
+ *
56
+ * @param {string} fileName
57
+ * @param {function(Error|null)} [callback]
58
+ */
59
+ function syncFile(fileName, callback) {
60
+ syncPath(fileName, 'r+', callback);
61
+ }
62
+
63
+ /**
64
+ * Like `syncFile()` for a directory. Platforms that can not open a directory for syncing (Windows) are skipped silently.
65
+ *
66
+ * @param {string} dirName
67
+ * @param {function(Error|null)} [callback] Always called without an error.
68
+ */
69
+ function syncDirectory(dirName, callback) {
70
+ if (typeof callback === 'function') {
71
+ syncPath(dirName, 'r', () => callback(null));
72
+ return;
73
+ }
74
+ try {
75
+ syncPath(dirName, 'r');
76
+ } catch (e) {
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @param {string} fileName
82
+ * @param {string} flags The flags to open the file with. Windows needs write access to sync a file.
83
+ * @param {function(Error|null)} [callback]
84
+ */
85
+ function syncPath(fileName, flags, callback) {
86
+ if (typeof callback !== 'function') {
87
+ const fd = fs.openSync(fileName, flags);
88
+ try {
89
+ fs.fsyncSync(fd);
90
+ } finally {
91
+ fs.closeSync(fd);
92
+ }
93
+ return;
94
+ }
95
+ fs.open(fileName, flags, (openError, fd) => {
96
+ if (openError) {
97
+ callback(openError);
98
+ return;
99
+ }
100
+ fs.fsync(fd, syncError => fs.close(fd, closeError => callback(syncError || closeError || null)));
101
+ });
102
+ }
103
+
104
+ /**
105
+ * A file deleted since it was written needs no sync anymore: its data is gone on purpose.
106
+ *
107
+ * @param {Error} error
108
+ */
109
+ function ignoreDeletedFile(error) {
110
+ if (error.code !== 'ENOENT') {
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Call all tasks at once and the callback once all of them called back, or with the first error.
117
+ *
118
+ * @param {Array<function(function(Error|null))>} tasks
119
+ * @param {function(Error|null)} callback
120
+ */
121
+ function parallel(tasks, callback) {
122
+ let pending = tasks.length;
123
+ let failed = false;
124
+ if (pending === 0) {
125
+ callback(null);
126
+ return;
127
+ }
128
+ for (const task of tasks) {
129
+ task(error => {
130
+ if (failed) return;
131
+ if (error) {
132
+ failed = true;
133
+ callback(error);
134
+ } else if (--pending === 0) {
135
+ callback(null);
136
+ }
137
+ });
138
+ }
139
+ }
140
+
17
141
  /**
18
142
  * Ensure that the given directory exists.
19
143
  * @param {string} dirName Target directory.
@@ -150,5 +274,11 @@ export {
150
274
  resolvePath,
151
275
  ensureDirectory,
152
276
  scanForFiles,
153
- isSameOrParentDirectory
277
+ isSameOrParentDirectory,
278
+ safeUnlink,
279
+ syncDirectory,
280
+ syncFile,
281
+ ignoreDeletedFile,
282
+ parallel,
283
+ writeFileAtomic
154
284
  };
@@ -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);