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,105 @@
1
+ import fs from 'fs';
2
+
3
+ /**
4
+ * LRU pool for file descriptors shared across multiple file-backed objects.
5
+ *
6
+ * Targets are expected to expose `fileName` and `fileMode` and may implement
7
+ * `onBeforeClose(fd, evicted)` to flush state before their descriptor closes.
8
+ */
9
+ class FileHandlePool {
10
+
11
+ /**
12
+ * @param {number} [maxOpen=0] Maximum number of simultaneously open handles. 0 disables eviction.
13
+ */
14
+ constructor(maxOpen = 0) {
15
+ this.maxOpen = maxOpen;
16
+ this.handles = new Map();
17
+ }
18
+
19
+ /**
20
+ * @param {object} target
21
+ * @returns {number}
22
+ */
23
+ get(target) {
24
+ const handle = this.handles.get(target);
25
+ if (handle) {
26
+ this.touch(target);
27
+ return handle.fd;
28
+ }
29
+
30
+ this.evictLeastRecentlyUsedIfNeeded(target);
31
+ const fd = fs.openSync(target.fileName, target.fileMode);
32
+ this.handles.set(target, { fd });
33
+ return fd;
34
+ }
35
+
36
+ /**
37
+ * @param {object} target
38
+ * @returns {boolean}
39
+ */
40
+ has(target) {
41
+ return this.handles.has(target);
42
+ }
43
+
44
+ /**
45
+ * @param {object} target
46
+ * @param {boolean} [evicted=true]
47
+ * @returns {boolean}
48
+ */
49
+ evict(target, evicted = true) {
50
+ const handle = this.handles.get(target);
51
+ if (!handle) {
52
+ return false;
53
+ }
54
+ try {
55
+ target.onBeforeClose?.(handle.fd, evicted);
56
+ } finally {
57
+ this.handles.delete(target);
58
+ fs.closeSync(handle.fd);
59
+ }
60
+ return true;
61
+ }
62
+
63
+ /**
64
+ * @param {object} target
65
+ * @returns {void}
66
+ */
67
+ touch(target) {
68
+ const handle = this.handles.get(target);
69
+ if (!handle) {
70
+ return;
71
+ }
72
+ this.handles.delete(target);
73
+ this.handles.set(target, handle);
74
+ }
75
+
76
+ /**
77
+ * Evict the least-recently-used descriptor before opening another one.
78
+ *
79
+ * @param {object} target
80
+ */
81
+ evictLeastRecentlyUsedIfNeeded(target) {
82
+ if (this.maxOpen <= 0) {
83
+ return;
84
+ }
85
+ this.handles.delete(target);
86
+ if (this.handles.size < this.maxOpen) {
87
+ return;
88
+ }
89
+ const lruTarget = this.handles.keys().next().value;
90
+ if (!lruTarget) {
91
+ return;
92
+ }
93
+ this.evict(lruTarget);
94
+ }
95
+
96
+ /**
97
+ * @returns {number}
98
+ */
99
+ get openCount() {
100
+ return this.handles.size;
101
+ }
102
+
103
+ }
104
+
105
+ export default FileHandlePool;
@@ -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
  }
