event-storage 1.4.1 → 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.
- package/README.md +12 -88
- package/index.d.ts +116 -10
- package/index.js +2 -1
- package/package.json +10 -3
- package/projections.d.ts +40 -0
- package/projections.js +1 -0
- package/src/Consumer.js +18 -29
- package/src/EventStore.js +24 -3
- package/src/Index/ReadOnlyIndex.js +3 -3
- package/src/Index/ReadableIndex.js +147 -102
- package/src/Index/WritableIndex.js +73 -23
- package/src/JoinEventStream.js +23 -83
- package/src/Partition/ReadablePartition.js +31 -8
- package/src/Partition/WritablePartition.js +58 -2
- package/src/Projection.js +164 -0
- package/src/Storage/ReadOnlyStorage.js +12 -13
- package/src/Storage/ReadableStorage.js +6 -11
- package/src/Storage/StorageLock.js +185 -0
- package/src/Storage/WritableStorage.js +86 -45
- package/src/Storage.js +3 -2
- package/src/utils/dcbUtil.js +18 -1
- package/src/utils/fsUtil.js +57 -1
- package/src/utils/indexUtil.js +85 -116
- package/src/utils/metadataUtil.js +23 -1
|
@@ -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
|
-
|
|
70
|
-
|
|
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.
|
|
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
|
-
|
|
175
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
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 {
|
|
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
|
-
|
|
270
|
-
|
|
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
|
|
273
|
-
|
|
274
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
284
|
-
*
|
|
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}
|
|
288
|
-
* @param {
|
|
289
|
-
* @returns {
|
|
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
|
-
|
|
292
|
-
|
|
293
|
-
|
|
343
|
+
entryAt(index, into = null) {
|
|
344
|
+
const chunk = this.chunkFor(index);
|
|
345
|
+
if (!chunk) {
|
|
346
|
+
return false;
|
|
294
347
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
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
|
-
|
|
315
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
* @
|
|
326
|
-
* @returns {
|
|
367
|
+
* @param {number} index The 0-based entry number.
|
|
368
|
+
* @returns {number}
|
|
327
369
|
*/
|
|
328
|
-
|
|
329
|
-
if (this.
|
|
330
|
-
return
|
|
370
|
+
numberAt(index) {
|
|
371
|
+
if (!this.wordsPerEntry) {
|
|
372
|
+
return this.entryAt(index).number;
|
|
331
373
|
}
|
|
332
|
-
return this.
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
|
360
|
-
* @param {number} until The 1-based index position
|
|
361
|
-
* @returns {
|
|
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
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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
|
-
*
|
|
426
|
+
* Iterate all index entries. Same as `range(1, -1)`, with the same reuse of the entry object.
|
|
372
427
|
*
|
|
373
428
|
* @api
|
|
374
|
-
* @
|
|
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
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC, CHUNK_CAPACITY, createChunk } from './ReadableIndex.js';
|
|
3
4
|
import { assert, assertEqual } from '../utils/util.js';
|
|
4
5
|
import { buildMetadataHeader } from '../utils/metadataUtil.js';
|
|
5
|
-
import { ensureDirectory } from '../utils/fsUtil.js';
|
|
6
|
+
import { ensureDirectory, syncDirectory } from '../utils/fsUtil.js';
|
|
6
7
|
import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -23,7 +24,7 @@ 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
|
|
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.
|
|
29
30
|
*/
|
|
@@ -47,11 +48,13 @@ class WritableIndex extends ReadableIndex {
|
|
|
47
48
|
ensureDirectory(options.dataDirectory);
|
|
48
49
|
|
|
49
50
|
this.fileMode = 'a+';
|
|
50
|
-
|
|
51
|
-
this.
|
|
51
|
+
// New entries are only written into the in-memory entries. Those behind `flushedLength` are the write buffer.
|
|
52
|
+
this.writeBufferSize = options.writeBufferSize >>> 0; // jshint ignore:line
|
|
53
|
+
this.flushedLength = 0;
|
|
52
54
|
this.flushCallbacks = [];
|
|
53
55
|
this.flushDelay = options.flushDelay >>> 0; // jshint ignore:line
|
|
54
56
|
this.syncOnFlush = !!options.syncOnFlush;
|
|
57
|
+
this.syncNewFile = this.syncOnFlush || options.syncInterval > 0;
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
/**
|
|
@@ -92,9 +95,10 @@ class WritableIndex extends ReadableIndex {
|
|
|
92
95
|
if (this.opened) {
|
|
93
96
|
return false;
|
|
94
97
|
}
|
|
95
|
-
this.writeBufferCursor = 0;
|
|
96
98
|
this.flushCallbacks = [];
|
|
97
|
-
|
|
99
|
+
const opened = super.open();
|
|
100
|
+
this.flushedLength = this.length;
|
|
101
|
+
return opened;
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/**
|
|
@@ -110,6 +114,9 @@ class WritableIndex extends ReadableIndex {
|
|
|
110
114
|
const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
|
|
111
115
|
fs.writeSync(this.getFileHandle(), metadataBuffer, 0, metadataBuffer.byteLength, 0);
|
|
112
116
|
this.headerSize = metadataBuffer.byteLength;
|
|
117
|
+
if (this.syncNewFile) {
|
|
118
|
+
syncDirectory(path.dirname(this.fileName));
|
|
119
|
+
}
|
|
113
120
|
}
|
|
114
121
|
|
|
115
122
|
/**
|
|
@@ -118,13 +125,24 @@ class WritableIndex extends ReadableIndex {
|
|
|
118
125
|
* @param {number} fd
|
|
119
126
|
*/
|
|
120
127
|
onBeforeClose(fd) {
|
|
121
|
-
if (!this.
|
|
128
|
+
if (!this.flushCallbacks) {
|
|
122
129
|
return;
|
|
123
130
|
}
|
|
124
131
|
this.flush();
|
|
125
132
|
fs.fdatasyncSync(fd);
|
|
126
133
|
}
|
|
127
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Write the buffered entries and close the index. The flush reopens the file handle if the pool evicted it
|
|
137
|
+
* since the last write, so no buffered entry is lost.
|
|
138
|
+
*
|
|
139
|
+
* @api
|
|
140
|
+
*/
|
|
141
|
+
close() {
|
|
142
|
+
this.flush();
|
|
143
|
+
super.close();
|
|
144
|
+
}
|
|
145
|
+
|
|
128
146
|
/**
|
|
129
147
|
* This destroys the index and deletes it from disk.
|
|
130
148
|
* @api
|
|
@@ -147,23 +165,40 @@ class WritableIndex extends ReadableIndex {
|
|
|
147
165
|
clearTimeout(this.flushTimeout);
|
|
148
166
|
this.flushTimeout = null;
|
|
149
167
|
}
|
|
150
|
-
if (this.
|
|
168
|
+
if (this.flushedLength === this.length) {
|
|
151
169
|
return false;
|
|
152
170
|
}
|
|
153
171
|
|
|
154
172
|
const fd = this.getFileHandle();
|
|
155
|
-
|
|
173
|
+
this.writeUnflushedEntries(fd);
|
|
156
174
|
if (this.syncOnFlush) {
|
|
157
175
|
fs.fsyncSync(fd);
|
|
158
176
|
}
|
|
159
177
|
|
|
160
|
-
this.writeBufferCursor = 0;
|
|
161
178
|
const callbacks = this.flushCallbacks;
|
|
162
179
|
this.flushCallbacks = [];
|
|
163
180
|
for (let i = 0; i < callbacks.length; i += 2) callbacks[i](callbacks[i + 1]);
|
|
164
181
|
return true;
|
|
165
182
|
}
|
|
166
183
|
|
|
184
|
+
/**
|
|
185
|
+
* Write the in-memory entries that are not in the file yet. They are already in the binary file format,
|
|
186
|
+
* so this writes them directly from memory, one write per chunk they span.
|
|
187
|
+
*
|
|
188
|
+
* @private
|
|
189
|
+
* @param {number} fd
|
|
190
|
+
*/
|
|
191
|
+
writeUnflushedEntries(fd) {
|
|
192
|
+
const entrySize = this.EntryClass.size;
|
|
193
|
+
while (this.flushedLength < this.length) {
|
|
194
|
+
const chunkIndex = Math.floor(this.flushedLength / CHUNK_CAPACITY);
|
|
195
|
+
const from = this.flushedLength - chunkIndex * CHUNK_CAPACITY;
|
|
196
|
+
const until = Math.min(CHUNK_CAPACITY, this.length - chunkIndex * CHUNK_CAPACITY);
|
|
197
|
+
fs.writeSync(fd, this.chunks[chunkIndex].buffer, from * entrySize, (until - from) * entrySize);
|
|
198
|
+
this.flushedLength += until - from;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
167
202
|
/**
|
|
168
203
|
* Register a flush callback for the given index position.
|
|
169
204
|
*
|
|
@@ -190,27 +225,42 @@ class WritableIndex extends ReadableIndex {
|
|
|
190
225
|
assertEqual(entry.constructor.name, this.EntryClass.name, `Wrong entry object.`);
|
|
191
226
|
assertEqual(entry.constructor.size, this.EntryClass.size, `Invalid entry size.`);
|
|
192
227
|
|
|
193
|
-
const dataLen = this.
|
|
194
|
-
assert(dataLen === 0 || this.
|
|
228
|
+
const dataLen = this.length;
|
|
229
|
+
assert(dataLen === 0 || this.numberAt(dataLen - 1) < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
|
|
195
230
|
|
|
196
|
-
if (this.
|
|
197
|
-
this.readUntil++;
|
|
198
|
-
}
|
|
199
|
-
this.data[dataLen] = entry;
|
|
200
|
-
|
|
201
|
-
if (this.writeBufferCursor === 0) {
|
|
231
|
+
if (this.flushedLength === dataLen) {
|
|
202
232
|
this.flushTimeout = setTimeout(() => this.flush(), this.flushDelay);
|
|
203
233
|
}
|
|
204
234
|
|
|
205
|
-
this.
|
|
235
|
+
this.appendEntry(entry);
|
|
206
236
|
this.onFlush(callback, this.length);
|
|
207
|
-
if (this.
|
|
237
|
+
if ((this.length - this.flushedLength) * this.EntryClass.size >= this.writeBufferSize) {
|
|
208
238
|
this.flush();
|
|
209
239
|
}
|
|
210
240
|
|
|
211
241
|
return this.length;
|
|
212
242
|
}
|
|
213
243
|
|
|
244
|
+
/**
|
|
245
|
+
* Write the entry into memory behind the last entry. It reaches the file with the next flush.
|
|
246
|
+
*
|
|
247
|
+
* @private
|
|
248
|
+
* @param {EntryInterface} entry
|
|
249
|
+
*/
|
|
250
|
+
appendEntry(entry) {
|
|
251
|
+
const chunkIndex = Math.floor(this.length / CHUNK_CAPACITY);
|
|
252
|
+
const position = this.length - chunkIndex * CHUNK_CAPACITY;
|
|
253
|
+
let chunk = position > 0 ? this.chunkFor(this.length - 1) : createChunk(this.EntryClass.size, 1);
|
|
254
|
+
assert(chunk, 'Can not append to the index, because its last entries could not be read.');
|
|
255
|
+
if (chunk.capacity === position) {
|
|
256
|
+
chunk = createChunk(this.EntryClass.size, position + 1, chunk);
|
|
257
|
+
}
|
|
258
|
+
this.chunks[chunkIndex] = chunk;
|
|
259
|
+
entry.toBuffer(chunk.buffer, position * this.EntryClass.size);
|
|
260
|
+
chunk.filled = position + 1;
|
|
261
|
+
this.setLength(this.length + 1);
|
|
262
|
+
}
|
|
263
|
+
|
|
214
264
|
/**
|
|
215
265
|
* Truncate the index after the given entry number.
|
|
216
266
|
*
|
|
@@ -232,8 +282,8 @@ class WritableIndex extends ReadableIndex {
|
|
|
232
282
|
return;
|
|
233
283
|
}
|
|
234
284
|
fs.truncateSync(this.fileName, truncatePosition);
|
|
235
|
-
this.
|
|
236
|
-
this.
|
|
285
|
+
this.setLength(after);
|
|
286
|
+
this.flushedLength = Math.min(this.flushedLength, after);
|
|
237
287
|
}
|
|
238
288
|
}
|
|
239
289
|
|