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.
@@ -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}
@@ -23,7 +23,7 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
23
23
  */
24
24
  watchFileFilter(filename) {
25
25
  if (!filename) {
26
- return this.syncOnMissingWatchFilename && this.readFileLength() !== this.data.length;
26
+ return this.syncOnMissingWatchFilename && this.readFileLength() !== this.length;
27
27
  }
28
28
  return filename === this.name;
29
29
  }
@@ -37,9 +37,9 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
37
37
  if (!this.isOpen()) {
38
38
  return;
39
39
  }
40
- const prevLength = this.data.length;
40
+ const prevLength = this.length;
41
41
  const newLength = this.readFileLength();
42
- this.data.length = newLength;
42
+ this.setLength(newLength);
43
43
  if (newLength > prevLength) {
44
44
  this.emit('append', prevLength, newLength);
45
45
  }
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs';
2
+ import os from 'os';
2
3
  import events from 'events';
3
4
  import Entry, { assertValidEntryClass } from '../IndexEntry.js';
4
5
  import FileHandlePool from '../FileHandlePool.js';
@@ -9,6 +10,35 @@ import { resolvePath } from "../utils/fsUtil.js";
9
10
  // node-event-store-index V01
10
11
  const HEADER_MAGIC = "nesidx01";
11
12
 
13
+ // Entries per in-memory chunk. A full chunk of default entries is 64 KiB, so loading one is a single small read.
14
+ const CHUNK_CAPACITY = 4096;
15
+ const MIN_CHUNK_ALLOCATION = 8;
16
+ const LITTLE_ENDIAN_HOST = os.endianness() === 'LE';
17
+
18
+ /**
19
+ * Create a chunk of raw entry bytes with room for `capacity` entries, optionally copying the entries of a smaller chunk.
20
+ * A dedicated ArrayBuffer keeps the Uint32Array view aligned, which a pooled Buffer does not guarantee.
21
+ *
22
+ * @param {number} entrySize
23
+ * @param {number} count The amount of entries the chunk needs room for. Rounded up to the next power of two.
24
+ * @param {object} [from] The chunk to copy the valid entries from.
25
+ * @returns {{buffer: Buffer, words: Uint32Array, capacity: number, filled: number}}
26
+ */
27
+ function createChunk(entrySize, count, from) {
28
+ let capacity = MIN_CHUNK_ALLOCATION;
29
+ while (capacity < count) {
30
+ capacity *= 2;
31
+ }
32
+ capacity = Math.min(capacity, CHUNK_CAPACITY);
33
+ const arrayBuffer = new ArrayBuffer(capacity * entrySize);
34
+ const chunk = { buffer: Buffer.from(arrayBuffer), words: new Uint32Array(arrayBuffer), capacity, filled: 0 };
35
+ if (from) {
36
+ from.buffer.copy(chunk.buffer, 0, 0, from.filled * entrySize);
37
+ chunk.filled = from.filled;
38
+ }
39
+ return chunk;
40
+ }
41
+
12
42
  class CorruptedIndexError extends Error {}
13
43
 
14
44
  /**
@@ -40,7 +70,6 @@ class ReadableIndex extends events.EventEmitter {
40
70
  * @param {object} [options] An object with additional index options.
41
71
  * @param {typeof EntryInterface} [options.EntryClass] The entry class to use for index items. Must implement the EntryInterface methods.
42
72
  * @param {string} [options.dataDirectory] The directory to store the index file in. Default '.'.
43
- * @param {number} [options.writeBufferSize] The number of bytes to use for the write buffer. Default 4096.
44
73
  * @param {number} [options.flushDelay] How many ms to delay the write buffer flush to optimize throughput. Default 100.
45
74
  * @param {object} [options.metadata] An object containing the metadata information for this index. Will be written on initial creation and checked on subsequent openings.
46
75
  * @param {object} [options.fileHandlePool] Shared file-handle pool used to reopen evicted handles on demand.
@@ -66,15 +95,18 @@ class ReadableIndex extends events.EventEmitter {
66
95
  * @param {object} options
67
96
  */