@@ -34,12 +34,12 @@ class ReadOnlyIndex extends watchesFile(ReadableIndex) {
34
34
  */
35
35
  onChange(filename) {
36
36
  /* c8 ignore next 3 */
37
- if (!this.fd) {
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,6 +1,8 @@
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';
5
+ import FileHandlePool from '../FileHandlePool.js';
4
6
  import { assert, wrapAndCheck, binarySearch } from '../utils/util.js';
5
7
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
6
8
  import { resolvePath } from "../utils/fsUtil.js";
@@ -8,6 +10,35 @@ import { resolvePath } from "../utils/fsUtil.js";
8
10
  // node-event-store-index V01
9
11
  const HEADER_MAGIC = "nesidx01";
10
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
+
11
42
  class CorruptedIndexError extends Error {}
12
43
 
13
44
  /**
@@ -39,12 +70,13 @@ class ReadableIndex extends events.EventEmitter {
39
70
  * @param {object} [options] An object with additional index options.
40
71
  * @param {typeof EntryInterface} [options.EntryClass] The entry class to use for index items. Must implement the EntryInterface methods.
41
72
  * @param {string} [options.dataDirectory] The directory to store the index file in. Default '.'.
42
- * @param {number} [options.writeBufferSize] The number of bytes to use for the write buffer. Default 4096.
43
73
  * @param {number} [options.flushDelay] How many ms to delay the write buffer flush to optimize throughput. Default 100.
44
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.
75
+ * @param {object} [options.fileHandlePool] Shared file-handle pool used to reopen evicted handles on demand.
45
76
  */
46
77
  constructor(name = '.index', options = {}) {
47
78
  super();
79
+ this.setMaxListeners(0);
48
80
  ({ name, options } = normalizeNamedCtorArgs(name, options, '.index'));
49
81
  let defaults = {
50
82
  dataDirectory: '.',
@@ -63,14 +95,18 @@ class ReadableIndex extends events.EventEmitter {
63
95
  * @param {object} options
64
96
  */
65
97
  initialize(options) {
66
- /* @type Array<Entry> */
67
- this.data = [];
68
- this.fd = null;
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;
104
+ this.opened = false;
69
105
  this.fileMode = 'r';
106
+ this.fileHandlePool = options.fileHandlePool || new FileHandlePool();
70
107
  this.EntryClass = options.EntryClass;
71
108
  this.dataDirectory = options.dataDirectory;
72
109
  this.fileName = resolvePath(options.dataDirectory, this.name);
73
- this.readBuffer = Buffer.allocUnsafe(Math.max(options.EntryClass.size, options.writeBufferSize > 0 ? options.writeBufferSize : 4096));
74
110
 
75
111
  if (options.metadata) {
76
112
  this.metadata = Object.assign({entryClass: options.EntryClass.name, entrySize: options.EntryClass.size}, options.metadata);
@@ -99,7 +135,7 @@ class ReadableIndex extends events.EventEmitter {
99
135
  * @returns {number}
100
136
  */
101
137
  get length() {
102
- return this.data.length;
138
+ return this.entryCount;
103
139
  }
104
140
 
105
141
  /**
@@ -109,7 +145,21 @@ class ReadableIndex extends events.EventEmitter {
109
145
  * @returns {boolean}
110
146
  */
111
147
  isOpen() {
112
- return !!this.fd;
148
+ return this.opened;
149
+ }
150
+
151
+ /**
152
+ * @returns {boolean}
153
+ */
154
+ hasFileHandle() {
155
+ return this.fileHandlePool.has(this);
156
+ }
157
+
158
+ /**
159
+ * @returns {number}
160
+ */
161
+ getFileHandle() {
162
+ return this.fileHandlePool.get(this);
113
163
  }
114
164
 
115
165
  /**
@@ -120,7 +170,7 @@ class ReadableIndex extends events.EventEmitter {
120
170
  * @throws {Error} If the file is corrupt or can not be read correctly.
121
171
  */
122
172
  checkFile() {
123
- const stat = fs.fstatSync(this.fd);
173
+ const stat = fs.fstatSync(this.getFileHandle());
124
174
  if (stat.size === 0) {
125
175
  return -1;
126
176
  }
@@ -145,20 +195,14 @@ class ReadableIndex extends events.EventEmitter {
145
195
  * @throws {Error} if the file can not be opened.
146
196
  */
147
197
  open() {
148
- if (this.fd) {
198
+ if (this.opened) {
149
199
  return false;
150
200
  }
151
-
152
- this.fd = fs.openSync(this.fileName, this.fileMode);
153
-
154
- this.readUntil = -1;
201
+ this.opened = this.getFileHandle() !== null;
155
202
 
156
203
  const length = this.readFileLength();
157
- if (length > 0) {
158
- this.data = new Array(length);
159
- // Read last item to get the index started
160
- this.read(length);
161
- }
204
+ this.setLength(0);
205
+ this.setLength(length);
162
206
 
163
207
  return true;
164
208
  }
@@ -209,8 +253,9 @@ class ReadableIndex extends events.EventEmitter {
209
253
  */
210
254
  readMetadata() {
211
255
  if (this.headerSize > 0) return this.headerSize;
256
+ const fd = this.getFileHandle();
212
257
  const headerBuffer = Buffer.allocUnsafe(8 + 4);
213
- fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
258
+ fs.readSync(fd, headerBuffer, 0, 8 + 4, 0);
214
259
  const headerMagic = headerBuffer.toString('utf8', 0, 8);
215
260
 
216
261
  assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), 'Invalid file header.');
@@ -221,7 +266,7 @@ class ReadableIndex extends events.EventEmitter {
221
266
 
222
267
  const metadataBuffer = Buffer.allocUnsafe(metadataSize - 1);
223
268
  metadataBuffer.fill(" ");
224
- fs.readSync(this.fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
269
+ fs.readSync(fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
225
270
  const metadata = metadataBuffer.toString('utf8').trim();
226
271
  this.verifyAndSetMetadata(metadata);
227
272
  this.headerSize = 8 + 4 + metadataSize;
@@ -233,85 +278,100 @@ class ReadableIndex extends events.EventEmitter {
233
278
  * @api
234
279
  */
235
280
  close() {
236
- this.data = [];
237
- this.readUntil = -1;
238
- this.readBuffer.fill(0);
239
- if (this.fd) {
240
- fs.closeSync(this.fd);
241
- this.fd = null;
242
- }
281
+ // Evict first, so a writer can still flush its unwritten entries from memory.
282
+ this.fileHandlePool.evict(this, false);
283
+ this.setLength(0);
284
+ this.opened = false;
243
285
  }
244
286
 
245
287
  /**
246
- * Read a single index entry from the given index position.
247
- * 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.
248
289
  *
249
290
  * @private
250
- * @param {number} index
251
- * @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.
252
293
  */
253
- read(index) {
254
- 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
+ }
255
301
 
256
- fs.readSync(this.fd, this.readBuffer, 0, this.EntryClass.size, this.headerSize + index * this.EntryClass.size);
257
- if (index === this.readUntil + 1) {
258
- 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);
259
305
  }
260
- 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
+ }
261
312
 
262
- 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
+ }
263
332
  }
264
333
 
265
334
  /**
266
- * Read a range of entries from disk. This method will not do any range checks.
267
- * 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.
268
337
  *
269
338
  * @private
270
- * @param {number} from The 1-based index position from where to read from (inclusive).
271
- * @param {number} until The 1-based index position until which to read to (inclusive).
272
- * @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.
273
342
  */
274
- readRange(from, until) {
275
- if (until === from) {
276
- return [this.read(from)];
343
+ entryAt(index, into = null) {
344
+ const chunk = this.chunkFor(index);
345
+ if (!chunk) {
346
+ return false;
277
347
  }
278
-
279
- from--;
280
- until--;
281
-
282
- const readFrom = Math.max(this.readUntil + 1, from);
283
- const amount = (until - readFrom + 1);
284
-
285
- const bufferSize = amount * this.EntryClass.size;
286
- const readBuffer = bufferSize <= this.readBuffer.byteLength
287
- ? this.readBuffer
288
- : Buffer.allocUnsafe(bufferSize);
289
- let readSize = fs.readSync(this.fd, readBuffer, 0, bufferSize, this.headerSize + readFrom * this.EntryClass.size);
290
- let index = 0;
291
- while (index < amount && readSize > 0) {
292
- this.data[index + readFrom] = this.EntryClass.fromBuffer(readBuffer, index * this.EntryClass.size);
293
- readSize -= this.EntryClass.size;
294
- index++;
348
+ const position = index % CHUNK_CAPACITY;
349
+ if (!this.wordsPerEntry) {
350
+ return this.EntryClass.fromBuffer(chunk.buffer, position * this.EntryClass.size);
295
351
  }
296
- if (from <= this.readUntil + 1) {
297
- 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]);
298
356
  }
299
-
300
- 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;
301
362
  }
302
363
 
303
364
  /**
304
- * Read all index entries. Equal to range(1, index.length) with the exception that this returns
305
- * 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.
306
366
  *
307
- * @api
308
- * @returns {Array<EntryInterface>} An array of all index entries.
367
+ * @param {number} index The 0-based entry number.
368
+ * @returns {number}
309
369
  */
310
- all() {
311
- if (this.length === 0) {
312
- return [];
370
+ numberAt(index) {
371
+ if (!this.wordsPerEntry) {
372
+ return this.entryAt(index).number;
313
373
  }
314
- return this.range(1, this.length);
374
+ return this.chunkFor(index).words[(index % CHUNK_CAPACITY) * this.wordsPerEntry];
315
375
  }
316
376
 
317
377
  /**
@@ -327,55 +387,58 @@ class ReadableIndex extends events.EventEmitter {
327
387
  return false;
328
388
  }
329
389
 
330
- if (this.data[index - 1]) {
331
- return this.data[index - 1];
332
- }
333
-
334
- return this.read(index);
390
+ return this.entryAt(index - 1);
335
391
  }
336
392
 
337
393
  /**
338
- * 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.
339
400
  *
340
401
  * @api
341
- * @param {number} from The 1-based index position from where to get entries from (inclusive).
342
- * @param {number} until The 1-based index position until where to get entries to (inclusive).
343
- * @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.
344
405
  */
345
- validRange(from, until) {
346
- if (from < 1 || from > this.length) {
347
- 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
+ }
348
422
  }
349
- return (until >= from && until <= this.length);
350
423
  }
351
424
 
352
425
  /**
353
- * Get a range of index entries.
426
+ * Iterate all index entries. Same as `range(1, -1)`, with the same reuse of the entry object.
354
427
  *
355
428
  * @api
356
- * @param {number} from The 1-based index position from where to get entries from (inclusive). If < 0 will start at that position from end.
357
- * @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.
358
- * @returns {Array<Entry>|boolean} An array of entries for the given range or false on error.
429
+ * @returns {Generator<Entry>}
359
430
  */
360
- range(from, until = -1) {
361
- from = wrapAndCheck(from, this.length);
362
- until = wrapAndCheck(until, this.length);
363
-
364
- if (from <= 0 || until < from) {
365
- return false;
366
- }
367
-
368
- const readFrom = Math.max(this.readUntil + 1, from);
369
- let readUntil = until;
370
- while (readUntil >= readFrom && this.data[readUntil - 1]) {
371
- readUntil--;
372
- }
373
-
374
- if (readFrom <= readUntil) {
375
- this.readRange(readFrom, readUntil);
376
- }
431
+ all() {
432
+ return this.range(1, -1);
433
+ }
377
434
 
378
- 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;
379
442
  }
380
443
 
381
444
  /**
@@ -396,10 +459,10 @@ class ReadableIndex extends events.EventEmitter {
396
459
  return 0;
397
460
  }
398
461
  // We only need to search until the searched number because entry.number is always >= position
399
- 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));
400
463
  return min ? low : high;
401
464
  }
402
465
  }
403
466
 
404
467
  export default ReadableIndex;
405
- export { Entry, HEADER_MAGIC, CorruptedIndexError };
468
+ export { Entry, HEADER_MAGIC, CorruptedIndexError, CHUNK_CAPACITY, createChunk };