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.
@@ -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,20 @@ 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';
9
+ import SyncScheduler from '../SyncScheduler.js';
8
10
  import { matches, buildMetadataForMatcher, buildMatcherFromMetadata } from '../utils/metadataUtil.js';
9
11
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
10
12
 
11
- const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
13
+ const PARTITION_PROBE_SEPARATOR = '~';
14
+ const PROBE_SUFFIX_PATTERN = new RegExp(PARTITION_PROBE_SEPARATOR + '\\d+$');
12
15
 
13
- const LOCK_RECLAIM = 0x1;
14
- const LOCK_THROW = 0x2;
16
+ const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
15
17
 
16
- class StorageLockedError extends Error {}
18
+ // Index entries and document headers store sequence numbers, file positions and sizes as unsigned 32-bit integers.
19
+ const MAX_UINT32 = 0xFFFFFFFF;
17
20
 
18
21
  /**
19
22
  * @typedef {object|function(object):boolean} Matcher
@@ -38,11 +41,12 @@ class WritableStorage extends ReadableStorage {
38
41
  * @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
39
42
  * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
40
43
  * @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
44
+ * @param {number} [config.syncInterval] Group commit: fsync every partition written at most this many ms later, in one shared run, and only then invoke write callbacks. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
41
45
  * @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
46
  * @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
47
  * @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
44
48
  * @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.
49
+ * @param {number} [config.lock] One of LOCK_* constants that defines how an existing lock should be handled. Default LOCK_AUTO.
46
50
  */
47
51
  constructor(storageName = 'storage', config = {}) {
48
52
  ({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
@@ -51,24 +55,31 @@ class WritableStorage extends ReadableStorage {
51
55
  writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
52
56
  maxWriteBufferDocuments: 0,
53
57
  syncOnFlush: false,
58
+ syncInterval: 0,
54
59
  dirtyReads: true,
55
- dataDirectory: '.'
60
+ dataDirectory: '.',
61
+ lock: LOCK_AUTO
56
62
  };
57
63
  config = Object.assign(defaults, config);
58
- config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush }, config.indexOptions);
64
+ assert(Number.isInteger(config.syncInterval) && config.syncInterval >= 0, 'syncInterval must be a non-negative integer.');
65
+ // One scheduler for all partitions and indexes, so that the files flushed within an interval share one sync run.
66
+ const syncScheduler = new SyncScheduler(config);
67
+ config.indexOptions = Object.assign({ syncOnFlush: config.syncOnFlush, syncInterval: config.syncInterval }, config.indexOptions, { syncScheduler });
68
+ config.syncScheduler = syncScheduler;
59
69
  ensureDirectory(config.dataDirectory);
60
70
  super(storageName, config);
71
+ this.syncScheduler = syncScheduler;
61
72
 
62
73
  this.lockFile = path.resolve(this.dataDirectory, this.storageFile + '.lock');
63
- this._lockMode = config.lock;
74
+ this.storageLock = new StorageLock(this.lockFile, this.storageFile, config.lock);
64
75
  this.partitioner = config.partitioner;
65
76
  this.partitionIds = {};
66
77
  }
67
78
 
68
79
  /**
69
80
  * 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.
81
+ * Removes an orphaned lock first (always with LOCK_RECLAIM, with LOCK_AUTO only when its owner process is gone);
82
+ * torn-write repair then runs after the primary index is open, before `'opened'` is emitted.
72
83
  *
73
84
  * @param {function(): void} [callback] Called after indexes open, before `'opened'` is emitted.
74
85
  * Can be used as a synchronous alternative to listening to the `'opened'` event.
@@ -76,7 +87,7 @@ class WritableStorage extends ReadableStorage {
76
87
  * @throws {StorageLockedError} If this storage is locked by another process.
77
88
  */