68
97
  initialize(options) {
69
- /* @type Array<Entry> */
70
- this.data = [];
98
+ // Entries are kept as raw entry bytes in chunks of CHUNK_CAPACITY, which are read lazily from the file.
99
+ // Only the first `filled` entries of a chunk are valid, the rest is room for appending.
100
+ this.chunks = [];
101
+ this.entryCount = 0;
102
+ // Entries with the default binary layout are read straight from 32-bit words, without creating objects.
103
+ this.wordsPerEntry = (LITTLE_ENDIAN_HOST && options.EntryClass.fromBuffer === Entry.fromBuffer) ? options.EntryClass.size / 4 : 0;
71
104
  this.opened = false;
72
105
  this.fileMode = 'r';
73
106
  this.fileHandlePool = options.fileHandlePool || new FileHandlePool();
74
107
  this.EntryClass = options.EntryClass;
75
108
  this.dataDirectory = options.dataDirectory;
76
109
  this.fileName = resolvePath(options.dataDirectory, this.name);
77
- this.readBuffer = Buffer.allocUnsafe(Math.max(options.EntryClass.size, options.writeBufferSize > 0 ? options.writeBufferSize : 4096));
78
110
 
79
111
  if (options.metadata) {
80
112
  this.metadata = Object.assign({entryClass: options.EntryClass.name, entrySize: options.EntryClass.size}, options.metadata);
@@ -103,7 +135,7 @@ class ReadableIndex extends events.EventEmitter {
103
135
  * @returns {number}
104
136
  */
105
137
  get length() {
106
- return this.data.length;
138
+ return this.entryCount;
107
139
  }
108
140
 
109
141
  /**
@@ -168,14 +200,9 @@ class ReadableIndex extends events.EventEmitter {
168
200
  }
169
201
  this.opened = this.getFileHandle() !== null;
170
202
 
171
- this.readUntil = -1;
172
-
173
203
  const length = this.readFileLength();
174
- if (length > 0) {
175
- this.data = new Array(length);
176
- // Read last item to get the index started
177
- this.read(length);
178
- }
204
+ this.setLength(0);
205
+ this.setLength(length);
179
206
 
180
207
  return true;
181
208
  }
@@ -251,85 +278,100 @@ class ReadableIndex extends events.EventEmitter {
251
278
  * @api
252
279
  */
253
280
  close() {
254
- this.data = [];
255
- this.readUntil = -1;
256
- this.readBuffer.fill(0);
281
+ // Evict first, so a writer can still flush its unwritten entries from memory.
257
282
  this.fileHandlePool.evict(this, false);
283
+ this.setLength(0);
258
284
  this.opened = false;
259
285
  }
260
286
 
261
287
  /**
262
- * Read a single index entry from the given index position.
263
- * Will prevent reading if the entry has already been read sequentially from the start.
288
+ * Return the chunk that holds the given entry, reading the missing part of it from file if necessary.
264
289
  *
265
290
  * @private
266
- * @param {number} index
267
- * @returns {Entry} The index entry at the given position.
291
+ * @param {number} index The 0-based entry number.
292
+ * @returns {object|null} The chunk or null if the entry could not be read.
268
293
  */
269
- read(index) {
270
- index = Number(index) - 1;
294
+ chunkFor(index) {
295
+ const chunkIndex = Math.floor(index / CHUNK_CAPACITY);
296
+ const chunkStart = chunkIndex * CHUNK_CAPACITY;
297
+ let chunk = this.chunks[chunkIndex];
298
+ if (chunk && index - chunkStart < chunk.filled) {
299
+ return chunk;
300
+ }
271
301
 
272
- const fd = this.getFileHandle();
273
- fs.readSync(fd, this.readBuffer, 0, this.EntryClass.size, this.headerSize + index * this.EntryClass.size);
274
- if (index === this.readUntil + 1) {
275
- this.readUntil++;
302
+ const count = Math.min(CHUNK_CAPACITY, this.length - chunkStart);
303
+ if (!chunk || chunk.capacity < count) {
304
+ chunk = this.chunks[chunkIndex] = createChunk(this.EntryClass.size, count, chunk);
276
305
  }
277
- this.data[index] = this.EntryClass.fromBuffer(this.readBuffer);
306
+ const entrySize = this.EntryClass.size;
307
+ const bytesRead = fs.readSync(this.getFileHandle(), chunk.buffer, chunk.filled * entrySize, (count - chunk.filled) * entrySize,
308
+ this.headerSize + (chunkStart + chunk.filled) * entrySize);
309
+ chunk.filled += Math.floor(bytesRead / entrySize);
310
+ return index - chunkStart < chunk.filled ? chunk : null;
311
+ }
278
312
 
279
- return this.data[index];
313
+ /**
314
+ * Set the amount of entries in the index. Additional entries are read from the file on access,
315
+ * entries beyond the new length are dropped from memory.
316
+ *
317
+ * @protected
318
+ * @param {number} length
319
+ */
320
+ setLength(length) {
321
+ if (length >= this.entryCount) {
322
+ this.entryCount = length;
323
+ return;
324
+ }
325
+ this.entryCount = length;
326
+ const chunkCount = Math.ceil(length / CHUNK_CAPACITY);
327
+ this.chunks.length = Math.min(this.chunks.length, chunkCount);
328
+ const lastChunk = this.chunks[chunkCount - 1];
329
+ if (lastChunk) {
330
+ lastChunk.filled = Math.min(lastChunk.filled, length - (chunkCount - 1) * CHUNK_CAPACITY);
331
+ }
280
332
  }
281
333
 
282
334
  /**
283
- * Read a range of entries from disk. This method will not do any range checks.
284
- * It will however optimize to prevent reading entries that have already been read sequentially from start.
335
+ * Create the entry object for a 0-based entry number. With `into`, the default entry layout fills that
336
+ * object instead of allocating a new one.
285
337
  *
286
338
  * @private
287
- * @param {number} from The 1-based index position from where to read from (inclusive).
288
- * @param {number} until The 1-based index position until which to read to (inclusive).
289
- * @returns {Array<Entry>|boolean} An array of the index entries in the given range or false on error.
339
+ * @param {number} index The 0-based entry number.
340
+ * @param {Entry|null} [into]
341
+ * @returns {Entry|boolean} The entry or false if it could not be read.
290
342
  */
291
- readRange(from, until) {
292
- if (until === from) {
293
- return [this.read(from)];
343
+ entryAt(index, into = null) {
344
+ const chunk = this.chunkFor(index);
345
+ if (!chunk) {
346
+ return false;
294
347
  }
295
-
296
- from--;
297
- until--;
298
-
299
- const readFrom = Math.max(this.readUntil + 1, from);
300
- const amount = (until - readFrom + 1);
301
-
302
- const bufferSize = amount * this.EntryClass.size;
303
- const readBuffer = bufferSize <= this.readBuffer.byteLength
304
- ? this.readBuffer
305
- : Buffer.allocUnsafe(bufferSize);
306
- const fd = this.getFileHandle();
307
- let readSize = fs.readSync(fd, readBuffer, 0, bufferSize, this.headerSize + readFrom * this.EntryClass.size);
308
- let index = 0;
309
- while (index < amount && readSize > 0) {
310
- this.data[index + readFrom] = this.EntryClass.fromBuffer(readBuffer, index * this.EntryClass.size);
311
- readSize -= this.EntryClass.size;
312
- index++;
348
+ const position = index % CHUNK_CAPACITY;
349
+ if (!this.wordsPerEntry) {
350
+ return this.EntryClass.fromBuffer(chunk.buffer, position * this.EntryClass.size);
313
351
  }
314
- if (from <= this.readUntil + 1) {
315
- this.readUntil = Math.max(this.readUntil, until);
352
+ const words = chunk.words;
353
+ const word = position * this.wordsPerEntry;
354
+ if (!into) {
355
+ return new this.EntryClass(words[word], words[word + 1], words[word + 2], words[word + 3]);
316
356
  }
317
-
318
- return this.data.slice(from, until + 1);
357
+ into[0] = words[word];
358
+ into[1] = words[word + 1];
359
+ into[2] = words[word + 2];
360
+ into[3] = words[word + 3];
361
+ return into;
319
362
  }
320
363
 
321
364
  /**
322
- * Read all index entries. Equal to range(1, index.length) with the exception that this returns
323
- * an empty array if the index is empty.
365
+ * Get the sequence number of an entry without creating an entry object for the default entry layout.
324
366
  *
325
- * @api
326
- * @returns {Array<EntryInterface>} An array of all index entries.
367
+ * @param {number} index The 0-based entry number.
368
+ * @returns {number}
327
369
  */
328
- all() {
329
- if (this.length === 0) {
330
- return [];
370
+ numberAt(index) {
371
+ if (!this.wordsPerEntry) {
372
+ return this.entryAt(index).number;
331
373
  }
332
- return this.range(1, this.length);
374
+ return this.chunkFor(index).words[(index % CHUNK_CAPACITY) * this.wordsPerEntry];
333
375
  }
334
376
 
335
377
  /**
@@ -345,55 +387,58 @@ class ReadableIndex extends events.EventEmitter {
345
387
  return false;
346
388
  }
347
389
 
348
- if (this.data[index - 1]) {
349
- return this.data[index - 1];
350
- }
351
-
352
- return this.read(index);
390
+ return this.entryAt(index - 1);
353
391
  }
354
392
 
355
393
  /**
356
- * Check if the given range is within the bounds of the index.
394
+ * Iterate the index entries between two positions, without loading them all at once.
395
+ * If `from` is greater than `until`, the entries are iterated backwards.
396
+ *
397
+ * For the default entry layout one entry object is reused for the whole iteration, so read its fields
398
+ * before advancing and do not keep it. Calling `next(number)` on the iterator skips ahead to the first
399
+ * entry whose sequence number does not come before `number` in the iteration direction.
357
400
  *
358
401
  * @api
359
- * @param {number} from The 1-based index position from where to get entries from (inclusive).
360
- * @param {number} until The 1-based index position until where to get entries to (inclusive).
361
- * @returns {boolean}
402
+ * @param {number} [from=1] The 1-based index position to start at (inclusive). If < 0 counts from the end.
403
+ * @param {number} [until=-1] The 1-based index position to end at (inclusive). If < 0 counts from the end.
404
+ * @returns {Generator<Entry>} An empty iteration if a position is out of bounds.
362
405
  */
363
- validRange(from, until) {
364
- if (from < 1 || from > this.length) {
365
- return false;
406
+ *range(from = 1, until = -1) {
407
+ from = wrapAndCheck(from, this.length);
408
+ until = wrapAndCheck(until, this.length);
409
+ if (from <= 0 || until <= 0) {
410
+ return;
411
+ }
412
+ const step = from <= until ? 1 : -1;
413
+ const end = until + step;
414
+ const entry = this.wordsPerEntry ? new this.EntryClass(0, 0) : null;
415
+ let position = from;
416
+ while (position !== end) {
417
+ const target = yield this.entryAt(position - 1, entry);
418
+ position += step;
419
+ if (target !== undefined && position !== end && (this.numberAt(position - 1) - target) * step < 0) {
420
+ position = this.skipTo(target, position, end, step);
421
+ }
366
422
  }
367
- return (until >= from && until <= this.length);
368
423
  }
369
424
 
370
425
  /**
371
- * Get a range of index entries.
426
+ * Iterate all index entries. Same as `range(1, -1)`, with the same reuse of the entry object.
372
427
  *
373
428
  * @api
374
- * @param {number} from The 1-based index position from where to get entries from (inclusive). If < 0 will start at that position from end.
375
- * @param {number} [until=-1] The 1-based index position until where to get entries to (inclusive). If < 0 will get until that position from the end. Defaults to this.length.
376
- * @returns {Array<Entry>|boolean} An array of entries for the given range or false on error.
429
+ * @returns {Generator<Entry>}
377
430
  */
378
- range(from, until = -1) {
379
- from = wrapAndCheck(from, this.length);
380
- until = wrapAndCheck(until, this.length);
381
-
382
- if (from <= 0 || until < from) {
383
- return false;
384
- }
385
-
386
- const readFrom = Math.max(this.readUntil + 1, from);
387
- let readUntil = until;
388
- while (readUntil >= readFrom && this.data[readUntil - 1]) {
389
- readUntil--;
390
- }
391
-
392
- if (readFrom <= readUntil) {
393
- this.readRange(readFrom, readUntil);
394
- }
431
+ all() {
432
+ return this.range(1, -1);
433
+ }
395
434
 
396
- return this.data.slice(from - 1, until);
435
+ /**
436
+ * @private
437
+ * @returns {number} The first position from `position` towards `end` whose number does not come before `target`.
438
+ */
439
+ skipTo(target, position, end, step) {
440
+ const found = step > 0 ? this.find(target, true) : this.find(target);
441
+ return found === 0 || (found - end) * step >= 0 ? end : found;
397
442
  }
398
443
 
399
444
  /**
@@ -414,10 +459,10 @@ class ReadableIndex extends events.EventEmitter {
414
459
  return 0;
415
460
  }
416
461
  // We only need to search until the searched number because entry.number is always >= position
417
- const [low, high] = binarySearch(number, Math.min(this.length, number), index => this.get(index).number);
462
+ const [low, high] = binarySearch(number, Math.min(this.length, number), index => this.numberAt(index - 1));
418
463
  return min ? low : high;
419
464
  }
420
465
  }
421
466
 
422
467
  export default ReadableIndex;
423
- export { Entry, HEADER_MAGIC, CorruptedIndexError };
468
+ export { Entry, HEADER_MAGIC, CorruptedIndexError, CHUNK_CAPACITY, createChunk };
@@ -1,8 +1,9 @@
1
1
  import fs from 'fs';
2
- import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC } from './ReadableIndex.js';
2
+ import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC, CHUNK_CAPACITY, createChunk } from './ReadableIndex.js';
3
3
  import { assert, assertEqual } from '../utils/util.js';
4
4
  import { buildMetadataHeader } from '../utils/metadataUtil.js';
5
5
  import { ensureDirectory } from '../utils/fsUtil.js';
6
+ import SyncScheduler from '../SyncScheduler.js';
6
7
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
7
8
 
8
9
  /**
@@ -23,9 +24,10 @@ class WritableIndex extends ReadableIndex {
23
24
  * @param {object} [options] An object with additional index options.
24
25
  * @param {EntryInterface} [options.EntryClass] The entry class to use for index items. Must implement the EntryInterface methods.
25
26
  * @param {string} [options.dataDirectory] The directory to store the index file in. Default '.'.
26
- * @param {number} [options.writeBufferSize] The number of bytes to use for the write buffer. Default 4096.
27
+ * @param {number} [options.writeBufferSize] The amount of bytes of unwritten entries after which they are flushed. Default 4096.
27
28
  * @param {number} [options.flushDelay] How many ms to delay the write buffer flush to optimize throughput. Default 100.
28
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`.
29
31
  */
30
32
  constructor(name = '.index', options = {}) {
31
33
  ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
@@ -47,11 +49,13 @@ class WritableIndex extends ReadableIndex {
47
49
  ensureDirectory(options.dataDirectory);
48
50
 
49
51
  this.fileMode = 'a+';
50
- this.writeBuffer = Buffer.allocUnsafe(options.writeBufferSize >>> 0); // jshint ignore:line
51
- this.writeBufferCursor = 0;
52
+ // New entries are only written into the in-memory entries. Those behind `flushedLength` are the write buffer.
53
+ this.writeBufferSize = options.writeBufferSize >>> 0; // jshint ignore:line
54
+ this.flushedLength = 0;
52
55
  this.flushCallbacks = [];
53
56
  this.flushDelay = options.flushDelay >>> 0; // jshint ignore:line
54
57
  this.syncOnFlush = !!options.syncOnFlush;
58
+ this.syncScheduler = options.syncScheduler || new SyncScheduler({ syncOnFlush: options.syncOnFlush, syncInterval: options.syncInterval });
55
59
  }
56
60
 
57
61
  /**
@@ -92,9 +96,10 @@ class WritableIndex extends ReadableIndex {
92
96
  if (this.opened) {
93
97
  return false;
94
98
  }
95
- this.writeBufferCursor = 0;
96
99
  this.flushCallbacks = [];
97
- return super.open();
100
+ const opened = super.open();
101
+ this.flushedLength = this.length;
102
+ return opened;
98
103
  }
99
104
 
100
105
  /**
@@ -110,19 +115,35 @@ class WritableIndex extends ReadableIndex {
110
115
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
111
116
  fs.writeSync(this.getFileHandle(), metadataBuffer, 0, metadataBuffer.byteLength, 0);
112
117
  this.headerSize = metadataBuffer.byteLength;
118
+ this.syncScheduler.created(this);
113
119
  }
114
120
 
115
121
  /**
116
- * 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.
117
124
  *
118
125
  * @param {number} fd
126
+ * @param {boolean} evicted
119
127
  */
120
- onBeforeClose(fd) {
121
- if (!this.writeBuffer) {
128
+ onBeforeClose(fd, evicted) {
129
+ if (!this.flushCallbacks) {
122
130
  return;
123
131
  }
124
132
  this.flush();
125
- fs.fdatasyncSync(fd);
133
+ if (!evicted) {
134
+ fs.fdatasyncSync(fd);
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Write the buffered entries and close the index. The flush reopens the file handle if the pool evicted it
140
+ * since the last write, so no buffered entry is lost.
141
+ *
142
+ * @api
143
+ */
144
+ close() {
145
+ this.flush();
146
+ super.close();
126
147
  }
127
148
 
128
149
  /**
@@ -147,23 +168,40 @@ class WritableIndex extends ReadableIndex {
147
168
  clearTimeout(this.flushTimeout);
148
169
  this.flushTimeout = null;
149
170
  }
150
- if (this.writeBufferCursor === 0) {
171
+ if (this.flushedLength === this.length) {
151
172
  return false;
152
173
  }
153
174
 
154
175
  const fd = this.getFileHandle();
155
- fs.writeSync(fd, this.writeBuffer, 0, this.writeBufferCursor);
176
+ this.writeUnflushedEntries(fd);
156
177
  if (this.syncOnFlush) {
157
178
  fs.fsyncSync(fd);
158
179
  }
159
180
 
160
- this.writeBufferCursor = 0;
161
181
  const callbacks = this.flushCallbacks;
162
182
  this.flushCallbacks = [];
163
183
  for (let i = 0; i < callbacks.length; i += 2) callbacks[i](callbacks[i + 1]);
164
184
  return true;
165
185
  }
166
186
 
187
+ /**
188
+ * Write the in-memory entries that are not in the file yet. They are already in the binary file format,
189
+ * so this writes them directly from memory, one write per chunk they span.
190
+ *
191
+ * @private
192
+ * @param {number} fd
193
+ */
194
+ writeUnflushedEntries(fd) {
195
+ const entrySize = this.EntryClass.size;
196
+ while (this.flushedLength < this.length) {
197
+ const chunkIndex = Math.floor(this.flushedLength / CHUNK_CAPACITY);
198
+ const from = this.flushedLength - chunkIndex * CHUNK_CAPACITY;
199
+ const until = Math.min(CHUNK_CAPACITY, this.length - chunkIndex * CHUNK_CAPACITY);
200
+ fs.writeSync(fd, this.chunks[chunkIndex].buffer, from * entrySize, (until - from) * entrySize);
201
+ this.flushedLength += until - from;
202
+ }
203
+ }
204
+
167
205
  /**
168
206
  * Register a flush callback for the given index position.
169
207
  *
@@ -190,27 +228,42 @@ class WritableIndex extends ReadableIndex {
190
228
  assertEqual(entry.constructor.name, this.EntryClass.name, `Wrong entry object.`);
191
229
  assertEqual(entry.constructor.size, this.EntryClass.size, `Invalid entry size.`);
192
230
 
193
- const dataLen = this.data.length;
194
- assert(dataLen === 0 || this.data.at(-1).number < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
231
+ const dataLen = this.length;
232
+ assert(dataLen === 0 || this.numberAt(dataLen - 1) < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
195
233
 
196
- if (this.readUntil === dataLen - 1) {
197
- this.readUntil++;
198
- }
199
- this.data[dataLen] = entry;
200
-
201
- if (this.writeBufferCursor === 0) {
234
+ if (this.flushedLength === dataLen) {
202
235
  this.flushTimeout = setTimeout(() => this.flush(), this.flushDelay);
203
236
  }
204
237
 
205
- this.writeBufferCursor += entry.toBuffer(this.writeBuffer, this.writeBufferCursor);
238
+ this.appendEntry(entry);
206
239
  this.onFlush(callback, this.length);
207
- if (this.writeBufferCursor >= this.writeBuffer.byteLength) {
240
+ if ((this.length - this.flushedLength) * this.EntryClass.size >= this.writeBufferSize) {
208
241
  this.flush();
209
242
  }
210
243
 
211
244
  return this.length;
212
245
  }
213
246
 
247
+ /**
248
+ * Write the entry into memory behind the last entry. It reaches the file with the next flush.
249
+ *
250
+ * @private
251
+ * @param {EntryInterface} entry
252
+ */
253
+ appendEntry(entry) {
254
+ const chunkIndex = Math.floor(this.length / CHUNK_CAPACITY);
255
+ const position = this.length - chunkIndex * CHUNK_CAPACITY;
256
+ let chunk = position > 0 ? this.chunkFor(this.length - 1) : createChunk(this.EntryClass.size, 1);
257
+ assert(chunk, 'Can not append to the index, because its last entries could not be read.');
258
+ if (chunk.capacity === position) {
259
+ chunk = createChunk(this.EntryClass.size, position + 1, chunk);
260
+ }
261
+ this.chunks[chunkIndex] = chunk;
262
+ entry.toBuffer(chunk.buffer, position * this.EntryClass.size);
263
+ chunk.filled = position + 1;
264
+ this.setLength(this.length + 1);
265
+ }
266
+
214
267
  /**
215
268
  * Truncate the index after the given entry number.
216
269
  *
@@ -232,8 +285,8 @@ class WritableIndex extends ReadableIndex {
232
285
  return;
233
286
  }
234
287
  fs.truncateSync(this.fileName, truncatePosition);
235
- this.data.splice(after);
236
- this.readUntil = Math.min(this.readUntil, after);
288
+ this.setLength(after);
289
+ this.flushedLength = Math.min(this.flushedLength, after);
237
290
  }
238
291
  }
239
292