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.
@@ -0,0 +1,185 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { assert } from '../utils/util.js';
5
+
6
+ const LOCK_RECLAIM = 0x1;
7
+ const LOCK_THROW = 0x2;
8
+ const LOCK_AUTO = 0x4;
9
+
10
+ // Ends in `.lock` so that partition scans, also those of earlier versions, skip it like the lock directory itself.
11
+ const OWNER_FILE = 'owner.lock';
12
+ const RECLAIM_MARKER = 'reclaim.lock';
13
+
14
+ class StorageLockedError extends Error {}
15
+
16
+ /**
17
+ * Containers sharing a host name can not see each other's processes, so a pid is only comparable within one pid namespace.
18
+ *
19
+ * @returns {string|null} The pid namespace of this process on Linux, null elsewhere.
20
+ */
21
+ function currentPidNamespace() {
22
+ try {
23
+ return fs.readlinkSync('/proc/self/ns/pid');
24
+ /* c8 ignore next 3 */
25
+ } catch (e) {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * @param {number} pid
32
+ * @returns {boolean}
33
+ */
34
+ function isProcessRunning(pid) {
35
+ try {
36
+ process.kill(pid, 0);
37
+ return true;
38
+ } catch (e) {
39
+ return e.code === 'EPERM';
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The single-writer lock of a storage: a directory that only one writer can create, holding a file that names its owner
45
+ * process, so that the lock of a crashed writer can be told apart from the lock of a running one.
46
+ */
47
+ class StorageLock {
48
+
49
+ /**
50
+ * @param {string} directory The path of the lock directory.
51
+ * @param {string} storageName The storage name used in error messages.
52
+ * @param {number} [mode] One of the LOCK_* constants. Default LOCK_AUTO.
53
+ */
54
+ constructor(directory, storageName, mode = LOCK_AUTO) {
55
+ this.directory = directory;
56
+ this.storageName = storageName;
57
+ this.mode = mode;
58
+ this.held = false;
59
+ }
60
+
61
+ /**
62
+ * Remove a lock left behind by another writer: always with LOCK_RECLAIM, with LOCK_AUTO only when its owner is gone.
63
+ *
64
+ * @returns {boolean} True if such a lock was removed, which means the storage needs to be repaired.
65
+ */
66
+ reclaimOrphaned() {
67
+ if (this.held) {
68
+ return false;
69
+ }
70
+ if (this.mode === LOCK_RECLAIM) {
71
+ return this.release();
72
+ }
73
+ return this.mode === LOCK_AUTO && this.isOwnerGone() && this.removeStaleLock();
74
+ }
75
+
76
+ /**
77
+ * Two writers starting at the same time may both find the owner gone. Without a claim, the slower one would delete
78
+ * the lock the faster one has just acquired. The claim is a directory inside the stale lock that only one of them
79
+ * can create, and the owner is checked again while holding it.
80
+ *
81
+ * @private
82
+ * @returns {boolean} True if the stale lock was removed by this instance.
83
+ */
84
+ removeStaleLock() {
85
+ const marker = path.join(this.directory, RECLAIM_MARKER);
86
+ try {
87
+ fs.mkdirSync(marker);
88
+ } catch (e) {
89
+ return false;
90
+ }
91
+ if (!this.isOwnerGone()) {
92
+ fs.rmdirSync(marker);
93
+ return false;
94
+ }
95
+ fs.rmSync(this.directory, { recursive: true, force: true });
96
+ return true;
97
+ }
98
+
99
+ /**
100
+ * @returns {boolean} True if the lock was acquired or false if this instance already holds it.
101
+ * @throws {StorageLockedError} If another writer holds the lock.
102
+ */
103
+ acquire() {
104
+ if (this.held) {
105
+ return false;
106
+ }
107
+ try {
108
+ fs.mkdirSync(this.directory);
109
+ } catch (e) {
110
+ /* c8 ignore next */
111
+ assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageName}: ` + e.message);
112
+ throw new StorageLockedError(this.describeHolder());
113
+ }
114
+ this.held = true;
115
+ StorageLock.heldByThisProcess.add(this.directory);
116
+ const owner = { pid: process.pid, hostname: os.hostname(), pidNamespace: currentPidNamespace(), lockedAt: new Date().toISOString() };
117
+ fs.writeFileSync(path.join(this.directory, OWNER_FILE), JSON.stringify(owner));
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * Remove the lock, no matter which writer holds it.
123
+ *
124
+ * @returns {boolean} True if a lock not held by this instance was removed.
125
+ */
126
+ release() {
127
+ const exists = fs.existsSync(this.directory);
128
+ const orphaned = exists && !this.held;
129
+ if (exists) {
130
+ fs.rmSync(this.directory, { recursive: true, force: true });
131
+ }
132
+ if (this.held) {
133
+ StorageLock.heldByThisProcess.delete(this.directory);
134
+ }
135
+ this.held = false;
136
+ return orphaned;
137
+ }
138
+
139
+ /**
140
+ * @returns {{pid: number, hostname: string, pidNamespace: string|null, lockedAt: string}|null} The process holding
141
+ * the lock, or null if there is no lock or it carries no owner information.
142
+ */
143
+ readOwner() {
144
+ try {
145
+ const owner = JSON.parse(fs.readFileSync(path.join(this.directory, OWNER_FILE), 'utf8'));
146
+ return Number.isInteger(owner.pid) ? owner : null;
147
+ } catch (e) {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Only an owner that provably ran in this process table (same host, same pid namespace) and no longer runs counts
154
+ * as gone. Anything else, including a lock without owner information, is treated as held.
155
+ *
156
+ * @private
157
+ * @returns {boolean}
158
+ */
159
+ isOwnerGone() {
160
+ const owner = this.readOwner();
161
+ if (owner === null || owner.hostname !== os.hostname() || owner.pidNamespace !== currentPidNamespace()) {
162
+ return false;
163
+ }
164
+ if (owner.pid === process.pid) {
165
+ return !StorageLock.heldByThisProcess.has(this.directory);
166
+ }
167
+ return !isProcessRunning(owner.pid);
168
+ }
169
+
170
+ /**
171
+ * @private
172
+ * @returns {string}
173
+ */
174
+ describeHolder() {
175
+ const owner = this.readOwner();
176
+ const holder = owner === null ? 'another process' : `process ${owner.pid} on ${owner.hostname} (locked at ${owner.lockedAt})`;
177
+ return `Storage ${this.storageName} is locked by ${holder}. If that process is no longer running, open the storage with LOCK_RECLAIM.`;
178
+ }
179
+ }
180
+
181
+ // Lock directories held in this process, to tell an own live lock from one left by an earlier process with the same pid.
182
+ StorageLock.heldByThisProcess = new Set();
183
+
184
+ export default StorageLock;
185
+ export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
@@ -3,17 +3,19 @@ import path from 'path';
3
3
  import WritablePartition from '../Partition/WritablePartition.js';
4
4
  import WritableIndex, { Entry as WritableIndexEntry } from '../Index/WritableIndex.js';
5
5
  import ReadableStorage from './ReadableStorage.js';
6
+ import StorageLock, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './StorageLock.js';
6
7
  import { assert } from '../utils/util.js';
7
8
  import { ensureDirectory } from '../utils/fsUtil.js';
8
9
  import { matches, buildMetadataForMatcher, buildMatcherFromMetadata } from '../utils/metadataUtil.js';
9
10
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
10
11
 
11
- const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
12
+ const PARTITION_PROBE_SEPARATOR = '~';
13
+ const PROBE_SUFFIX_PATTERN = new RegExp(PARTITION_PROBE_SEPARATOR + '\\d+$');
12
14
 
13
- const LOCK_RECLAIM = 0x1;
14
- const LOCK_THROW = 0x2;
15
+ const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
15
16
 
16
- class StorageLockedError extends Error {}
17
+ // Index entries and document headers store sequence numbers, file positions and sizes as unsigned 32-bit integers.
18
+ const MAX_UINT32 = 0xFFFFFFFF;
17
19
 
18
20
  /**
19
21
  * @typedef {object|function(object):boolean} Matcher
@@ -38,11 +40,12 @@ class WritableStorage extends ReadableStorage {
38
40
  * @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
39
41
  * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
40
42
  * @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
43
+ * @param {number} [config.syncInterval] Group commit: fsync each partition at most every this many ms and only then invoke write callbacks. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
41
44
  * @param {boolean} [config.dirtyReads] If dirty reads should be allowed. This means that writes that are in write buffer but not yet flushed can be read. Defaults to true.
42
45
  * @param {function(object, number): string} [config.partitioner] A function that takes a document and sequence number and returns a partition name that the document should be stored in. Defaults to write all documents to the primary partition.
43
46
  * @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
44
47
  * @param {string} [config.hmacSecret] A private key that is used to verify matchers retrieved from indexes.
45
- * @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled.
48
+ * @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled. Default LOCK_AUTO.
46
49
  */
47
50
  constructor(storageName = 'storage', config = {}) {
48
51
  ({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
@@ -51,24 +54,27 @@ class WritableStorage extends ReadableStorage {
51
54
  writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
52
55
  maxWriteBufferDocuments: 0,
53
56
  syncOnFlush: false,
57
+ syncInterval: 0,
54
58
  dirtyReads: true,
55
- dataDirectory: '.'
59
+ dataDirectory: '.',
60
+ lock: LOCK_AUTO
56
61
  };
57
62
  config = Object.assign(defaults, config);
58
- config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush }, config.indexOptions);
63
+ assert(Number.isInteger(config.syncInterval) && config.syncInterval >= 0, 'syncInterval must be a non-negative integer.');
64
+ config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush, syncInterval: config.syncInterval }, config.indexOptions);
59
65
  ensureDirectory(config.dataDirectory);
60
66
  super(storageName, config);
61
67
 
62
68
  this.lockFile = path.resolve(this.dataDirectory, this.storageFile + '.lock');
63
- this._lockMode = config.lock;
69
+ this.storageLock = new StorageLock(this.lockFile, this.storageFile, config.lock);
64
70
  this.partitioner = config.partitioner;
65
71
  this.partitionIds = {};
66
72
  }
67
73
 
68
74
  /**
69
75
  * Acquires the write lock synchronously.
70
- * For LOCK_RECLAIM, removes any orphaned lock before trying to acquire our own; torn-write
71
- * repair runs after the primary index is open, before `'opened'` is emitted.
76
+ * Removes an orphaned lock first (always with LOCK_RECLAIM, with LOCK_AUTO only when its owner process is gone);
77
+ * torn-write repair then runs after the primary index is open, before `'opened'` is emitted.
72
78
  *
73
79
  * @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
74
80
  * Can be used as a synchronous alternative to listening to the `'opened'` event.
@@ -76,7 +82,7 @@ class WritableStorage extends ReadableStorage {
76
82
  * @throws {StorageLockedError} If this storage is locked by another process.
77
83
  */
78
84
  open(callback) {
79
- const needsRepair = this._lockMode === LOCK_RECLAIM && this.unlock();
85
+ const needsRepair = this.storageLock.reclaimOrphaned();
80
86
 
81
87
  if (!this.lock()) {
82
88
  return true;
@@ -177,8 +183,6 @@ class WritableStorage extends ReadableStorage {
177
183
  }
178
184
 
179
185
  this.forEachPartition(partition => partition.close());
180
- // Partitions were closed directly (bypassing the pool), so reset the open-handle tracking.
181
- this.partitions.clearOpenHandles();
182
186
  }
183
187
 
184
188
  /**
@@ -216,6 +220,22 @@ class WritableStorage extends ReadableStorage {
216
220
  this.flush();
217
221
  }
218
222
 
223
+ /**
224
+ * @api
225
+ * @returns {{pid: number, hostname: string, pidNamespace: string|null, lockedAt: string}|null} The process holding
226
+ * the lock, or null if the storage is not locked or the lock carries no owner information.
227
+ */
228
+ readLockOwner() {
229
+ return this.storageLock.readOwner();
230
+ }
231
+
232
+ /**
233
+ * @returns {boolean} If this writer holds the storage lock.
234
+ */
235
+ get locked() {
236
+ return this.storageLock.held;
237
+ }
238
+
219
239
  /**
220
240
  * Attempt to lock this storage by means of a lock directory.
221
241
  * @returns {boolean} True if the lock was created or false if the lock is already in place.
@@ -223,35 +243,16 @@ class WritableStorage extends ReadableStorage {
223
243
  * @throws {Error} If the lock could not be created.
224
244
  */
225
245
  lock() {
226
- if (this.locked) {
227
- return false;
228
- }
229
- try {
230
- fs.mkdirSync(this.lockFile);
231
- this.locked = true;
232
- } catch (e) {
233
- /* c8 ignore next */
234
- assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
235
-
236
- throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
237
- }
238
- return true;
246
+ return this.storageLock.acquire();
239
247
  }
240
248
 
241
249
  /**
242
250
  * Unlock this storage, no matter if it was previously locked by this writer.
243
251
  * Only use this if you are sure there is no other process still having a writer open.
244
- * Current implementation just deletes a lock file that is named like the storage.
245
252
  * @returns {boolean} True if an orphaned lock from another process was removed.
246
253
  */
247
254
  unlock() {
248
- const lockExists = fs.existsSync(this.lockFile);
249
- const orphaned = lockExists && !this.locked;
250
- if (lockExists) {
251
- fs.rmdirSync(this.lockFile);
252
- }
253
- this.locked = false;
254
- return orphaned;
255
+ return this.storageLock.release();
255
256
  }
256
257
 
257
258
  /**
@@ -265,6 +266,21 @@ class WritableStorage extends ReadableStorage {
265
266
  super.close();
266
267
  }
267
268
 
269
+ /**
270
+ * Reject a write that the index format can not record, before anything is written. Otherwise the document would
271
+ * land in the partition and the index entry would fail afterwards, leaving data and index diverged.
272
+ *
273
+ * @private
274
+ * @param {WritablePartition} partition The partition the document will be written to.
275
+ * @throws {Error} if the storage or the partition is full.
276
+ */
277
+ assertWithinLimits(partition) {
278
+ assert(this.index.length < MAX_UINT32,
279
+ `Storage is full: it can hold at most ${MAX_UINT32} documents.`);
280
+ assert(partition.size <= MAX_UINT32,
281
+ `Partition ${partition.name} is full: documents must start within the first 4 GiB of a partition. Use a partitioner that spreads the documents over more partitions.`);
282
+ }
283
+
268
284
  /**
269
285
  * Add an index entry for the given document at the position and size.
270
286
  *
@@ -294,6 +310,7 @@ class WritableStorage extends ReadableStorage {
294
310
  return callback(indexPosition);
295
311
  }
296
312
  });
313
+ this.emit('index-add', '_all', this.index.length, document);
297
314
  return entry;
298
315
  }
299
316
 
@@ -310,10 +327,33 @@ class WritableStorage extends ReadableStorage {
310
327
  this.on('preCommit', hook);
311
328
  }
312
329
 
313
- getPartitionIdForName(partitionShortName, partitionName) {
314
- const partitionId = this.partitionIds[partitionShortName] ?? WritablePartition.idFor(partitionName);
315
- this.partitionIds[partitionShortName] = partitionId;
316
- return partitionId;
330
+ /**
331
+ * Resolve the id and file name of the partition for a partition name.
332
+ *
333
+ * A partition id is the 32-bit hash of the partition file name, both here and when readers scan the files.
334
+ * If that id is already taken by a partition with a different file name (hash collision), the partition is
335
+ * stored in the file `<partitionName>~1` instead, and so on. The probing is deterministic, so the same
336
+ * name always resolves to the same file, and readers derive the same id from the file name.
337
+ *
338
+ * @private
339
+ * @param {string} partitionShortName The partition name returned by the partitioner.
340
+ * @param {string} partitionName The partition file name without probe suffix.
341
+ * @returns {{ id: number, fileName: string }}
342
+ */
343
+ resolvePartition(partitionShortName, partitionName) {
344
+ const cached = this.partitionIds[partitionShortName];
345
+ if (cached !== undefined) {
346
+ return cached;
347
+ }
348
+ let fileName = partitionName;
349
+ let partitionId = WritablePartition.idFor(fileName);
350
+ for (let probe = 1; partitionId in this.partitions && this.partitions[partitionId].name !== fileName; probe++) {
351
+ fileName = partitionName + PARTITION_PROBE_SEPARATOR + probe;
352
+ partitionId = WritablePartition.idFor(fileName);
353
+ }
354
+ const resolved = { id: partitionId, fileName };
355
+ this.partitionIds[partitionShortName] = resolved;
356
+ return resolved;
317
357
  }
318
358
 
319
359
  buildPartitionConfig(partitionShortName) {
@@ -331,12 +371,14 @@ class WritableStorage extends ReadableStorage {
331
371
  }
332
372
 
333
373
  createNamedPartition(partitionId, partitionName, partitionShortName) {
334
- if (this.partitions.has(partitionId)) {
374
+ if (partitionId in this.partitions) {
335
375
  return;
336
376
  }
377
+ assert(!PROBE_SUFFIX_PATTERN.test(partitionShortName),
378
+ `Invalid partition name "${partitionShortName}". Names ending in "${PARTITION_PROBE_SEPARATOR}<number>" are reserved.`);
337
379
  const partitionConfig = this.buildPartitionConfig(partitionShortName);
338
380
  this.ensurePartitionDirectory(partitionName);
339
- this.partitions.add(partitionId, this.createPartition(partitionName, partitionConfig));
381
+ this.partitions[partitionId] = this.createPartition(partitionName, partitionConfig);
340
382
  this.emit('partition-created', partitionId);
341
383
  }
342
384
 
@@ -356,8 +398,9 @@ class WritableStorage extends ReadableStorage {
356
398
  if (typeof partitionIdentifier === 'string') {
357
399
  const partitionShortName = partitionIdentifier;
358
400
  const partitionName = this.storageFile + (partitionIdentifier.length ? '.' + partitionIdentifier : '');
359
- partitionIdentifier = this.getPartitionIdForName(partitionShortName, partitionName);
360
- this.createNamedPartition(partitionIdentifier, partitionName, partitionShortName);
401
+ const { id, fileName } = this.resolvePartition(partitionShortName, partitionName);
402
+ this.createNamedPartition(id, fileName, partitionShortName);
403
+ partitionIdentifier = id;
361
404
  }
362
405
  return super.getPartition(partitionIdentifier);
363
406
  }
@@ -374,6 +417,7 @@ class WritableStorage extends ReadableStorage {
374
417
 
375
418
  const partitionName = this.partitioner(document, this.index.length + 1);
376
419
  const partition = this.getPartition(partitionName);
420
+ this.assertWithinLimits(partition);
377
421
  this.emit('preCommit', document, partition.metadata);
378
422
 
379
423
  const position = partition.write(data, this.length, callback);
@@ -458,7 +502,7 @@ class WritableStorage extends ReadableStorage {
458
502
  */
459
503
  forEachDistinctPartitionOf(entries, iterationHandler) {
460
504
  const partitions = [];
461
- const numPartitions = this.partitions.count;
505
+ const numPartitions = Object.keys(this.partitions).length;
462
506
  for (let entry of entries) {
463
507
  if (partitions.indexOf(entry.partition) >= 0) {
464
508
  continue;
@@ -487,12 +531,8 @@ class WritableStorage extends ReadableStorage {
487
531
  return;
488
532
  }
489
533
 
490
- const entries = this.index.range(after + 1); // We need the first entry that is cut off
491
- if (entries === false || entries.length === 0) {
492
- return;
493
- }
494
-
495
- this.forEachDistinctPartitionOf(entries, entry => this.getPartition(entry.partition).truncate(entry.position));
534
+ // We need the first entry that is cut off in each partition.
535
+ this.forEachDistinctPartitionOf(this.index.range(after + 1), entry => this.getPartition(entry.partition).truncate(entry.position));
496
536
  }
497
537
 
498
538
  /**
@@ -545,7 +585,7 @@ class WritableStorage extends ReadableStorage {
545
585
  * @returns {{ index: WritableIndex, matcher: Matcher }}
546
586
  */
547
587
  createIndex(name, options = {}) {
548
- const index = new WritableIndex(name, options);
588
+ const index = new WritableIndex(name, { ...options, fileHandlePool: this.indexHandlePool });
549
589
  let matcher;
550
590
 
551
591
  // If the index contains a matcher (possibly a serialized function) we check HMAC
@@ -569,10 +609,10 @@ class WritableStorage extends ReadableStorage {
569
609
  * @returns {WritablePartition}
570
610
  */
571
611
  createPartition(name, config = {}) {
572
- return new WritablePartition(name, config);
612
+ return new WritablePartition(name, { ...config, fileHandlePool: this.partitionHandlePool });
573
613
  }
574
614
 
575
615
  }
576
616
 
577
617
  export default WritableStorage;
578
- export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM };
618
+ export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
package/src/Storage.js CHANGED
@@ -1,10 +1,11 @@
1
- import WritableStorage, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM } from './Storage/WritableStorage.js';
1
+ import WritableStorage, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './Storage/WritableStorage.js';
2
2
  import ReadOnlyStorage from './Storage/ReadOnlyStorage.js';
3
3
 
4
4
  WritableStorage.ReadOnly = ReadOnlyStorage;
5
5
  WritableStorage.StorageLockedError = StorageLockedError;
6
6
  WritableStorage.LOCK_THROW = LOCK_THROW;
7
7
  WritableStorage.LOCK_RECLAIM = LOCK_RECLAIM;
8
+ WritableStorage.LOCK_AUTO = LOCK_AUTO;
8
9
 
9
10
  export default WritableStorage;
10
- export { ReadOnlyStorage as ReadOnly, StorageLockedError, LOCK_THROW, LOCK_RECLAIM };
11
+ export { ReadOnlyStorage as ReadOnly, StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO };
package/src/Watcher.js CHANGED
@@ -229,6 +229,7 @@ class Watcher extends events.EventEmitter {
229
229
  */
230
230
  constructor(fileOrDirectory, fileFilter = null, options = null) {
231
231
  super();
232
+ this.setMaxListeners(0);
232
233
  const watchOptions = Object.assign({ recursive: true }, options);
233
234
  delete watchOptions.rootDirectory;
234
235
  this.relativePrefixes = [];
@@ -67,4 +67,21 @@ function compileDcbItem(item, resolveType, resolveTag) {
67
67
  return terms; // inner array = AND level
68
68
  }
69
69
 
70
- export {isDcbQuery, compileDcbQuery};
70
+ /**
71
+ * Check in memory whether an event with the given type and tags matches a {@link DcbQuery}.
72
+ * Mirrors the semantics of {@link compileDcbQuery}: items are ORed, tags within an item are ANDed,
73
+ * types within an item are ORed, and a missing/empty `types` or `tags` constraint matches anything.
74
+ *
75
+ * @param {object} query A DcbQuery with an `items` array.
76
+ * @param {string|undefined} type The event type.
77
+ * @param {string[]} tags The event tags (empty array when the event has none).
78
+ * @returns {boolean}
79
+ */
80
+ function matchesDcbQuery(query, type, tags) {
81
+ return query.items.some(item =>
82
+ (!item.types?.length || item.types.includes(type)) &&
83
+ (item.tags ?? []).every(tag => tags.includes(tag))
84
+ );
85
+ }
86
+
87
+ export {isDcbQuery, compileDcbQuery, matchesDcbQuery};
@@ -14,6 +14,59 @@ 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
+ * A new file is only guaranteed to survive a power loss once its directory entry is synced as well.
53
+ * Platforms that can not open a directory for syncing (Windows) are skipped silently.
54
+ *
55
+ * @param {string} dirName
56
+ */
57
+ function syncDirectory(dirName) {
58
+ let fd;
59
+ try {
60
+ fd = fs.openSync(dirName, 'r');
61
+ fs.fsyncSync(fd);
62
+ } catch (e) {
63
+ } finally {
64
+ if (fd !== undefined) {
65
+ fs.closeSync(fd);
66
+ }
67
+ }
68
+ }
69
+
17
70
  /**
18
71
  * Ensure that the given directory exists.
19
72
  * @param {string} dirName Target directory.
@@ -150,5 +203,8 @@ export {
150
203
  resolvePath,
151
204
  ensureDirectory,
152
205
  scanForFiles,
153
- isSameOrParentDirectory
206
+ isSameOrParentDirectory,
207
+ safeUnlink,
208
+ syncDirectory,
209
+ writeFileAtomic
154
210
  };