78
89
  open(callback) {
79
- const needsRepair = this._lockMode === LOCK_RECLAIM && this.unlock();
90
+ const needsRepair = this.storageLock.reclaimOrphaned();
80
91
 
81
92
  if (!this.lock()) {
82
93
  return true;
@@ -214,6 +225,22 @@ class WritableStorage extends ReadableStorage {
214
225
  this.flush();
215
226
  }
216
227
 
228
+ /**
229
+ * @api
230
+ * @returns {{pid: number, hostname: string, pidNamespace: string|null, lockedAt: string}|null} The process holding
231
+ * the lock, or null if the storage is not locked or the lock carries no owner information.
232
+ */
233
+ readLockOwner() {
234
+ return this.storageLock.readOwner();
235
+ }
236
+
237
+ /**
238
+ * @returns {boolean} If this writer holds the storage lock.
239
+ */
240
+ get locked() {
241
+ return this.storageLock.held;
242
+ }
243
+
217
244
  /**
218
245
  * Attempt to lock this storage by means of a lock directory.
219
246
  * @returns {boolean} True if the lock was created or false if the lock is already in place.
@@ -221,48 +248,46 @@ class WritableStorage extends ReadableStorage {
221
248
  * @throws {Error} If the lock could not be created.
222
249
  */
223
250
  lock() {
224
- if (this.locked) {
225
- return false;
226
- }
227
- try {
228
- fs.mkdirSync(this.lockFile);
229
- this.locked = true;
230
- } catch (e) {
231
- /* c8 ignore next */
232
- assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
233
-
234
- throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
235
- }
236
- return true;
251
+ return this.storageLock.acquire();
237
252
  }
238
253
 
239
254
  /**
240
255
  * Unlock this storage, no matter if it was previously locked by this writer.
241
256
  * Only use this if you are sure there is no other process still having a writer open.
242
- * Current implementation just deletes a lock file that is named like the storage.
243
257
  * @returns {boolean} True if an orphaned lock from another process was removed.
244
258
  */
245
259
  unlock() {
246
- const lockExists = fs.existsSync(this.lockFile);
247
- const orphaned = lockExists && !this.locked;
248
- if (lockExists) {
249
- fs.rmdirSync(this.lockFile);
250
- }
251
- this.locked = false;
252
- return orphaned;
260
+ return this.storageLock.release();
253
261
  }
254
262
 
255
263
  /**
256
264
  * @inheritDoc
257
- * Unlocks the storage, then delegates to the parent close().
265
+ * Syncs everything written as configured, unlocks the storage, then delegates to the parent close().
258
266
  */
259
267
  close() {
268
+ this.forEachPartition(partition => partition.flush());
269
+ this.syncScheduler.run();
260
270
  if (this.locked) {
261
271
  this.unlock();
262
272
  }
263
273
  super.close();
264
274
  }
265
275
 
276
+ /**
277
+ * Reject a write that the index format can not record, before anything is written. Otherwise the document would
278
+ * land in the partition and the index entry would fail afterwards, leaving data and index diverged.
279
+ *
280
+ * @private
281
+ * @param {WritablePartition} partition The partition the document will be written to.
282
+ * @throws {Error} if the storage or the partition is full.
283
+ */
284
+ assertWithinLimits(partition) {
285
+ assert(this.index.length < MAX_UINT32,
286
+ `Storage is full: it can hold at most ${MAX_UINT32} documents.`);
287
+ assert(partition.size <= MAX_UINT32,
288
+ `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.`);
289
+ }
290
+
266
291
  /**
267
292
  * Add an index entry for the given document at the position and size.
268
293
  *
@@ -309,10 +334,33 @@ class WritableStorage extends ReadableStorage {
309
334
  this.on('preCommit', hook);
310
335
  }
311
336
 
312
- getPartitionIdForName(partitionShortName, partitionName) {
313
- const partitionId = this.partitionIds[partitionShortName] ?? WritablePartition.idFor(partitionName);
314
- this.partitionIds[partitionShortName] = partitionId;
315
- return partitionId;
337
+ /**
338
+ * Resolve the id and file name of the partition for a partition name.
339
+ *
340
+ * A partition id is the 32-bit hash of the partition file name, both here and when readers scan the files.
341
+ * If that id is already taken by a partition with a different file name (hash collision), the partition is
342
+ * stored in the file `<partitionName>~1` instead, and so on. The probing is deterministic, so the same
343
+ * name always resolves to the same file, and readers derive the same id from the file name.
344
+ *
345
+ * @private
346
+ * @param {string} partitionShortName The partition name returned by the partitioner.
347
+ * @param {string} partitionName The partition file name without probe suffix.
348
+ * @returns {{ id: number, fileName: string }}
349
+ */
350
+ resolvePartition(partitionShortName, partitionName) {
351
+ const cached = this.partitionIds[partitionShortName];
352
+ if (cached !== undefined) {
353
+ return cached;
354
+ }
355
+ let fileName = partitionName;
356
+ let partitionId = WritablePartition.idFor(fileName);
357
+ for (let probe = 1; partitionId in this.partitions && this.partitions[partitionId].name !== fileName; probe++) {
358
+ fileName = partitionName + PARTITION_PROBE_SEPARATOR + probe;
359
+ partitionId = WritablePartition.idFor(fileName);
360
+ }
361
+ const resolved = { id: partitionId, fileName };
362
+ this.partitionIds[partitionShortName] = resolved;
363
+ return resolved;
316
364
  }
317
365
 
318
366
  buildPartitionConfig(partitionShortName) {
@@ -333,6 +381,8 @@ class WritableStorage extends ReadableStorage {
333
381
  if (partitionId in this.partitions) {
334
382
  return;
335
383
  }
384
+ assert(!PROBE_SUFFIX_PATTERN.test(partitionShortName),
385
+ `Invalid partition name "${partitionShortName}". Names ending in "${PARTITION_PROBE_SEPARATOR}<number>" are reserved.`);
336
386
  const partitionConfig = this.buildPartitionConfig(partitionShortName);
337
387
  this.ensurePartitionDirectory(partitionName);
338
388
  this.partitions[partitionId] = this.createPartition(partitionName, partitionConfig);
@@ -355,8 +405,9 @@ class WritableStorage extends ReadableStorage {
355
405
  if (typeof partitionIdentifier === 'string') {
356
406
  const partitionShortName = partitionIdentifier;
357
407
  const partitionName = this.storageFile + (partitionIdentifier.length ? '.' + partitionIdentifier : '');
358
- partitionIdentifier = this.getPartitionIdForName(partitionShortName, partitionName);
359
- this.createNamedPartition(partitionIdentifier, partitionName, partitionShortName);
408
+ const { id, fileName } = this.resolvePartition(partitionShortName, partitionName);
409
+ this.createNamedPartition(id, fileName, partitionShortName);
410
+ partitionIdentifier = id;
360
411
  }
361
412
  return super.getPartition(partitionIdentifier);
362
413
  }
@@ -373,6 +424,7 @@ class WritableStorage extends ReadableStorage {
373
424
 
374
425
  const partitionName = this.partitioner(document, this.index.length + 1);
375
426
  const partition = this.getPartition(partitionName);
427
+ this.assertWithinLimits(partition);
376
428
  this.emit('preCommit', document, partition.metadata);
377
429
 
378
430
  const position = partition.write(data, this.length, callback);
@@ -486,12 +538,8 @@ class WritableStorage extends ReadableStorage {
486
538
  return;
487
539
  }
488
540
 
489
- const entries = this.index.range(after + 1); // We need the first entry that is cut off
490
- if (entries === false || entries.length === 0) {
491
- return;
492
- }
493
-
494
- this.forEachDistinctPartitionOf(entries, entry => this.getPartition(entry.partition).truncate(entry.position));
541
+ // We need the first entry that is cut off in each partition.
542
+ this.forEachDistinctPartitionOf(this.index.range(after + 1), entry => this.getPartition(entry.partition).truncate(entry.position));
495
543
  }
496
544
 
497
545
  /**
@@ -574,4 +622,4 @@ class WritableStorage extends ReadableStorage {
574
622
  }
575
623
 
576
624
  export default WritableStorage;
577
- export { StorageLockedError, LOCK_THROW, LOCK_RECLAIM };
625
+ 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 };
@@ -0,0 +1,164 @@
1
+ import path from 'path';
2
+ import { syncDirectory, parallel } from './utils/fsUtil.js';
3
+ /** @typedef {import('./FileHandlePool.js').default} FileHandlePool */
4
+
5
+ /**
6
+ * Decides when flushed data reaches the disk, for all files of a storage:
7
+ * - `syncOnFlush`: every flush is synced immediately.
8
+ * - `syncInterval`: all files flushed within the interval are synced together by one run, once each, and only then
9
+ * are their write callbacks invoked (group commit). Commits to different partitions thus share one run. A run syncs
10
+ * its files in parallel in the background, so that it takes about as long as a single fsync and the process can go
11
+ * on writing meanwhile. Runs never overlap, so write callbacks are invoked in the order of the writes.
12
+ * - neither: nothing is synced.
13
+ * The directory of a new file follows the same rule, so that the file survives a power loss.
14
+ */
15
+ class SyncScheduler {
16
+
17
+ /**
18
+ * @param {object} [options]
19
+ * @param {boolean} [options.syncOnFlush] Sync every flush immediately. Defaults to false.
20
+ * @param {number} [options.syncInterval] Sync all flushes at most this many ms later in one run. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
21
+ */
22
+ constructor({ syncOnFlush = false, syncInterval = 0 } = {}) {
23
+ this.immediate = !!syncOnFlush;
24
+ this.interval = this.immediate ? 0 : syncInterval;
25
+ this.timeout = null;
26
+ this.files = new Set();
27
+ this.directories = new Set();
28
+ this.callbacks = [];
29
+ this.running = null;
30
+ this.due = false;
31
+ }
32
+
33
+ /**
34
+ * @param {{fileName: string, fileHandlePool: FileHandlePool}} file The partition or index that was flushed. It is
35
+ * synced through its pool, which uses the pooled descriptor if the file is still open.
36
+ * @param {Array<function>} [callbacks] The write callbacks to invoke once the flushed data is as durable as configured.
37
+ */
38
+ flushed(file, callbacks = []) {
39
+ if (this.immediate) {
40
+ file.fileHandlePool.sync(file);
41
+ } else if (this.interval > 0) {
42
+ this.files.add(file);
43
+ for (let i = 0; i < callbacks.length; i++) this.callbacks.push(callbacks[i]);
44
+ this.schedule();
45
+ return;
46
+ }
47
+ for (let i = 0; i < callbacks.length; i++) callbacks[i]();
48
+ }
49
+
50
+ /**
51
+ * Sync the directory entry of a new file, so that the file survives a power loss. Its content is synced with its
52
+ * flushes. With an interval it is synced by the next run.
53
+ *
54
+ * @param {{fileName: string}} file The partition or index that was created.
55
+ */
56
+ created(file) {
57
+ if (this.immediate) {
58
+ syncDirectory(path.dirname(file.fileName));
59
+ } else if (this.interval > 0) {
60
+ this.directories.add(path.dirname(file.fileName));
61
+ this.schedule();
62
+ }
63
+ }
64
+
65
+ /**
66
+ * @param {object} file
67
+ * @returns {boolean} If a flush of the file waits for the next run.
68
+ */
69
+ isWaiting(file) {
70
+ return this.files.has(file);
71
+ }
72
+
73
+ /**
74
+ * @private
75
+ */
76
+ schedule() {
77
+ if (this.timeout === null && !this.due) {
78
+ this.timeout = setTimeout(() => this.elapsed(), this.interval);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The interval of the oldest waiting flush has elapsed. If a run is still syncing, the next one starts right after it.
84
+ * A failed sync is thrown as an uncaught exception: the data may be lost, and no write after it must be acknowledged.
85
+ * @private
86
+ */
87
+ elapsed() {
88
+ this.timeout = null;
89
+ if (this.running) {
90
+ this.due = true;
91
+ return;
92
+ }
93
+ this.run(error => {
94
+ if (error) {
95
+ process.nextTick(() => { throw error; });
96
+ } else if (this.due) {
97
+ this.elapsed();
98
+ }
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Take everything waiting for a sync, leaving the scheduler empty.
104
+ * @private
105
+ * @returns {{files: Set<object>, directories: Set<string>, callbacks: Array<function>}}
106
+ */
107
+ take() {
108
+ const { files, directories, callbacks } = this;
109
+ this.files = new Set();
110
+ this.directories = new Set();
111
+ this.callbacks = [];
112
+ if (this.timeout !== null) {
113
+ clearTimeout(this.timeout);
114
+ this.timeout = null;
115
+ }
116
+ this.due = false;
117
+ return { files, directories, callbacks };
118
+ }
119
+
120
+ /**
121
+ * Sync every waiting file and the directory of every new file, then invoke their write callbacks in the order of
122
+ * the writes. Writes from within the callbacks belong to the next run.
123
+ * Without a callback this blocks until everything is on disk, and takes over a run still syncing in the background,
124
+ * as when closing the storage. With a callback it syncs everything in parallel in the background.
125
+ *
126
+ * @param {function(Error|null)} [callback] Called once the run is done, or with the error of a failed sync.
127
+ */
128
+ run(callback) {
129
+ const background = typeof callback === 'function';
130
+ const batches = !background && this.running ? [this.running, this.take()] : [this.take()];
131
+ const batch = batches[batches.length - 1];
132
+ this.running = background ? batch : null;
133
+ const done = error => {
134
+ // A run that a blocking run took over was synced and acknowledged by it already.
135
+ if (background && this.running !== batch) return;
136
+ this.running = null;
137
+ if (!error) batches.forEach(({ callbacks }) => invoke(callbacks));
138
+ callback?.(error);
139
+ };
140
+ const syncs = [];
141
+ for (const { files, directories } of batches) {
142
+ for (const file of files) syncs.push(next => file.fileHandlePool.sync(file, next));
143
+ for (const directory of directories) syncs.push(next => syncDirectory(directory, next));
144
+ }
145
+ if (background) {
146
+ parallel(syncs, done);
147
+ } else {
148
+ syncs.forEach(sync => sync());
149
+ done(null);
150
+ }
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Invoke and remove all callbacks, so that a callback is never invoked twice when `run()` already completed a
156
+ * background run.
157
+ * @param {Array<function>} callbacks
158
+ */
159
+ function invoke(callbacks) {
160
+ const waiting = callbacks.splice(0);
161
+ for (let i = 0; i < waiting.length; i++) waiting[i]();
162
+ }
163
+
164
+ export default SyncScheduler;
@@ -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};