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 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()');
@@ -58,7 +64,7 @@ class WritablePartition extends ReadablePartition {
58
64
  * @returns {boolean}
59
65
  */
60
66
  open() {
61
- if (this.fd) {
67
+ if (this.opened) {
62
68
  return true;
63
69
  }
64
70
 
@@ -93,16 +99,30 @@ class WritablePartition extends ReadablePartition {
93
99
  * @returns void
94
100
  */
95
101
  close() {
96
- if (this.fd && this.writeBuffer) {
97
- this.flush();
98
- fs.fsyncSync(this.fd);
99
-
102
+ if (this.syncTimeout !== null) {
103
+ this.sync();
104
+ }
105
+ super.close();
106
+ if (this.writeBuffer) {
100
107
  this.writeBuffer = null;
101
108
  this.writeBufferCursor = 0;
102
109
  this.writeBufferDocuments = 0;
103
110
  this.writeMetaBuffer = null;
104
111
  }
105
- super.close();
112
+ }
113
+
114
+ /**
115
+ * Flush pending buffered writes before the pool closes the descriptor.
116
+ *
117
+ * @param {number} fd
118
+ */
119
+ onBeforeClose(fd) {
120
+ if (!this.writeBuffer) {
121
+ return;
122
+ }
123
+ this.flush();
124
+ fs.fsyncSync(fd);
125
+ this.invokeSyncCallbacks();
106
126
  }
107
127
 
108
128
  /**
@@ -115,6 +135,9 @@ class WritablePartition extends ReadablePartition {
115
135
  const metadataBuffer = buildMetadataHeader(HEADER_MAGIC, this.metadata);
116
136
  fs.writeFileSync(this.fileName, metadataBuffer);
117
137
  this.headerSize = metadataBuffer.byteLength;
138
+ if (this.syncOnFlush || this.syncInterval > 0) {
139
+ syncDirectory(path.dirname(this.fileName));
140
+ }
118
141
  }
119
142
 
120
143
  /**
@@ -124,27 +147,71 @@ class WritablePartition extends ReadablePartition {
124
147
  * @returns {boolean}
125
148
  */
126
149
  flush() {
127
- if (!this.fd) {
150
+ if (!this.isOpen()) {
128
151
  return false;
129
152
  }
130
153
  if (this.writeBufferCursor === 0) {
131
154
  return false;
132
155
  }
133
156
 
134
- fs.writeSync(this.fd, this.writeBuffer, 0, this.writeBufferCursor);
157
+ const fd = this.getFileHandle();
158
+ fs.writeSync(fd, this.writeBuffer, 0, this.writeBufferCursor);
135
159
  if (this.syncOnFlush) {
136
- fs.fsyncSync(this.fd);
160
+ fs.fsyncSync(fd);
137
161
  }
138
162
 
139
163
  this.writeBufferCursor = 0;
140
164
  this.writeBufferDocuments = 0;
141
165
  const callbacks = this.flushCallbacks;
142
166
  this.flushCallbacks = [];
143
- 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
+ }
144
172
 
145
173
  return true;
146
174
  }
147
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
+
148
215
  /**
149
216
  * @private
150
217
  * @param {number} dataSize The size of the data that needs to go into the write buffer next.
@@ -217,15 +284,16 @@ class WritablePartition extends ReadablePartition {
217
284
  writeUnbuffered(data, dataSize, sequenceNumber, callback) {
218
285
  this.flush();
219
286
  this.writeDocumentHeader(this.writeMetaBuffer, 0, dataSize, sequenceNumber);
287
+ const fd = this.getFileHandle();
220
288
 
221
289
  let bytesWritten = 0;
222
- bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, DOCUMENT_HEADER_SIZE);
223
- bytesWritten += fs.writeSync(this.fd, data);
290
+ bytesWritten += fs.writeSync(fd, this.writeMetaBuffer, 0, DOCUMENT_HEADER_SIZE);
291
+ bytesWritten += fs.writeSync(fd, data);
224
292
  const padSize = alignTo(dataSize + DOCUMENT_FOOTER_SIZE, DOCUMENT_ALIGNMENT);
225
- bytesWritten += fs.writeSync(this.fd, DOCUMENT_PAD.substring(0, padSize));
293
+ bytesWritten += fs.writeSync(fd, DOCUMENT_PAD.substring(0, padSize));
226
294
  this.writeMetaBuffer.writeUInt32BE(dataSize, 0);
227
- bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, 4);
228
- bytesWritten += fs.writeSync(this.fd, DOCUMENT_SEPARATOR);
295
+ bytesWritten += fs.writeSync(fd, this.writeMetaBuffer, 0, 4);
296
+ bytesWritten += fs.writeSync(fd, DOCUMENT_SEPARATOR);
229
297
  if (typeof callback === 'function') {
230
298
  process.nextTick(callback);
231
299
  }
@@ -270,7 +338,7 @@ class WritablePartition extends ReadablePartition {
270
338
  * @returns {number|boolean} The file position at which the data was written or false on error.
271
339
  */
272
340
  write(data, sequenceNumber, callback) {
273
- assert(this.fd, 'Partition is not opened.');
341
+ this.getFileHandle();
274
342
  ({ sequenceNumber, callback } = this.normalizeWriteArguments(sequenceNumber, callback));
275
343
  const dataSize = Buffer.byteLength(data, 'utf8');
276
344
  assert(dataSize <= 64 * 1024 * 1024, 'Document is too large! Maximum is 64 MB');
@@ -419,9 +487,10 @@ class WritablePartition extends ReadablePartition {
419
487
  branchOff(branchName, position) {
420
488
  const deletedBranch = new WritablePartition(this.name + '-' + branchName + '-' + position + '.branch', { dataDirectory: this.dataDirectory, metadata: { epoch: this.metadata.epoch } });
421
489
  deletedBranch.open();
490
+ const branchFd = deletedBranch.getFileHandle();
422
491
  do {
423
492
  const reader = this.prepareReadBuffer(position);
424
- fs.writeSync(deletedBranch.fd, reader.buffer, reader.cursor, reader.length);
493
+ fs.writeSync(branchFd, reader.buffer, reader.cursor, reader.length);
425
494
  position += reader.length;
426
495
  } while (position < this.size);
427
496
  deletedBranch.close();
@@ -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];
158
- if (!this.partitions.has(entry.partition)) {
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
+ }
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,12 +3,12 @@ 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';
10
10
  import IndexMatcher from '../IndexMatcher.js';
11
- import PartitionPool from '../PartitionPool.js';
11
+ import FileHandlePool from '../FileHandlePool.js';
12
12
  import ReadablePartition from "../Partition/ReadablePartition.js";
13
13
 
14
14
  const DEFAULT_READ_BUFFER_SIZE = 4 * 1024;
@@ -27,6 +27,7 @@ const DEFAULT_MATCHER_PROPERTIES = ['stream', 'payload.type'];
27
27
  * Partitions beyond this limit are evicted using LRU order. 0 disables the limit.
28
28
  */
29
29
  const DEFAULT_MAX_OPEN_PARTITIONS = 1024;
30
+ const DEFAULT_MAX_OPEN_INDEXES = 1024;
30
31
 
31
32
  /**
32
33
  * @typedef {object|function(object):boolean} Matcher
@@ -58,9 +59,13 @@ class ReadableStorage extends events.EventEmitter {
58
59
  * @param {number} [config.maxOpenPartitions] Maximum number of partition file descriptors kept open at one time.
59
60
  * When the limit is reached the least-recently-used partition is closed to make room. 0 disables the limit.
60
61
  * Default: 1024.
62
+ * @param {number} [config.maxOpenIndexes] Maximum number of index file descriptors kept open at one time.
63
+ * When the limit is reached the least-recently-used index handle is closed to make room. 0 disables the limit.
64
+ * Default: 1024.
61
65
  */
62
66
  constructor(storageName = 'storage', config = {}) {
63
67
  super();
68
+ this.setMaxListeners(0);
64
69
  ({ name: storageName, options: config } = normalizeNamedCtorArgs(storageName, config));
65
70
 
66
71
  this.storageFile = storageName || 'storage';
@@ -72,7 +77,8 @@ class ReadableStorage extends events.EventEmitter {
72
77
  hmacSecret: '',
73
78
  metadata: {},
74
79
  matcherProperties: DEFAULT_MATCHER_PROPERTIES,
75
- maxOpenPartitions: DEFAULT_MAX_OPEN_PARTITIONS
80
+ maxOpenPartitions: DEFAULT_MAX_OPEN_PARTITIONS,
81
+ maxOpenIndexes: DEFAULT_MAX_OPEN_INDEXES
76
82
  };
77
83
  config = Object.assign(defaults, config);
78
84
  this.serializer = config.serializer;
@@ -83,7 +89,9 @@ class ReadableStorage extends events.EventEmitter {
83
89
 
84
90
  const partitionDefaults = { readBufferSize: DEFAULT_READ_BUFFER_SIZE };
85
91
  this.partitionConfig = Object.assign(partitionDefaults, config);
86
- this.partitions = new PartitionPool(config.maxOpenPartitions);
92
+ this.partitionHandlePool = new FileHandlePool(config.maxOpenPartitions);
93
+ this.indexHandlePool = new FileHandlePool(config.maxOpenIndexes);
94
+ this.partitions = Object.create(null);
87
95
 
88
96
  // initialized: null = not started (or scan cancelled), false = in progress, true = done
89
97
  this.initialized = null;
@@ -99,7 +107,7 @@ class ReadableStorage extends events.EventEmitter {
99
107
  */
100
108
  createIndex(name, options = {}) {
101
109
  /** @type ReadableIndex */
102
- const index = new ReadOnlyIndex(name, options);
110
+ const index = new ReadOnlyIndex(name, { ...options, fileHandlePool: this.indexHandlePool });
103
111
  return { index };
104
112
  }
105
113
 
@@ -110,7 +118,7 @@ class ReadableStorage extends events.EventEmitter {
110
118
  * @returns {ReadablePartition}
111
119
  */
112
120
  createPartition(name, options = {}) {
113
- return new ReadOnlyPartition(name, options);
121
+ return new ReadOnlyPartition(name, { ...options, fileHandlePool: this.partitionHandlePool });
114
122
  }
115
123
 
116
124
  /**
@@ -154,9 +162,9 @@ class ReadableStorage extends events.EventEmitter {
154
162
  */
155
163
  registerPartitionFile(filename) {
156
164
  const partitionId = ReadablePartition.idFor(filename);
157
- if (!this.partitions.has(partitionId)) {
165
+ if (!(partitionId in this.partitions)) {
158
166
  const partition = this.createPartition(filename, this.partitionConfig);
159
- this.partitions.add(partition.id, partition);
167
+ this.partitions[partition.id] = partition;
160
168
  this.emit('partition-created', partition.id);
161
169
  }
162
170
  return partitionId;
@@ -254,6 +262,7 @@ class ReadableStorage extends events.EventEmitter {
254
262
  for (let index of Object.values(this.readonlyIndexes)) {
255
263
  index.close();
256
264
  }
265
+ this.readonlyIndexes = {};
257
266
  this.forEachPartition(partition => partition.close());
258
267
  this.emit('closed');
259
268
  }
@@ -268,8 +277,10 @@ class ReadableStorage extends events.EventEmitter {
268
277
  * @throws {Error} If no such partition exists.
269
278
  */
270
279
  getPartition(partitionIdentifier) {
271
- assert(this.partitions.has(partitionIdentifier), `Partition #${partitionIdentifier} does not exist.`);
272
- return this.partitions.open(partitionIdentifier);
280
+ assert(partitionIdentifier in this.partitions, `Partition #${partitionIdentifier} does not exist.`);
281
+ const partition = this.partitions[partitionIdentifier];
282
+ partition.open();
283
+ return partition;
273
284
  }
274
285
 
275
286
  /**
@@ -372,13 +383,9 @@ class ReadableStorage extends events.EventEmitter {
372
383
  }
373
384
 
374
385
  const idx = index || this.index;
375
- const forwards = from <= until;
376
- const lo = Math.min(from, until);
377
- const hi = Math.max(from, until);
378
- const entries = idx.range(lo, hi);
379
- if (!entries) return;
380
- for (const entry of iterate(entries, forwards)) {
381
- 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);
382
389
  }
383
390
  }
384
391
 
@@ -510,9 +517,8 @@ class ReadableStorage extends events.EventEmitter {
510
517
  return;
511
518
  }
512
519
 
513
- const entries = this.index.all();
514
-
515
- for (let entry of entries) {
520
+ for (let position = 1; position <= this.index.length; position++) {
521
+ const entry = this.index.get(position);
516
522
  const document = this.readFrom(entry.partition, entry.position, entry.size);
517
523
  iterationHandler(document, entry);
518
524
  }
@@ -559,7 +565,9 @@ class ReadableStorage extends events.EventEmitter {
559
565
  return;
560
566
  }
561
567
 
562
- this.partitions.forEach(iterationHandler);
568
+ for (const partitionId of Object.keys(this.partitions)) {
569
+ iterationHandler(this.partitions[partitionId]);
570
+ }
563
571
  }
564
572
 
565
573
  }