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.
@@ -1,8 +1,9 @@
1
1
  import fs from 'fs';
2
- import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC } from './ReadableIndex.js';
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 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.
29
30
  */
@@ -47,11 +48,13 @@ class WritableIndex extends ReadableIndex {
47
48
  ensureDirectory(options.dataDirectory);
48
49
 
49
50
  this.fileMode = 'a+';
50
- this.writeBuffer = Buffer.allocUnsafe(options.writeBufferSize >>> 0); // jshint ignore:line
51
- this.writeBufferCursor = 0;
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
  /**
@@ -89,12 +92,13 @@ class WritableIndex extends ReadableIndex {
89
92
  * @throws {Error} if the file can not be opened.
90
93
  */
91
94
  open() {
92
- if (this.fd) {
95
+ if (this.opened) {
93
96
  return false;
94
97
  }
95
- this.writeBufferCursor = 0;
96
98
  this.flushCallbacks = [];
97
- return super.open();
99
+ const opened = super.open();
100
+ this.flushedLength = this.length;
101
+ return opened;
98
102
  }
99
103
 
100
104
  /**
@@ -108,19 +112,34 @@ class WritableIndex extends ReadableIndex {
108
112
  this.metadata = {entryClass: this.EntryClass.name, entrySize: this.EntryClass.size};
109
113
  }
110
114
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
111
- fs.writeSync(this.fd, metadataBuffer, 0, metadataBuffer.byteLength, 0);
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
  /**
116
- * Close the index and release the file handle.
123
+ * Flush pending buffered writes before the pool closes the descriptor.
124
+ *
125
+ * @param {number} fd
126
+ */
127
+ onBeforeClose(fd) {
128
+ if (!this.flushCallbacks) {
129
+ return;
130
+ }
131
+ this.flush();
132
+ fs.fdatasyncSync(fd);
133
+ }
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
+ *
117
139
  * @api
118
140
  */
119
141
  close() {
120
- if (this.fd) {
121
- this.flush();
122
- fs.fdatasyncSync(this.fd);
123
- }
142
+ this.flush();
124
143
  super.close();
125
144
  }
126
145
 
@@ -139,29 +158,47 @@ class WritableIndex extends ReadableIndex {
139
158
  * @returns {boolean} If a flush actually was executed.
140
159
  */
141
160
  flush() {
142
- if (!this.fd) {
161
+ if (!this.isOpen()) {
143
162
  return false;
144
163
  }
145
164
  if (this.flushTimeout) {
146
165
  clearTimeout(this.flushTimeout);
147
166
  this.flushTimeout = null;
148
167
  }
149
- if (this.writeBufferCursor === 0) {
168
+ if (this.flushedLength === this.length) {
150
169
  return false;
151
170
  }
152
171
 
153
- fs.writeSync(this.fd, this.writeBuffer, 0, this.writeBufferCursor);
172
+ const fd = this.getFileHandle();
173
+ this.writeUnflushedEntries(fd);
154
174
  if (this.syncOnFlush) {
155
- fs.fsyncSync(this.fd);
175
+ fs.fsyncSync(fd);
156
176
  }
157
177
 
158
- this.writeBufferCursor = 0;
159
178
  const callbacks = this.flushCallbacks;
160
179
  this.flushCallbacks = [];
161
180
  for (let i = 0; i < callbacks.length; i += 2) callbacks[i](callbacks[i + 1]);
162
181
  return true;
163
182
  }
164
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
+
165
202
  /**
166
203
  * Register a flush callback for the given index position.
167
204
  *
@@ -188,36 +225,52 @@ class WritableIndex extends ReadableIndex {
188
225
  assertEqual(entry.constructor.name, this.EntryClass.name, `Wrong entry object.`);
189
226
  assertEqual(entry.constructor.size, this.EntryClass.size, `Invalid entry size.`);
190
227
 
191
- const dataLen = this.data.length;
192
- assert(dataLen === 0 || this.data.at(-1).number < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
193
-
194
- if (this.readUntil === dataLen - 1) {
195
- this.readUntil++;
196
- }
197
- this.data[dataLen] = entry;
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.');
198
230
 
199
- if (this.writeBufferCursor === 0) {
231
+ if (this.flushedLength === dataLen) {
200
232
  this.flushTimeout = setTimeout(() => this.flush(), this.flushDelay);
201
233
  }
202
234
 
203
- this.writeBufferCursor += entry.toBuffer(this.writeBuffer, this.writeBufferCursor);
235
+ this.appendEntry(entry);
204
236
  this.onFlush(callback, this.length);
205
- if (this.writeBufferCursor >= this.writeBuffer.byteLength) {
237
+ if ((this.length - this.flushedLength) * this.EntryClass.size >= this.writeBufferSize) {
206
238
  this.flush();
207
239
  }
208
240
 
209
241
  return this.length;
210
242
  }
211
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
+
212
264
  /**
213
265
  * Truncate the index after the given entry number.
214
266
  *
215
267
  * @param {number} after The index entry number to truncate after.
216
268
  */
217
269
  truncate(after) {
218
- if (!this.fd) {
270
+ if (!this.isOpen()) {
219
271
  return;
220
272
  }
273
+ this.getFileHandle();
221
274
  if (after < 0) {
222
275
  after = 0;
223
276
  }
@@ -229,8 +282,8 @@ class WritableIndex extends ReadableIndex {
229
282
  return;
230
283
  }
231
284
  fs.truncateSync(this.fileName, truncatePosition);
232
- this.data.splice(after);
233
- this.readUntil = Math.min(this.readUntil, after);
285
+ this.setLength(after);
286
+ this.flushedLength = Math.min(this.flushedLength, after);
234
287
  }
235
288
  }
236
289
 
@@ -1,5 +1,5 @@
1
1
  import EventStream from './EventStream.js';
2
- import {assert, iterate} from './utils/util.js';
2
+ import {assert} from './utils/util.js';
3
3
  import {intersect, normalizeSelector, union} from './utils/indexUtil.js';
4
4
  import {normalizeRevision} from './utils/apiHelpers.js';
5
5
 
@@ -40,118 +40,58 @@ class JoinEventStream extends EventStream {
40
40
  this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
41
41
  this.version = this.streamIndex.length;
42
42
 
43
- this._combinedRanges = null;
44
-
45
43
  this.fetch = () => this.iterateDocuments();
46
44
  this._iterator = null;
47
45
  }
48
46
 
49
47
 
50
48
  /**
51
- * Resolve and cache the combined index-entry ranges for the full selector.
52
- *
53
- * @private
54
- * @returns {Array<Array<number>>}
55
- */
56
- resolveCombinedRanges() {
57
- if (this._combinedRanges) {
58
- return this._combinedRanges;
59
- }
60
-
61
- this._combinedRanges = this.resolveSelectorRanges(this.selector);
62
- return this._combinedRanges;
63
- }
64
-
65
- /**
66
- * Resolve one selector node into a sorted index-entry range.
67
- * Selector is already normalized and optimized from constructor, so we just traverse and collect ranges.
49
+ * Resolve one selector node into a lazy range of matching index entries.
50
+ * Selector is already normalized and optimized from constructor, so we just traverse it.
68
51
  *
69
52
  * @private
70
53
  * @param {string|Array<string|Array>} selectorNode
71
54
  * @param {number} [depth=0]
72
- * @returns {Array<Array<number>>}
55
+ * @returns {Iterator<Entry>}
73
56
  */
74
- resolveSelectorRanges(selectorNode, depth = 0) {
57
+ resolveSelectorRange(selectorNode, depth = 0) {
58
+ const forwards = this.minRevision <= this.maxRevision;
75
59
  if (typeof selectorNode === 'string') {
76
60
  const index = this.eventStore.streams[selectorNode]?.index;
77
- return this.resolveIndexRange(index);
78
- }
79
-
80
- const childRanges = selectorNode.map(node => this.resolveSelectorRanges(node, depth + 1));
81
- return depth % 2 === 0 ? union(...childRanges) : intersect(...childRanges);
82
- }
83
-
84
- /**
85
- * Resolve one stream index to the global revision-bounded entry range.
86
- *
87
- * @private
88
- * @param {object|undefined} index
89
- * @returns {Array<Array<number>>}
90
- */
91
- resolveIndexRange(index) {
92
- if (!index || index.length === 0) {
93
- return [];
61
+ if (!index || index.length === 0) {
62
+ return [][Symbol.iterator]();
63
+ }
64
+ const first = index.find(Math.min(this.minRevision, this.maxRevision), true);
65
+ const last = index.find(Math.max(this.minRevision, this.maxRevision));
66
+ if (first === 0 || last === 0 || first > last) {
67
+ return [][Symbol.iterator]();
68
+ }
69
+ return forwards ? index.range(first, last) : index.range(last, first);
94
70
  }
95
71
 
96
- const ascending = this.minRevision <= this.maxRevision;
97
- const from = index.find(this.minRevision, ascending);
98
- const until = index.find(this.maxRevision, !ascending);
99
- if (
100
- from === 0 ||
101
- until === 0 ||
102
- (ascending ? from > until : from < until)
103
- ) {
104
- return [];
72
+ const ranges = selectorNode.map(node => this.resolveSelectorRange(node, depth + 1));
73
+ if (ranges.length === 0) {
74
+ return [][Symbol.iterator]();
105
75
  }
106
-
107
- const rangeFrom = ascending ? from : until;
108
- const rangeUntil = ascending ? until : from;
109
- return index.range(rangeFrom, rangeUntil) || [];
110
- }
111
-
112
- /**
113
- * Iterate matching index entries in requested direction.
114
- *
115
- * @private
116
- * @returns {Generator<Array<number>>}
117
- */
118
- * iterateEntries() {
119
- const entries = this.resolveCombinedRanges();
120
- const forwards = this.minRevision <= this.maxRevision;
121
- yield* iterate(entries, forwards);
76
+ const combine = depth % 2 === 0 ? union : intersect;
77
+ return ranges.reduce((left, right) => combine(left, right, forwards));
122
78
  }
123
79
 
124
80
  /**
125
- * Iterate storage documents lazily from combined index entries.
81
+ * Iterate storage documents lazily from the matching index entries.
126
82
  *
127
83
  * @private
128
84
  * @returns {Generator<object|{ buffer: Buffer, time64: number, sequenceNumber: number }>}
129
85
  */
130
86
  * iterateDocuments() {
131
87
  const forwards = this.minRevision <= this.maxRevision;
132
- for (const entry of this.iterateEntries()) {
133
- const event = this.eventStore.storage.readFrom(
134
- entry.partition,
135
- entry.position,
136
- entry.size,
137
- this.raw,
138
- !forwards
139
- );
88
+ for (const entry of this.resolveSelectorRange(this.selector)) {
89
+ const event = this.eventStore.storage.readFrom(entry.partition, entry.position, entry.size, this.raw, !forwards);
140
90
  if (event) {
141
91
  yield event;
142
92
  }
143
93
  }
144
94
  }
145
-
146
- /**
147
- * Reset fetch state and cached selector ranges when stream boundaries changed.
148
- *
149
- * @returns {JoinEventStream}
150
- */
151
- reset() {
152
- this._combinedRanges = null;
153
- return super.reset();
154
- }
155
95
  }
156
96
 
157
97
  export default JoinEventStream;
@@ -19,7 +19,7 @@ class ReadOnlyPartition extends WatchesFile(ReadablePartition) {
19
19
  */
20
20
  onChange(filename) {
21
21
  /* c8 ignore next 3 */
22
- if (!this.fd) {
22
+ if (!this.isOpen()) {
23
23
  return;
24
24
  }
25
25
  const prevSize = this.size;
@@ -1,6 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import events from 'events';
4
+ import FileHandlePool from '../FileHandlePool.js';
4
5
  import { assert, alignTo, hash, binarySearch } from '../utils/util.js';
5
6
  import { resolvePath } from "../utils/fsUtil.js";
6
7
 
@@ -41,9 +42,11 @@ class ReadablePartition extends events.EventEmitter {
41
42
  * @param {object} [config] An object with storage parameters.
42
43
  * @param {string} [config.dataDirectory] The path where the storage data should reside. Default '.'.
43
44
  * @param {number} [config.readBufferSize] Size of the read buffer in bytes. Default 4096.
45
+ * @param {object} [config.fileHandlePool] Shared file-handle pool used to reopen evicted handles on demand.
44
46
  */
45
47
  constructor(name, config = {}) {
46
48
  super();
49
+ this.setMaxListeners(0);
47
50
  assert(typeof name === 'string' && name !== '', 'Must specify a partition name.');
48
51
 
49
52
  let defaults = {
@@ -57,7 +60,9 @@ class ReadablePartition extends events.EventEmitter {
57
60
  this.id = ReadablePartition.idFor(name);
58
61
  this.fileName = path.resolve(this.dataDirectory, this.name);
59
62
  this.fileMode = 'r';
63
+ this.fileHandlePool = config.fileHandlePool || new FileHandlePool();
60
64
  this.headerSize = 0;
65
+ this.opened = false;
61
66
 
62
67
  this.readBufferSize = config.readBufferSize >>> 0; // jshint ignore:line
63
68
  }
@@ -68,7 +73,21 @@ class ReadablePartition extends events.EventEmitter {
68
73
  * @returns {boolean}
69
74
  */
70
75
  isOpen() {
71
- return !!this.fd;
76
+ return this.opened;
77
+ }
78
+
79
+ /**
80
+ * @returns {boolean}
81
+ */
82
+ hasFileHandle() {
83
+ return this.fileHandlePool.has(this);
84
+ }
85
+
86
+ /**
87
+ * @returns {number}
88
+ */
89
+ getFileHandle() {
90
+ return this.fileHandlePool.get(this);
72
91
  }
73
92
 
74
93
  /**
@@ -78,12 +97,10 @@ class ReadablePartition extends events.EventEmitter {
78
97
  * @returns {boolean} Returns false if the file is not a valid partition.
79
98
  */
80
99
  open() {
81
- if (this.fd) {
100
+ if (this.opened) {
82
101
  return true;
83
102
  }
84
-
85
- this.fd = fs.openSync(this.fileName, this.fileMode);
86
-
103
+ this.opened = this.getFileHandle() !== null;
87
104
  // allocUnsafeSlow because we don't need buffer pooling for these relatively long-lived buffers
88
105
  this.readBuffer = Buffer.allocUnsafeSlow(this.readBufferSize);
89
106
  // Where inside the file the read buffer starts
@@ -97,9 +114,13 @@ class ReadablePartition extends events.EventEmitter {
97
114
  return false;
98
115
  }
99
116
 
100
- this.size -= this.readMetadata();
101
-
102
- return true;
117
+ try {
118
+ this.size -= this.readMetadata();
119
+ return true;
120
+ } catch (error) {
121
+ this.close();
122
+ throw error;
123
+ }
103
124
  }
104
125
 
105
126
  /**
@@ -113,8 +134,9 @@ class ReadablePartition extends events.EventEmitter {
113
134
  readMetadata() {
114
135
  assert(this.size >= 16, `Invalid file.`);
115
136
 
137
+ const fd = this.getFileHandle();
116
138
  const headerBuffer = Buffer.allocUnsafe(8 + 4);
117
- fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
139
+ fs.readSync(fd, headerBuffer, 0, 8 + 4, 0);
118
140
  const headerMagic = headerBuffer.toString('utf8', 0, 8);
119
141
 
120
142
  assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), `Invalid file header in partition ${this.name}.`);
@@ -127,7 +149,7 @@ class ReadablePartition extends events.EventEmitter {
127
149
 
128
150
  const metadataBuffer = Buffer.allocUnsafe(metadataSize - 1);
129
151
  metadataBuffer.fill(" ");
130
- fs.readSync(this.fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
152
+ fs.readSync(fd, metadataBuffer, 0, metadataSize - 1, 8 + 4);
131
153
  const metadata = metadataBuffer.toString('utf8').trim();
132
154
  try {
133
155
  this.metadata = JSON.parse(metadata);
@@ -155,7 +177,7 @@ class ReadablePartition extends events.EventEmitter {
155
177
  * @returns {number} The file size not including the file header.
156
178
  */
157
179
  readFileSize() {
158
- const stat = fs.statSync(this.fileName);
180
+ const stat = fs.fstatSync(this.getFileHandle());
159
181
  this.crtime = stat.birthtimeMs;
160
182
  return stat.size - this.headerSize;
161
183
  }
@@ -167,10 +189,8 @@ class ReadablePartition extends events.EventEmitter {
167
189
  * @returns void
168
190
  */
169
191
  close() {
170
- if (this.fd) {
171
- fs.closeSync(this.fd);
172
- this.fd = null;
173
- }
192
+ this.fileHandlePool.evict(this, false);
193
+ this.opened = false;
174
194
  if (this.readBuffer) {
175
195
  this.readBuffer = null;
176
196
  this.readBufferPos = -1;
@@ -185,7 +205,8 @@ class ReadablePartition extends events.EventEmitter {
185
205
  * @param {number} [from] The file position to start filling the read buffer from. Default 0.
186
206
  */
187
207
  fillBuffer(from = 0) {
188
- this.readBufferLength = fs.readSync(this.fd, this.readBuffer, 0, this.readBuffer.byteLength, this.headerSize + from);
208
+ const fd = this.getFileHandle();
209
+ this.readBufferLength = fs.readSync(fd, this.readBuffer, 0, this.readBuffer.byteLength, this.headerSize + from);
189
210
  this.readBufferPos = from;
190
211
  }
191
212
 
@@ -250,7 +271,7 @@ class ReadablePartition extends events.EventEmitter {
250
271
  * @throws {CorruptFileError} if the document at the given position can not be read completely.
251
272
  */
252
273
  readFrom(position, size = 0, headerOut = null, backwardsHint = false) {
253
- assert(this.fd, 'Partition is not opened.');
274
+ const fd = this.getFileHandle();
254
275
  assert((position % DOCUMENT_ALIGNMENT) === 0, `Invalid read position ${position}. Needs to be a multiple of ${DOCUMENT_ALIGNMENT}.`);
255
276
 
256
277
  const { reader, bufferOffset } = this.selectReader(position, size, backwardsHint);
@@ -272,7 +293,7 @@ class ReadablePartition extends events.EventEmitter {
272
293
 
273
294
  if (dataSize + DOCUMENT_HEADER_SIZE > reader.buffer.byteLength) {
274
295
  const tempReadBuffer = Buffer.allocUnsafe(dataSize);
275
- fs.readSync(this.fd, tempReadBuffer, 0, dataSize, this.headerSize + position + DOCUMENT_HEADER_SIZE);
296
+ fs.readSync(fd, tempReadBuffer, 0, dataSize, this.headerSize + position + DOCUMENT_HEADER_SIZE);
276
297
  return tempReadBuffer;
277
298
  }
278
299
 
@@ -333,7 +354,7 @@ class ReadablePartition extends events.EventEmitter {
333
354
  * @returns {number|boolean} The start position of the first document before the given position or false if no header could be found.
334
355
  */
335
356
  findDocumentPositionBefore(position) {
336
- assert(this.fd, 'Partition is not opened.');
357
+ this.getFileHandle();
337
358
  if (position > 0) position -= (position % DOCUMENT_ALIGNMENT);
338
359
  if (position <= 0) {
339
360
  return false;
@@ -343,22 +364,45 @@ class ReadablePartition extends events.EventEmitter {
343
364
  // Optimization if we are at an exact document boundary, where we can just read the document size
344
365
  let reader = this.prepareReadBufferBackwards(position);
345
366
  const block = reader.buffer.toString('ascii', reader.cursor - separatorSize, reader.cursor);
346
- if (block === DOCUMENT_SEPARATOR) {
347
- const dataSize = reader.buffer.readUInt32BE(reader.cursor - separatorSize - 4);
348
- return position - this.documentWriteSize(dataSize);
367
+ const documentStart = block === DOCUMENT_SEPARATOR && this.documentStartBefore(position);
368
+ if (documentStart !== false) {
369
+ return documentStart;
349
370
  }
350
371
 
351
- do {
372
+ while (position - separatorSize >= DOCUMENT_HEADER_SIZE + DOCUMENT_FOOTER_SIZE) {
352
373
  reader = this.prepareReadBufferBackwards(position - separatorSize);
353
374
 
354
375
  const bufferSeparatorPosition = reader.buffer.lastIndexOf(DOCUMENT_SEPARATOR, reader.cursor - separatorSize, 'ascii');
355
376
  if (bufferSeparatorPosition >= 0) {
356
377
  position = this.readBufferPos + bufferSeparatorPosition + separatorSize;
357
- break;
378
+ // The separator bytes can also occur inside a document header, e.g. in the timestamp
379
+ if (this.documentStartBefore(position) !== false) {
380
+ return position;
381
+ }
382
+ } else {
383
+ // Continue so that a separator crossing the start of the buffer is found as well
384
+ position = this.readBufferPos + 2 * separatorSize;
358
385
  }
359
- position -= this.readBufferLength;
360
- } while (position > 0);
361
- return Math.max(0, position);
386
+ }
387
+ return 0;
388
+ }
389
+
390
+ /**
391
+ * Verify that a document ends at the given position and return its start.
392
+ *
393
+ * @private
394
+ * @param {number} documentEnd The position right after a document separator.
395
+ * @returns {number|boolean} The start position of the document or false if no document ends at that position.
396
+ */
397
+ documentStartBefore(documentEnd) {
398
+ if (documentEnd % DOCUMENT_ALIGNMENT !== 0 || documentEnd < DOCUMENT_HEADER_SIZE + DOCUMENT_FOOTER_SIZE) {
399
+ return false;
400
+ }
401
+ const footer = this.prepareReadBufferBackwards(documentEnd);
402
+ const dataSize = footer.buffer.readUInt32BE(footer.cursor - DOCUMENT_FOOTER_SIZE);
403
+ const documentStart = documentEnd - this.documentWriteSize(dataSize);
404
+ const header = documentStart >= 0 && this.prepareReadBuffer(documentStart);
405
+ return header?.buffer?.readUInt32BE(header.cursor) === dataSize ? documentStart : false;
362
406
  }
363
407
 
364
408
  /**