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.
@@ -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;
@@ -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
  /**
@@ -1,8 +1,9 @@
1
1
  import fs from 'fs';
2
+ import path from 'path';
2
3
  import ReadablePartition, { CorruptFileError, HEADER_MAGIC, DOCUMENT_ALIGNMENT, DOCUMENT_SEPARATOR, DOCUMENT_HEADER_SIZE, DOCUMENT_FOOTER_SIZE } from './ReadablePartition.js';
3
4
  import { assert, alignTo } 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 Clock from '../Clock.js';
7
8
 
8
9
  const DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024;
@@ -22,6 +23,7 @@ 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).
25
27
  * @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
28
  * @param {object} [config.metadata] A metadata object that will be written to the file header.
27
29
  * @param {typeof Clock} [config.clock] The constructor to a clock interface
@@ -31,6 +33,7 @@ class WritablePartition extends ReadablePartition {
31
33
  writeBufferSize: DEFAULT_WRITE_BUFFER_SIZE,
32
34
  maxWriteBufferDocuments: 0,
33
35
  syncOnFlush: false,
36
+ syncInterval: 0,
34
37
  dirtyReads: true,
35
38
  metadata: {
36
39
  epoch: Date.now()
@@ -45,6 +48,9 @@ class WritablePartition extends ReadablePartition {
45
48
  this.writeBufferSize = config.writeBufferSize >>> 0; // jshint ignore:line
46
49
  this.maxWriteBufferDocuments = config.maxWriteBufferDocuments >>> 0; // jshint ignore:line
47
50
  this.syncOnFlush = !!config.syncOnFlush;
51
+ this.syncInterval = this.syncOnFlush ? 0 : config.syncInterval >>> 0; // jshint ignore:line
52
+ this.syncTimeout = null;
53
+ this.syncCallbacks = [];
48
54
  this.dirtyReads = !!config.dirtyReads;
49
55
  this.metadata = config.metadata;
50
56
  assert(typeof(config.clock.prototype) === 'object' && typeof(config.clock.prototype.time) === 'function', 'Clock needs to implement the method time()');
@@ -93,6 +99,9 @@ class WritablePartition extends ReadablePartition {
93
99
  * @returns void
94
100
  */
95
101
  close() {
102
+ if (this.syncTimeout !== null) {
103
+ this.sync();
104
+ }
96
105
  super.close();
97
106
  if (this.writeBuffer) {
98
107
  this.writeBuffer = null;
@@ -113,6 +122,7 @@ class WritablePartition extends ReadablePartition {
113
122
  }
114
123
  this.flush();
115
124
  fs.fsyncSync(fd);
125
+ this.invokeSyncCallbacks();
116
126
  }
117
127
 
118
128
  /**
@@ -125,6 +135,9 @@ class WritablePartition extends ReadablePartition {
125
135
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
126
136
  fs.writeFileSync(this.fileName, metadataBuffer);
127
137
  this.headerSize = metadataBuffer.byteLength;
138
+ if (this.syncOnFlush || this.syncInterval > 0) {
139
+ syncDirectory(path.dirname(this.fileName));
140
+ }
128
141
  }
129
142
 
130
143
  /**
@@ -151,11 +164,54 @@ class WritablePartition extends ReadablePartition {
151
164
  this.writeBufferDocuments = 0;
152
165
  const callbacks = this.flushCallbacks;
153
166
  this.flushCallbacks = [];
154
- for (let i = 0; i < callbacks.length; i++) callbacks[i]();
167
+ if (this.syncInterval > 0) {
168
+ this.scheduleSync(callbacks);
169
+ } else {
170
+ for (let i = 0; i < callbacks.length; i++) callbacks[i]();
171
+ }
155
172
 
156
173
  return true;
157
174
  }
158
175
 
176
+ /**
177
+ * Group commit: many flushes share one fsync, and their callbacks only fire once the data is on disk.
178
+ *
179
+ * @private
180
+ * @param {Array<function>} callbacks
181
+ */
182
+ scheduleSync(callbacks) {
183
+ for (let i = 0; i < callbacks.length; i++) this.syncCallbacks.push(callbacks[i]);
184
+ if (this.syncTimeout === null) {
185
+ this.syncTimeout = setTimeout(() => this.sync(), this.syncInterval);
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Flush the write buffer and fsync the file, then invoke all callbacks waiting for durability.
191
+ *
192
+ * @api
193
+ */
194
+ sync() {
195
+ if (this.isOpen()) {
196
+ this.flush();
197
+ fs.fsyncSync(this.getFileHandle());
198
+ }
199
+ if (this.syncTimeout !== null) {
200
+ clearTimeout(this.syncTimeout);
201
+ this.syncTimeout = null;
202
+ }
203
+ this.invokeSyncCallbacks();
204
+ }
205
+
206
+ /**
207
+ * @private
208
+ */
209
+ invokeSyncCallbacks() {
210
+ const callbacks = this.syncCallbacks;
211
+ this.syncCallbacks = [];
212
+ for (let i = 0; i < callbacks.length; i++) callbacks[i]();
213
+ }
214
+
159
215
  /**
160
216
  * @private
161
217
  * @param {number} dataSize The size of the data that needs to go into the write buffer next.
@@ -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
  }