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,7 +1,7 @@
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
- import {normalizeRevision} from './utils/apiHelpers.js';
4
+ import {normalizeMaxRevision, normalizeRevision} from './utils/apiHelpers.js';
5
5
 
6
6
  /**
7
7
  * JoinEventStream is a virtual stream over one or multiple physical stream indexes.
@@ -37,121 +37,68 @@ class JoinEventStream extends EventStream {
37
37
  this.selector = normalizeSelector(selector);
38
38
  this.streamIndex = eventStore.storage.index;
39
39
  this.minRevision = normalizeRevision(minRevision, eventStore.length);
40
- this.maxRevision = normalizeRevision(maxRevision, eventStore.length);
40
+ this.maxRevision = normalizeMaxRevision(eventStore.length, maxRevision);
41
41
  this.version = this.streamIndex.length;
42
42
 
43
- 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) || [];
76
+ const combine = depth % 2 === 0 ? union : intersect;
77
+ return ranges.reduce((left, right) => combine(left, right, forwards));
110
78
  }
111
79
 
112
80
  /**
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);
122
- }
123
-
124
- /**
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() {
87
+ // Revisions counted from the end are already resolved and the upper bound is clamped to the end, so anything
88
+ // below 1 here lies before the first event. A range that starts outside the store is empty, like for a single
89
+ // stream. Clamping the start too would turn a read from beyond the end into a backwards read.
90
+ const length = this.eventStore.length;
91
+ if (this.minRevision < 1 || this.minRevision > length || this.maxRevision < 1) {
92
+ return;
93
+ }
131
94
  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
- );
95
+ for (const entry of this.resolveSelectorRange(this.selector)) {
96
+ const event = this.eventStore.storage.readFrom(entry.partition, entry.position, entry.size, this.raw, !forwards);
140
97
  if (event) {
141
98
  yield event;
142
99
  }
143
100
  }
144
101
  }
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
102
  }
156
103
 
157
104
  export default JoinEventStream;
@@ -364,22 +364,45 @@ class ReadablePartition extends events.EventEmitter {
364
364
  // Optimization if we are at an exact document boundary, where we can just read the document size
365
365
  let reader = this.prepareReadBufferBackwards(position);
366
366
  const block = reader.buffer.toString('ascii', reader.cursor - separatorSize, reader.cursor);
367
- if (block === DOCUMENT_SEPARATOR) {
368
- const dataSize = reader.buffer.readUInt32BE(reader.cursor - separatorSize - 4);
369
- return position - this.documentWriteSize(dataSize);
367
+ const documentStart = block === DOCUMENT_SEPARATOR && this.documentStartBefore(position);
368
+ if (documentStart !== false) {
369
+ return documentStart;
370
370
  }
371
371
 
372
- do {
372
+ while (position - separatorSize >= DOCUMENT_HEADER_SIZE + DOCUMENT_FOOTER_SIZE) {
373
373
  reader = this.prepareReadBufferBackwards(position - separatorSize);
374
374
 
375
375
  const bufferSeparatorPosition = reader.buffer.lastIndexOf(DOCUMENT_SEPARATOR, reader.cursor - separatorSize, 'ascii');
376
376
  if (bufferSeparatorPosition >= 0) {
377
377
  position = this.readBufferPos + bufferSeparatorPosition + separatorSize;
378
- 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;
379
385
  }
380
- position -= this.readBufferLength;
381
- } while (position > 0);
382
- 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;
383
406
  }
384
407
 
385
408
  /**
@@ -4,6 +4,7 @@ import { assert, alignTo } from '../utils/util.js';
4
4
  import { buildMetadataHeader } from '../utils/metadataUtil.js';
5
5
  import { ensureDirectory } from '../utils/fsUtil.js';
6
6
  import Clock from '../Clock.js';
7
+ import SyncScheduler from '../SyncScheduler.js';
7
8
 
8
9
  const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
9
10
  const DOCUMENT_PAD = ' '.repeat(DOCUMENT_ALIGNMENT);
@@ -22,6 +23,8 @@ class WritablePartition extends ReadablePartition {
22
23
  * @param {number} [config.writeBufferSize] Size of the write buffer in bytes. Default 16384.
23
24
  * @param {number} [config.maxWriteBufferDocuments] How many documents to have in the write buffer at max. 0 means as much as possible. Default 0.
24
25
  * @param {boolean} [config.syncOnFlush] If fsync should be called on write buffer flush. Set this if you need strict durability. Defaults to false.
26
+ * @param {number} [config.syncInterval] Call fsync at most every this many ms and only invoke write callbacks after it. Ignored when `syncOnFlush` is set. Defaults to 0 (off).
27
+ * @param {SyncScheduler} [config.syncScheduler] The scheduler that syncs the flushes, shared by all files of a storage. Defaults to one for this partition, configured by `syncOnFlush` and `syncInterval`.
25
28
  * @param {boolean} [config.dirtyReads] If dirty reads should be allowed. This means that writes that are in write buffer but not yet flushed can be read. Defaults to true.
26
29
  * @param {object} [config.metadata] A metadata object that will be written to the file header.
27
30
  * @param {typeof Clock} [config.clock] The constructor to a clock interface
@@ -31,6 +34,7 @@ class WritablePartition extends ReadablePartition {
31
34
  writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
32
35
  maxWriteBufferDocuments: 0,
33
36
  syncOnFlush: false,
37
+ syncInterval: 0,
34
38
  dirtyReads: true,
35
39
  metadata: {
36
40
  epoch: Date.now()
@@ -44,7 +48,7 @@ class WritablePartition extends ReadablePartition {
44
48
  this.fileMode = 'a+';
45
49
  this.writeBufferSize = config.writeBufferSize >>> 0; // jshint ignore:line
46
50
  this.maxWriteBufferDocuments = config.maxWriteBufferDocuments >>> 0; // jshint ignore:line
47
- this.syncOnFlush = !!config.syncOnFlush;
51
+ this.syncScheduler = config.syncScheduler || new SyncScheduler({ syncOnFlush: config.syncOnFlush, syncInterval: config.syncInterval >>> 0 }); // jshint ignore:line
48
52
  this.dirtyReads = !!config.dirtyReads;
49
53
  this.metadata = config.metadata;
50
54
  assert(typeof(config.clock.prototype) === 'object' && typeof(config.clock.prototype.time) === 'function', 'Clock needs to implement the method time()');
@@ -93,6 +97,12 @@ class WritablePartition extends ReadablePartition {
93
97
  * @returns void
94
98
  */
