event-storage 1.5.0 → 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.
package/index.d.ts CHANGED
@@ -34,7 +34,16 @@ export interface DcbQuery {
34
34
  items: DcbQueryItem[];
35
35
  }
36
36
 
37
- export type CommitCallback = (commit: Record<string, unknown>) => void;
37
+ export interface Commit {
38
+ commitId: number;
39
+ committedAt: number;
40
+ streamName: string;
41
+ streamVersion: number;
42
+ events: any[];
43
+ [metadata: string]: unknown;
44
+ }
45
+
46
+ export type CommitCallback = (commit: Commit) => void;
38
47
 
39
48
  export interface Serializer {
40
49
  serialize(document: any): string | Buffer;
@@ -231,10 +240,10 @@ export class EventStore extends EventEmitter {
231
240
  expectedVersion?: number | CommitCondition,
232
241
  metadata?: Record<string, unknown>,
233
242
  callback?: CommitCallback
234
- ): void;
235
- commit(streamName: string, events: any | any[], expectedVersion: number | CommitCondition, callback: CommitCallback): void;
236
- commit(streamName: string, events: any | any[], metadata: Record<string, unknown>, callback?: CommitCallback): void;
237
- commit(streamName: string, events: any | any[], callback: CommitCallback): void;
243
+ ): Commit;
244
+ commit(streamName: string, events: any | any[], expectedVersion: number | CommitCondition, callback: CommitCallback): Commit;
245
+ commit(streamName: string, events: any | any[], metadata: Record<string, unknown>, callback?: CommitCallback): Commit;
246
+ commit(streamName: string, events: any | any[], callback: CommitCallback): Commit;
238
247
 
239
248
  getConsumer(streamName: string, identifier: string, initialState?: Record<string, unknown>, since?: number): Consumer;
240
249
  getConsumer(identifier: string): Consumer | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "event-storage",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "type": "module",
5
5
  "description": "An optimized embedded event store for node.js",