95
99
  close() {
100
+ if (this.writeBuffer) {
101
+ this.flush();
102
+ }
103
+ if (this.syncScheduler.isWaiting(this)) {
104
+ this.syncScheduler.run();
105
+ }
96
106
  super.close();
97
107
  if (this.writeBuffer) {
98
108
  this.writeBuffer = null;
@@ -103,16 +113,20 @@ class WritablePartition extends ReadablePartition {
103
113
  }
104
114
 
105
115
  /**
106
- * Flush pending buffered writes before the pool closes the descriptor.
116
+ * Flush pending buffered writes before the pool closes the descriptor. Closing the partition also syncs it. An
117
+ * eviction does not: a flush waiting for a sync is synced by the scheduler, through its own descriptor if needed.
107
118
  *
108
119
  * @param {number} fd
120
+ * @param {boolean} evicted
109
121
  */
110
- onBeforeClose(fd) {
122
+ onBeforeClose(fd, evicted) {
111
123
  if (!this.writeBuffer) {
112
124
  return;
113
125
  }
114
126
  this.flush();
115
- fs.fsyncSync(fd);
127
+ if (!evicted) {
128
+ fs.fsyncSync(fd);
129
+ }
116
130
  }
117
131
 
118
132
  /**
@@ -125,6 +139,7 @@ class WritablePartition extends ReadablePartition {
125
139
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
126
140
  fs.writeFileSync(this.fileName, metadataBuffer);
127
141
  this.headerSize = metadataBuffer.byteLength;
142
+ this.syncScheduler.created(this);
128
143
  }
129
144
 
130
145
  /**
@@ -141,21 +156,32 @@ class WritablePartition extends ReadablePartition {
141
156
  return false;
142
157
  }
143
158
 
144
- const fd = this.getFileHandle();
145
- fs.writeSync(fd, this.writeBuffer, 0, this.writeBufferCursor);
146
- if (this.syncOnFlush) {
147
- fs.fsyncSync(fd);
148
- }
149
-
159
+ fs.writeSync(this.getFileHandle(), this.writeBuffer, 0, this.writeBufferCursor);
150
160
  this.writeBufferCursor = 0;
151
161
  this.writeBufferDocuments = 0;
152
162
  const callbacks = this.flushCallbacks;
153
163
  this.flushCallbacks = [];
154
- for (let i = 0; i < callbacks.length; i++) callbacks[i]();
164
+ this.syncScheduler.flushed(this, callbacks);
155
165
 
156
166
  return true;
157
167
  }
158
168
 
169
+ /**
170
+ * Flush the write buffer and fsync the file, then invoke all callbacks waiting for durability, including those of
171
+ * other files of the same storage.
172
+ *
173
+ * @api
174
+ */
175
+ sync() {
176
+ if (this.isOpen()) {
177
+ this.flush();
178
+ }
179
+ this.syncScheduler.run();
180
+ if (this.isOpen()) {
181
+ this.fileHandlePool.sync(this);
182
+ }
183
+ }
184
+
159
185
  /**
160
186
  * @private
161
187
  * @param {number} dataSize The size of the data that needs to go into the write buffer next.
@@ -238,9 +264,7 @@ class WritablePartition extends ReadablePartition {
238
264
  this.writeMetaBuffer.writeUInt32BE(dataSize, 0);
239
265
  bytesWritten += fs.writeSync(fd, this.writeMetaBuffer, 0, 4);
240
266
  bytesWritten += fs.writeSync(fd, DOCUMENT_SEPARATOR);
241
- if (typeof callback === 'function') {
242
- process.nextTick(callback);
243
- }
267
+ this.syncScheduler.flushed(this, typeof callback === 'function' ? [() => process.nextTick(callback)] : []);
244
268
  return bytesWritten;
245
269
  }
246
270
 
@@ -0,0 +1,164 @@
1
+ import { assert } from './utils/util.js';
2
+ import { matchesDcbQuery } from './utils/dcbUtil.js';
3
+
4
+ /**
5
+ * @typedef {object} ProjectionDefinition
6
+ * @property {any} initialState The state before any event was applied.
7
+ * @property {Object<string, function(any, object, object): any>} when Pure reducers keyed by event type.
8
+ * Each receives `(state, event, metadata)` and returns the new state.
9
+ * @property {string[]} [tagFilter] Tags that every handled event must carry (AND semantics).
10
+ */
11
+
12
+ /**
13
+ * @typedef {object} Projection
14
+ * @property {any} initialState
15
+ * @property {{ items: Array<{ types?: string[], tags?: string[] }> }} query The DcbQuery selecting all events this
16
+ * projection needs.
17
+ * @property {function(any, object, object, {type: string, tags: string[]}): any} apply Apply one event. Events that
18
+ * do not match `query` leave the state unchanged.
19
+ */
20
+
21
+ /**
22
+ * Create a projection in the dcb.events declarative format.
23
+ * The query is derived from the event types in `when` and the tag filter.
24
+ *
25
+ * @param {ProjectionDefinition} definition
26
+ * @returns {Projection}
27
+ */
28
+ function createProjection({ initialState = null, when, tagFilter = [] }) {
29
+ assert(when !== null && typeof when === 'object', 'A projection needs a `when` object with one handler per event type.');
30
+ const types = Object.keys(when);
31
+ assert(types.length > 0, 'A projection needs at least one event handler.');
32
+ assert(Array.isArray(tagFilter), 'Projection tagFilter must be an array of tags.');
33
+ const query = { items: [tagFilter.length ? { types, tags: [...tagFilter] } : { types }] };
34
+ return Object.freeze({
35
+ initialState,
36
+ query,
37
+ apply(state, event, metadata, { type, tags }) {
38
+ if (!matchesDcbQuery(query, type, tags)) return state;
39
+ return when[type](state, event, metadata);
40
+ }
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Compose several projections into one. The state is an object with one key per projection, the query
46
+ * is the OR of all sub-queries, and each event is only applied to the projections whose query it matches.
47
+ *
48
+ * @param {Object<string, Projection>} projections
49
+ * @returns {Projection}
50
+ */
51
+ function composeProjections(projections) {
52
+ const entries = Object.entries(projections);
53
+ assert(entries.length > 0, 'Need at least one projection to compose.');
54
+ const initialState = Object.fromEntries(entries.map(([key, p]) => [key, p.initialState]));
55
+ const query = { items: entries.flatMap(([, p]) => p.query.items) };
56
+ return Object.freeze({
57
+ initialState,
58
+ query,
59
+ apply(state, event, metadata, context) {
60
+ const next = { ...state };
61
+ for (const [key, projection] of entries) {
62
+ next[key] = projection.apply(state[key], event, metadata, context);
63
+ }
64
+ return next;
65
+ }
66
+ });
67
+ }
68
+
69
+ /**
70
+ * @param {any} value
71
+ * @returns {boolean} True if the value looks like a single projection rather than a map of projections.
72
+ */
73
+ function isProjection(value) {
74
+ return value !== null && typeof value === 'object' && typeof value.apply === 'function' && 'query' in value;
75
+ }
76
+
77
+ /**
78
+ * The state of one or more projections at a known position of the store, together with the append condition
79
+ * that protects a decision made on it. Immutable: {@link DecisionModel#update} returns a new model.
80
+ */
81
+ class DecisionModel {
82
+
83
+ /**
84
+ * @param {import('./EventStore.js').default} eventStore
85
+ * @param {Projection} projection
86
+ * @param {any} state
87
+ * @param {import('./EventStore.js').CommitCondition} commitCondition
88
+ */
89
+ constructor(eventStore, projection, state, commitCondition) {
90
+ this.eventStore = eventStore;
91
+ this.projection = projection;
92
+ this.state = state;
93
+ this.commitCondition = commitCondition;
94
+ Object.freeze(this);
95
+ }
96
+
97
+ /**
98
+ * The events matching the condition that were committed after this model was built, i.e. the events that
99
+ * make a commit with that condition fail. Defaults to this model's `commitCondition`; pass a narrowed
100
+ * condition (e.g. from `commitCondition.without(...)`) to get only the events that conflict with it.
101
+ *
102
+ * @param {import('./EventStore.js').CommitCondition} [condition]
103
+ * @returns {import('./EventStream.js').default}
104
+ */
105
+ since(condition = this.commitCondition) {
106
+ return this.eventStore.fromStreams(
107
+ '_since_' + condition.noneMatchAfter,
108
+ condition.selector,
109
+ condition.noneMatchAfter + 1,
110
+ -1,
111
+ condition.matcher,
112
+ condition.raw
113
+ );
114
+ }
115
+
116
+ /**
117
+ * Apply the events committed since this model was built and return the updated model. Only those events are
118
+ * read. Returns this model unchanged when nothing new was committed.
119
+ *
120
+ * @returns {DecisionModel}
121
+ */
122
+ update() {
123
+ if (this.eventStore.length === this.commitCondition.noneMatchAfter) {
124
+ return this;
125
+ }
126
+ return readDecisionModel(this.eventStore, this.projection, this.state, this.commitCondition.noneMatchAfter + 1);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * @param {import('./EventStore.js').default} eventStore
132
+ * @param {Projection} projection
133
+ * @param {any} state The state to apply the events to.
134
+ * @param {number} from The first global position to read.
135
+ * @returns {DecisionModel}
136
+ */
137
+ function readDecisionModel(eventStore, projection, state, from) {
138
+ const { stream, condition } = eventStore.query(projection.query, null, from);
139
+ const typeOf = eventStore.typeSource.accessor;
140
+ const tagsOf = eventStore.tagsSource ? eventStore.tagsSource.accessor : () => [];
141
+ stream.forEach((event, metadata) => {
142
+ const context = { type: typeOf(event), tags: tagsOf(event) ?? [] };
143
+ state = projection.apply(state, event, metadata, context);
144
+ });
145
+ return new DecisionModel(eventStore, projection, state, condition);
146
+ }
147
+
148
+ /**
149
+ * Build a decision model: read all events relevant to the projection(s) and fold them into state.
150
+ * The returned model carries the append condition that protects the decision. After a conflict, or to keep
151
+ * a model in memory across commands, call `model.update()` to only apply the events committed since.
152
+ *
153
+ * @param {import('./EventStore.js').default} eventStore A store configured with `typeAccessor` (and `tagsAccessor`
154
+ * when projections use a tagFilter).
155
+ * @param {Projection|Object<string, Projection>} projectionOrMap A projection, or a map of projections to compose.
156
+ * @returns {DecisionModel}
157
+ */
158
+ function buildDecisionModel(eventStore, projectionOrMap) {
159
+ assert(eventStore.typeSource !== null, 'Projections need the store to be configured with a typeAccessor.');
160
+ const projection = isProjection(projectionOrMap) ? projectionOrMap : composeProjections(projectionOrMap);
161
+ return readDecisionModel(eventStore, projection, projection.initialState, 1);
162
+ }
163
+
164
+ export { createProjection, composeProjections, buildDecisionModel, DecisionModel };
@@ -27,7 +27,7 @@ class ReadOnlyStorage extends ReadableStorage {
27
27
  if (!filename) {
28
28
  return true;
29
29
  }
30
- return !filename.endsWith('.branch') && (filename === this.storageFile || filename.substring(0, this.storageFile.length + 1) === this.storageFile + '.');
30
+ return !filename.endsWith('.branch') && !filename.endsWith('.lock') && (filename === this.storageFile || filename.substring(0, this.storageFile.length + 1) === this.storageFile + '.');
31
31
  }
32
32
 
33
33
  /**
@@ -124,12 +124,7 @@ class ReadOnlyStorage extends ReadableStorage {
124
124
  // If the watcher has been removed, this means this storage was closed and we don't want to handle events any more
125
125
  return;
126
126
  }
127
- const entries = index.range(prevLength + 1, newLength);
128
- /* c8 ignore next 3 */
129
- if (entries === false) {
130
- return;
131
- }
132
- this.processAppendedEntries(index, indexShortName, entries);
127
+ this.processAppendedEntries(index, indexShortName, prevLength + 1, newLength);
133
128
  });
134
129
  index.on('truncate', (prevLength, newLength) => {
135
130
  if (index === this.index) {
@@ -149,15 +144,19 @@ class ReadOnlyStorage extends ReadableStorage {
149
144
  * @private
150
145
  * @param {ReadableIndex} index
151
146
  * @param {string} indexShortName
152
- * @param {IndexEntry[]} entries
153
- * @param {number} [startIndex] The entry offset to resume from on a retry.
147
+ * @param {number} from The 1-based index position of the first appended entry.
148
+ * @param {number} until The 1-based index position of the last appended entry.
154
149
  */
155
- processAppendedEntries(index, indexShortName, entries, startIndex = 0) {
156
- for (let i = startIndex; i < entries.length; i++) {
157
- const entry = entries[i];
150
+ processAppendedEntries(index, indexShortName, from, until) {
151
+ for (let position = from; position <= until; position++) {
152
+ const entry = index.get(position);
153
+ /* c8 ignore next 3 */
154
+ if (entry === false) {
155
+ return;
156
+ }
158
157
  if (!(entry.partition in this.partitions)) {
159
158
  this.scheduleScan(() => {
160
- this.processAppendedEntries(index, indexShortName, entries, i);
159
+ this.processAppendedEntries(index, indexShortName, position, until);
161
160
  });
162
161
  return;
163
162
  }
@@ -3,7 +3,7 @@ import path from 'path';
3
3
  import events from 'events';
4
4
  import { ReadOnly as ReadOnlyPartition } from '../Partition.js';
5
5
  import { ReadOnly as ReadOnlyIndex } from '../Index.js';
6
- import { assert, wrapAndCheck, iterate, kWayMerge } from '../utils/util.js';
6
+ import { assert, wrapAndCheck, kWayMerge } from '../utils/util.js';
7
7
  import { resolvePath, scanForFiles } from '../utils/fsUtil.js';
8
8
  import { createHmac, matches, buildMetadataForMatcher } from '../utils/metadataUtil.js';
9
9
  import { normalizeNamedCtorArgs } from '../utils/apiHelpers.js';
@@ -383,13 +383,9 @@ class ReadableStorage extends events.EventEmitter {
383
383
  }
384
384
 
385
385
  const idx = index || this.index;
386
- const forwards = from <= until;
387
- const lo = Math.min(from, until);
388
- const hi = Math.max(from, until);
389
- const entries = idx.range(lo, hi);
390
- if (!entries) return;
391
- for (const entry of iterate(entries, forwards)) {
392
- yield this.readFrom(entry.partition, entry.position, entry.size, raw, !forwards);
386
+ const backwards = from > until;
387
+ for (const entry of idx.range(from, until)) {
388
+ yield this.readFrom(entry.partition, entry.position, entry.size, raw, backwards);
393
389
  }
394
390
  }
395
391
 
@@ -521,9 +517,8 @@ class ReadableStorage extends events.EventEmitter {
521
517
  return;
522
518
  }
523
519
 
524
- const entries = this.index.all();
525
-
526
- for (let entry of entries) {
520
+ for (let position = 1; position <= this.index.length; position++) {
521
+ const entry = this.index.get(position);
527
522
  const document = this.readFrom(entry.partition, entry.position, entry.size);
528
523
  iterationHandler(document, entry);
529
524
  }