6
6
  "keywords": [
@@ -44,6 +44,7 @@
44
44
  "src/Partition*.js",
45
45
  "src/Storage*.js",
46
46
  "src/FileHandlePool.js",
47
+ "src/SyncScheduler.js",
47
48
  "src/Watcher*.js",
48
49
  "src/Clock*.js",
49
50
  "src/Index/*.js",
package/src/EventStore.js CHANGED
@@ -516,6 +516,7 @@ class EventStore extends events.EventEmitter {
516
516
  * stream version number, or a {@link CommitCondition} obtained from {@link EventStore#query}.
517
517
  * @param {object} [metadata] The commit metadata to use as base. Useful for replication and adding storage metadata.
518
518
  * @param {function} [callback] A function that will be executed when all events have been committed.
519
+ * @returns {object} The commit, which already holds its position in the log. The events are not durable before the callback fires.
519
520
  * @throws {OptimisticConcurrencyError} if the stream is not at the expected version, or if a
520
521
  * {@link CommitCondition} was provided and conflicting events have been committed since it was obtained.
521
522
  */
@@ -580,6 +581,7 @@ class EventStore extends events.EventEmitter {
580
581
  commit.events.push(event);
581
582
  this.storage.write(storedEvent, commitVersion !== events.length ? undefined : commitCallback);
582
583
  }
584
+ return commit;
583
585
  }
584
586
 
585
587
  /**
@@ -39,8 +39,8 @@ class EventStream extends stream.Readable {
39
39
  if (eventStore.streams[name]) {
40
40
  this.streamIndex = eventStore.streams[name].index;
41
41
  this.minRevision = normalizeRevision(minRevision, this.streamIndex.length);
42
- this.maxRevision = normalizeRevision(maxRevision, this.streamIndex.length);
43
- this.version = normalizeMaxRevision(this.streamIndex.length, maxRevision);
42
+ this.maxRevision = normalizeMaxRevision(this.streamIndex.length, maxRevision);
43
+ this.version = this.maxRevision;
44
44
  this._iterator = null;
45
45
  this.fetch = () => eventStore.storage.readRange(this.minRevision, this.maxRevision, this.streamIndex, raw);
46
46
  } else {
@@ -66,8 +66,8 @@ class EventStream extends stream.Readable {
66
66
  * @returns {EventStream}
67
67
  */
68
68
  until(revision) {
69
- this.maxRevision = normalizeRevision(revision, this.streamIndex.length);
70
- this.version = normalizeMaxRevision(this.streamIndex.length, this.maxRevision);
69
+ this.maxRevision = normalizeMaxRevision(this.streamIndex.length, revision);
70
+ this.version = this.maxRevision;
71
71
  return this;
72
72
  }
73
73
 
@@ -1,10 +1,14 @@
1
1
  import fs from 'fs';
2
+ import { syncFile, ignoreDeletedFile } from './utils/fsUtil.js';
2
3
 
3
4
  /**
4
5
  * LRU pool for file descriptors shared across multiple file-backed objects.
5
6
  *
6
7
  * Targets are expected to expose `fileName` and `fileMode` and may implement
7
8
  * `onBeforeClose(fd, evicted)` to flush state before their descriptor closes.
9
+ *
10
+ * A descriptor that is being synced is pinned: evicting it removes it from the pool right away, but only closes it once
11
+ * the sync is done. Otherwise the OS could reuse the number for another file meanwhile, which the sync would then hit.
8
12
  */
9
13
  class FileHandlePool {
10
14
 
@@ -29,7 +33,7 @@ class FileHandlePool {
29
33
 
30
34
  this.evictLeastRecentlyUsedIfNeeded(target);
31
35
  const fd = fs.openSync(target.fileName, target.fileMode);
32
- this.handles.set(target, { fd });
36
+ this.handles.set(target, { fd, pins: 0, removed: false });
33
37
  return fd;
34
38
  }
35
39
 
@@ -55,11 +59,50 @@ class FileHandlePool {
55
59
  target.onBeforeClose?.(handle.fd, evicted);
56
60
  } finally {
57
61
  this.handles.delete(target);
58
- fs.closeSync(handle.fd);
62
+ handle.removed = true;
63
+ if (handle.pins === 0) {
64
+ fs.closeSync(handle.fd);
65
+ }
59
66
  }
60
67
  return true;
61
68
  }
62
69
 
70
+ /**
71
+ * Sync the target's file to disk. An fsync covers all data written to the file through any descriptor, so the
72
+ * pooled one is used if the file is open, which saves opening and closing one just for the sync. A file that is not
73
+ * open in the pool is synced through its own descriptor, without displacing another one. A file deleted meanwhile
74
+ * needs no sync.
75
+ * Without a callback this blocks until the file is on disk. With a callback it syncs in the background and pins the
76
+ * descriptor until then.
77
+ *
78
+ * @param {object} target
79
+ * @param {function(Error|null)} [callback]
80
+ */
81
+ sync(target, callback) {
82
+ const handle = this.handles.get(target);
83
+ if (typeof callback !== 'function') {
84
+ try {
85
+ if (handle) fs.fsyncSync(handle.fd);
86
+ else syncFile(target.fileName);
87
+ } catch (error) {
88
+ ignoreDeletedFile(error);
89
+ }
90
+ return;
91
+ }
92
+ if (!handle) {
93
+ syncFile(target.fileName, error => callback(error && error.code !== 'ENOENT' ? error : null));
94
+ return;
95
+ }
96
+ handle.pins++;
97
+ fs.fsync(handle.fd, error => {
98
+ handle.pins--;
99
+ if (handle.removed && handle.pins === 0) {
100
+ fs.closeSync(handle.fd);
101
+ }
102
+ callback(error || null);
103
+ });
104
+ }
105
+
63
106
  /**
64
107
  * @param {object} target
65
108
  * @returns {void}
@@ -1,9 +1,9 @@
1
1
  import fs from 'fs';
2
- import path from 'path';
3
2
  import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC, CHUNK_CAPACITY, createChunk } from './ReadableIndex.js';
4
3
  import { assert, assertEqual } from '../utils/util.js';
5
4
  import { buildMetadataHeader } from '../utils/metadataUtil.js';
6
- import { ensureDirectory, syncDirectory } from '../utils/fsUtil.js';
5
+ import { ensureDirectory } from '../utils/fsUtil.js';
6
+ import SyncScheduler from '../SyncScheduler.js';
7
7
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
8
8
 
9
9
  /**
@@ -27,6 +27,7 @@ class WritableIndex extends ReadableIndex {
27
27
  * @param {number} [options.writeBufferSize] The amount of bytes of unwritten entries after which they are flushed. Default 4096.
28
28
  * @param {number} [options.flushDelay] How many ms to delay the write buffer flush to optimize throughput. Default 100.
29
29
  * @param {object} [options.metadata] An object containing the metadata information for this index. Will be written on initial creation and checked on subsequent openings.
30
+ * @param {SyncScheduler} [options.syncScheduler] Syncs the directory of a new index file, shared by all files of a storage. Defaults to one for this index, configured by `syncOnFlush` and `syncInterval`.
30
31
  */
31
32
  constructor(name = '.index', options = {}) {
32
33
  ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
@@ -54,7 +55,7 @@ class WritableIndex extends ReadableIndex {
54
55
  this.flushCallbacks = [];
55
56
  this.flushDelay = options.flushDelay >>> 0; // jshint ignore:line
56
57
  this.syncOnFlush = !!options.syncOnFlush;
57
- this.syncNewFile = this.syncOnFlush || options.syncInterval > 0;
58
+ this.syncScheduler = options.syncScheduler || new SyncScheduler({ syncOnFlush: options.syncOnFlush, syncInterval: options.syncInterval });
58
59
  }
59
60
 
60
61
  /**
@@ -114,22 +115,24 @@ class WritableIndex extends ReadableIndex {
114
115
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
115
116
  fs.writeSync(this.getFileHandle(), metadataBuffer, 0, metadataBuffer.byteLength, 0);
116
117
  this.headerSize = metadataBuffer.byteLength;
117
- if (this.syncNewFile) {
118
- syncDirectory(path.dirname(this.fileName));
119
- }
118
+ this.syncScheduler.created(this);
120
119
  }
121
120
 
122
121
  /**
123
- * Flush pending buffered writes before the pool closes the descriptor.
122
+ * Flush pending buffered writes before the pool closes the descriptor. Closing the index also syncs it, an eviction
123
+ * does not.
124
124
  *
125
125
  * @param {number} fd
126
+ * @param {boolean} evicted
126
127
  */
127
- onBeforeClose(fd) {
128
+ onBeforeClose(fd, evicted) {
128
129
  if (!this.flushCallbacks) {
129
130
  return;
130
131
  }
131
132
  this.flush();
132
- fs.fdatasyncSync(fd);
133
+ if (!evicted) {
134
+ fs.fdatasyncSync(fd);
135
+ }
133
136
  }
134
137
 
135
138
  /**
@@ -1,7 +1,7 @@
1
1
  import EventStream from './EventStream.js';
2
2
  import {assert} from './utils/util.js';
3
3
  import {intersect, normalizeSelector, union} from './utils/indexUtil.js';
4
- import {normalizeRevision} from './utils/apiHelpers.js';
4
+ import {normalizeMaxRevision, normalizeRevision} from './utils/apiHelpers.js';
5
5
 
6
6
  /**
7
7
  * JoinEventStream is a virtual stream over one or multiple physical stream indexes.
@@ -37,7 +37,7 @@ class JoinEventStream extends EventStream {
37
37
  this.selector = normalizeSelector(selector);
38
38
  this.streamIndex = eventStore.storage.index;
39
39
  this.minRevision = normalizeRevision(minRevision, eventStore.length);
40
- this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
40
+ this.maxRevision = normalizeMaxRevision(eventStore.length, maxRevision);
41
41
  this.version = this.streamIndex.length;
42
42
 
43
43
  this.fetch = () => this.iterateDocuments();
@@ -84,6 +84,13 @@ class JoinEventStream extends EventStream {
84
84
  * @returns {Generator<object|{ buffer: Buffer, time64: number, sequenceNumber: number }>}
85
85
  */
86
86
  * iterateDocuments() {
87
+ // Revisions counted from the end are already resolved and the upper bound is clamped to the end, so anything
88
+ // below 1 here lies before the first event. A range that starts outside the store is empty, like for a single
89
+ // stream. Clamping the start too would turn a read from beyond the end into a backwards read.
90
+ const length = this.eventStore.length;
91
+ if (this.minRevision < 1 || this.minRevision > length || this.maxRevision < 1) {
92
+ return;
93
+ }
87
94
  const forwards = this.minRevision <= this.maxRevision;
88
95
  for (const entry of this.resolveSelectorRange(this.selector)) {
89
96
  const event = this.eventStore.storage.readFrom(entry.partition, entry.position, entry.size, this.raw, !forwards);
@@ -1,10 +1,10 @@
1
1
  import fs from 'fs';
2
- import path from 'path';
3
2
  import ReadablePartition, { CorruptFileError, HEADER_MAGIC, DOCUMENT_ALIGNMENT, DOCUMENT_SEPARATOR, DOCUMENT_HEADER_SIZE, DOCUMENT_FOOTER_SIZE } from './ReadablePartition.js';
4
3
  import { assert, alignTo } from '../utils/util.js';
5
4
  import { buildMetadataHeader } from '../utils/metadataUtil.js';
6
- import { ensureDirectory, syncDirectory } from '../utils/fsUtil.js';
5
+ import { ensureDirectory } from '../utils/fsUtil.js';
7
6
  import Clock from '../Clock.js';
7
+ import SyncScheduler from '../SyncScheduler.js';
8
8
 
9
9
  const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
10
10
  const DOCUMENT_PAD = ' '.repeat(DOCUMENT_ALIGNMENT);
@@ -24,6 +24,7 @@ class WritablePartition extends ReadablePartition {
24
24
  * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
25
25
  * @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
26
26
  * @param {number} [config.syncInterval] Call fsync at most every this many ms and only invoke write callbacks after it. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
27
+ * @param {SyncScheduler} [config.syncScheduler] The scheduler that syncs the flushes, shared by all files of a storage. Defaults to one for this partition, configured by `syncOnFlush` and `syncInterval`.
27
28
  * @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.
28
29
  * @param {object} [config.metadata] A metadata object that will be written to the file header.
29
30
  * @param {typeof Clock} [config.clock] The constructor to a clock interface
@@ -47,10 +48,7 @@ class WritablePartition extends ReadablePartition {
47
48
  this.fileMode = 'a+';
48
49
  this.writeBufferSize = config.writeBufferSize >>> 0; // jshint ignore:line
49
50
  this.maxWriteBufferDocuments = config.maxWriteBufferDocuments >>> 0; // jshint ignore:line
50
- this.syncOnFlush = !!config.syncOnFlush;
51
- this.syncInterval = this.syncOnFlush ? 0 : config.syncInterval >>> 0; // jshint ignore:line
52
- this.syncTimeout = null;
53
- this.syncCallbacks = [];
51
+ this.syncScheduler = config.syncScheduler || new SyncScheduler({ syncOnFlush: config.syncOnFlush, syncInterval: config.syncInterval >>> 0 }); // jshint ignore:line
54
52
  this.dirtyReads = !!config.dirtyReads;
55
53
  this.metadata = config.metadata;
56
54
  assert(typeof(config.clock.prototype) === 'object' && typeof(config.clock.prototype.time) === 'function', 'Clock needs to implement the method time()');
@@ -99,8 +97,11 @@ class WritablePartition extends ReadablePartition {
99
97
  * @returns void
100
98
  */
101
99
  close() {
102
- if (this.syncTimeout !== null) {
103
- this.sync();
100
+ if (this.writeBuffer) {
101
+ this.flush();
102
+ }
103
+ if (this.syncScheduler.isWaiting(this)) {
104
+ this.syncScheduler.run();
104
105
  }
105
106
  super.close();
106
107
  if (this.writeBuffer) {
@@ -112,17 +113,20 @@ class WritablePartition extends ReadablePartition {
112
113
  }
113
114
 
114
115
  /**
115
- * Flush pending buffered writes before the pool closes the descriptor.
116
+ * Flush pending buffered writes before the pool closes the descriptor. Closing the partition also syncs it. An
117
+ * eviction does not: a flush waiting for a sync is synced by the scheduler, through its own descriptor if needed.
116
118
  *
117
119
  * @param {number} fd
120
+ * @param {boolean} evicted
118
121
  */
119
- onBeforeClose(fd) {
122
+ onBeforeClose(fd, evicted) {
120
123
  if (!this.writeBuffer) {
121
124
  return;
122
125
  }
123
126
  this.flush();
124
- fs.fsyncSync(fd);
125
- this.invokeSyncCallbacks();
127
+ if (!evicted) {
128
+ fs.fsyncSync(fd);
129
+ }
126
130
  }
127
131
 
128
132
  /**
@@ -135,9 +139,7 @@ class WritablePartition extends ReadablePartition {
135
139
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
136
140
  fs.writeFileSync(this.fileName, metadataBuffer);
137
141
  this.headerSize = metadataBuffer.byteLength;
138
- if (this.syncOnFlush || this.syncInterval > 0) {
139
- syncDirectory(path.dirname(this.fileName));
140
- }
142
+ this.syncScheduler.created(this);
141
143
  }
142
144
 
143
145
  /**
@@ -154,62 +156,30 @@ class WritablePartition extends ReadablePartition {
154
156
  return false;
155
157
  }
156
158
 
157
- const fd = this.getFileHandle();
158
- fs.writeSync(fd, this.writeBuffer, 0, this.writeBufferCursor);
159
- if (this.syncOnFlush) {
160
- fs.fsyncSync(fd);
161
- }
162
-
159
+ fs.writeSync(this.getFileHandle(), this.writeBuffer, 0, this.writeBufferCursor);
163
160
  this.writeBufferCursor = 0;
164
161
  this.writeBufferDocuments = 0;
165
162
  const callbacks = this.flushCallbacks;
166
163
  this.flushCallbacks = [];
167
- if (this.syncInterval > 0) {
168
- this.scheduleSync(callbacks);
169
- } else {
170
- for (let i = 0; i < callbacks.length; i++) callbacks[i]();
171
- }
164
+ this.syncScheduler.flushed(this, callbacks);
172
165
 
173
166
  return true;
174
167
  }
175
168
 
176
169
  /**
177
- * Group commit: many flushes share one fsync, and their callbacks only fire once the data is on disk.
178
- *
179
- * @private
180
- * @param {Array<function>} callbacks
181
- */
182
- scheduleSync(callbacks) {
183
- for (let i = 0; i < callbacks.length; i++) this.syncCallbacks.push(callbacks[i]);
184
- if (this.syncTimeout === null) {
185
- this.syncTimeout = setTimeout(() => this.sync(), this.syncInterval);
186
- }
187
- }
188
-
189
- /**
190
- * Flush the write buffer and fsync the file, then invoke all callbacks waiting for durability.
170
+ * Flush the write buffer and fsync the file, then invoke all callbacks waiting for durability, including those of
171
+ * other files of the same storage.
191
172
  *
192
173
  * @api
193
174
  */
194
175
  sync() {
195
176
  if (this.isOpen()) {
196
177
  this.flush();
197
- fs.fsyncSync(this.getFileHandle());
198
178
  }
199
- if (this.syncTimeout !== null) {
200
- clearTimeout(this.syncTimeout);
201
- this.syncTimeout = null;
179
+ this.syncScheduler.run();
180
+ if (this.isOpen()) {
181
+ this.fileHandlePool.sync(this);
202
182
  }
203
- this.invokeSyncCallbacks();
204
- }
205
-
206
- /**
207
- * @private
208
- */
209
- invokeSyncCallbacks() {
210
- const callbacks = this.syncCallbacks;
211
- this.syncCallbacks = [];
212
- for (let i = 0; i < callbacks.length; i++) callbacks[i]();
213
183
  }
214
184
 
215
185
  /**
@@ -294,9 +264,7 @@ class WritablePartition extends ReadablePartition {
294
264
  this.writeMetaBuffer.writeUInt32BE(dataSize, 0);
295
265
  bytesWritten += fs.writeSync(fd, this.writeMetaBuffer, 0, 4);
296
266
  bytesWritten += fs.writeSync(fd, DOCUMENT_SEPARATOR);
297
- if (typeof callback === 'function') {
298
- process.nextTick(callback);
299
- }
267
+ this.syncScheduler.flushed(this, typeof callback === 'function' ? [() => process.nextTick(callback)] : []);
300
268
  return bytesWritten;
301
269
  }
302
270
 
@@ -6,6 +6,7 @@ import ReadableStorage from './ReadableStorage.js';
6
6
  import StorageLock, { StorageLockedError, LOCK_THROW, LOCK_RECLAIM, LOCK_AUTO } from './StorageLock.js';
7
7
  import { assert } from '../utils/util.js';
8
8
  import { ensureDirectory } from '../utils/fsUtil.js';
9
+ import SyncScheduler from '../SyncScheduler.js';
9
10
  import { matches, buildMetadataForMatcher, buildMatcherFromMetadata } from '../utils/metadataUtil.js';
10
11
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
11
12
 
@@ -40,7 +41,7 @@ class WritableStorage extends ReadableStorage {
40
41
  * @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
41
42
  * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
42
43
  * @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).
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).
44
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.
45
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.
46
47
  * @param {object} [config.indexOptions] An options object that should be passed to all indexes on construction.
@@ -61,9 +62,13 @@ class WritableStorage extends ReadableStorage {
61
62
  };
62
63
  config = Object.assign(defaults, config);
63
64
  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);
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;
65
69
  ensureDirectory(config.dataDirectory);
66
70
  super(storageName, config);
71
+ this.syncScheduler = syncScheduler;
67
72
 
68
73
  this.lockFile = path.resolve(this.dataDirectory, this.storageFile + '.lock');
69
74
  this.storageLock = new StorageLock(this.lockFile, this.storageFile, config.lock);
@@ -257,9 +262,11 @@ class WritableStorage extends ReadableStorage {
257
262
 
258
263
  /**
259
264
  * @inheritDoc
260
- * Unlocks the storage, then delegates to the parent close().
265
+ * Syncs everything written as configured, unlocks the storage, then delegates to the parent close().
261
266
  */
262
267
  close() {
268
+ this.forEachPartition(partition => partition.flush());
269
+ this.syncScheduler.run();
263
270
  if (this.locked) {
264
271
  this.unlock();
265
272
  }
@@ -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;
@@ -49,21 +49,92 @@ function writeFileAtomic(fileName, data, tmpFileName = fileName + '.tmp') {
49
49
  }
50
50
 
51
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.
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.
54
65
  *
55
66
  * @param {string} dirName
67
+ * @param {function(Error|null)} [callback] Always called without an error.
56
68
  */
57
- function syncDirectory(dirName) {
58
- let fd;
69
+ function syncDirectory(dirName, callback) {
70
+ if (typeof callback === 'function') {
71
+ syncPath(dirName, 'r', () => callback(null));
72
+ return;
73
+ }
59
74
  try {
60
- fd = fs.openSync(dirName, 'r');
61
- fs.fsyncSync(fd);
75
+ syncPath(dirName, 'r');
62
76
  } catch (e) {
63
- } finally {
64
- if (fd !== undefined) {
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 {
65
91
  fs.closeSync(fd);
66
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
+ });
67
138
  }
68
139
  }
69
140
 
@@ -206,5 +277,8 @@ export {
206
277
  isSameOrParentDirectory,
207
278
  safeUnlink,
208
279
  syncDirectory,
280
+ syncFile,
281
+ ignoreDeletedFile,
282
+ parallel,
209
283
  writeFileAtomic
210
284
  };