Skip to content

Commit 0c5d557

Browse files
authored
Merge origin/main and resolve conflicts
2 parents a949838 + cae6036 commit 0c5d557

9 files changed

Lines changed: 33 additions & 50 deletions

File tree

src/EventStore.js

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -403,11 +403,7 @@ class EventStore extends events.EventEmitter {
403403
condition.raw
404404
);
405405

406-
if (stream.next() !== false) {
407-
throw new OptimisticConcurrencyError(
408-
`Optimistic Concurrency error. A conflicting event was committed since the condition was obtained.`
409-
);
410-
}
406+
assert(stream.next() === false, `Optimistic Concurrency error. A conflicting event was committed since the condition was obtained.`, OptimisticConcurrencyError);
411407
}
412408

413409
/**
@@ -490,9 +486,10 @@ class EventStore extends events.EventEmitter {
490486
}
491487
assert(!this.streams[streamName].closed, `Stream "${streamName}" is closed and cannot be written to.`);
492488
let streamVersion = this.streams[streamName].index.length;
493-
if (expectedVersion !== ExpectedVersion.Any && streamVersion !== expectedVersion) {
494-
throw new OptimisticConcurrencyError(`Optimistic Concurrency error. Expected stream "${streamName}" at version ${expectedVersion} but is at version ${streamVersion}.`);
495-
}
489+
assert(expectedVersion === ExpectedVersion.Any || streamVersion === expectedVersion,
490+
`Optimistic Concurrency error. Expected stream "${streamName}" at version ${expectedVersion} but is at version ${streamVersion}.`,
491+
OptimisticConcurrencyError
492+
);
496493

497494
if (events.length > 1) {
498495
delete metadata.commitVersion;
@@ -668,9 +665,8 @@ class EventStore extends events.EventEmitter {
668665
streamName.startsWith(categoryName + '/')
669666
);
670667

671-
if (categoryStreams.length === 0) {
672-
throw new Error(`No streams for category '${categoryName}' exist.`);
673-
}
668+
assert(categoryStreams.length > 0, `No streams for category '${categoryName}' exist.`);
669+
674670
return this.fromStreams(categoryName, categoryStreams, minRevision, maxRevision, predicate, raw);
675671
}
676672

src/Index/ReadableIndex.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ class ReadableIndex extends events.EventEmitter {
7777
if (options.metadata) {
7878
this.metadata = Object.assign({entryClass: options.EntryClass.name, entrySize: options.EntryClass.size}, options.metadata);
7979
}
80+
this.headerSize = 0;
8081
}
8182

8283
/**
@@ -208,12 +209,13 @@ class ReadableIndex extends events.EventEmitter {
208209
* @throws {Error} if the metadata size in the header is invalid.
209210
*/
210211
readMetadata() {
212+
if (this.headerSize > 0) return this.headerSize;
211213
const headerBuffer = Buffer.allocUnsafe(8 + 4);
212214
fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
213215
const headerMagic = headerBuffer.toString('utf8', 0, 8);
214216

215-
assert(headerMagic.substr(0, 6) === HEADER_MAGIC.substr(0, 6), 'Invalid file header.');
216-
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The index ${this.fileName} was created with a different library version (${headerMagic.substr(6)}).`);
217+
assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), 'Invalid file header.');
218+
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The index ${this.fileName} was created with a different library version (${headerMagic.substring(6)}).`);
217219

218220
const metadataSize = headerBuffer.readUInt32BE(8);
219221
assert(metadataSize >= 3, 'Invalid metadata size.');

src/Index/WritableIndex.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from 'fs';
22
import ReadableIndex, { Entry, CorruptedIndexError, HEADER_MAGIC } from './ReadableIndex.js';
3-
import { assertEqual } from '../utils/util.js';
3+
import { assert, assertEqual } from '../utils/util.js';
44
import { buildMetadataHeader } from '../utils/metadataUtil.js';
55
import { ensureDirectory } from '../utils/fsUtil.js';
66

@@ -191,9 +191,7 @@ class WritableIndex extends ReadableIndex {
191191
assertEqual(entry.constructor.size, this.EntryClass.size, `Invalid entry size.`);
192192

193193
const dataLen = this.data.length;
194-
if (dataLen > 0 && this.data[dataLen - 1].number >= entry.number) {
195-
throw new Error('Consistency error. Tried to add an index that should come before existing last entry.');
196-
}
194+
assert(dataLen === 0 || this.data.at(-1).number < entry.number, 'Consistency error. Tried to add an index that should come before existing last entry.');
197195

198196
if (this.readUntil === dataLen - 1) {
199197
this.readUntil++;

src/JoinEventStream.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import EventStream from './EventStream.js';
2-
import { kWayMerge } from './utils/util.js';
2+
import { assert, kWayMerge } from './utils/util.js';
33

44
/** Reusable sentinel used for missing or empty per-stream iterators. */
55
const emptyIterator = Object.freeze({ next() { return { done: true }; } });
@@ -32,9 +32,7 @@ class JoinEventStream extends EventStream {
3232
*/
3333
constructor(name, streams, eventStore, minRevision = 1, maxRevision = -1, predicate = null, raw = false) {
3434
super(name, eventStore, minRevision, maxRevision, predicate, raw);
35-
if (!(streams instanceof Array) || streams.length === 0) {
36-
throw new Error(`Invalid list of streams supplied to JoinStream ${name}.`);
37-
}
35+
assert(streams instanceof Array && streams.length > 0, `Invalid list of streams supplied to JoinStream ${name}.`);
3836

3937
this.streamIndex = eventStore.storage.index;
4038
// Translate revisions to index numbers (1-based) and wrap around negatives

src/Partition/ReadablePartition.js

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@ class ReadablePartition extends events.EventEmitter {
116116
fs.readSync(this.fd, headerBuffer, 0, 8 + 4, 0);
117117
const headerMagic = headerBuffer.toString('utf8', 0, 8);
118118

119-
assert(headerMagic.substr(0, 6) === HEADER_MAGIC.substr(0, 6), `Invalid file header in partition ${this.name}.`);
119+
assert(headerMagic.substring(0, 6) === HEADER_MAGIC.substring(0, 6), `Invalid file header in partition ${this.name}.`);
120120

121121
this.header = headerMagic;
122-
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The partition ${this.name} was created with a different library version (${headerMagic.substr(6)}).`);
122+
assert(headerMagic === HEADER_MAGIC, `Invalid file version. The partition ${this.name} was created with a different library version (${headerMagic.substring(6)}).`);
123123

124124
const metadataSize = headerBuffer.readUInt32BE(8);
125125
assert(metadataSize > 2 && metadataSize <= 4096, 'Invalid metadata size.');
@@ -202,9 +202,7 @@ class ReadablePartition extends events.EventEmitter {
202202
const dataSize = buffer.readUInt32BE(offset + 0);
203203
assert(dataSize > 0 && dataSize <= 64 * 1024 * 1024, `Error reading document size from ${position}, got ${dataSize}.`);
204204

205-
if (size && dataSize !== size) {
206-
throw new InvalidDataSizeError(`Invalid document size ${dataSize} at position ${position}, expected ${size}.`);
207-
}
205+
assert(!size || dataSize === size, `Invalid document size ${dataSize} at position ${position}, expected ${size}.`, InvalidDataSizeError);
208206

209207
const sequenceNumber = buffer.readUInt32BE(offset + 4);
210208
const time64 = buffer.readDoubleBE(offset + 8);
@@ -268,9 +266,7 @@ class ReadablePartition extends events.EventEmitter {
268266
this.assignHeaderOutput(headerOut, header);
269267

270268
const writeSize = this.documentWriteSize(dataSize);
271-
if (position + writeSize > this.size) {
272-
throw new CorruptFileError(`Invalid document at position ${position}. This may be caused by an unfinished write.`);
273-
}
269+
assert(position + writeSize <= this.size, `Invalid document at position ${position}. This may be caused by an unfinished write.`, CorruptFileError);
274270

275271
if (dataSize + DOCUMENT_HEADER_SIZE > reader.buffer.byteLength) {
276272
const tempReadBuffer = Buffer.allocUnsafe(dataSize);

src/Partition/WritablePartition.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,8 @@ class WritablePartition extends ReadablePartition {
179179
writeDocumentHeader(buffer, offset, dataSize, sequenceNumber = null, time64 = null) {
180180
({ sequenceNumber, time64 } = this.normalizeWriteMetadata(sequenceNumber, time64));
181181
/* istanbul ignore if */
182-
if (time64 < 0) {
183-
throw new Error('Time may not be negative!');
184-
}
182+
assert(time64 >= 0, 'Time may not be negative!');
183+
185184
buffer.writeUInt32BE(dataSize, offset);
186185
buffer.writeUInt32BE(sequenceNumber, offset + 4);
187186
buffer.writeDoubleBE(time64, offset + 8);
@@ -223,7 +222,7 @@ class WritablePartition extends ReadablePartition {
223222
bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, DOCUMENT_HEADER_SIZE);
224223
bytesWritten += fs.writeSync(this.fd, data);
225224
const padSize = alignTo(dataSize + DOCUMENT_FOOTER_SIZE, DOCUMENT_ALIGNMENT);
226-
bytesWritten += fs.writeSync(this.fd, DOCUMENT_PAD.substr(0, padSize));
225+
bytesWritten += fs.writeSync(this.fd, DOCUMENT_PAD.substring(0, padSize));
227226
this.writeMetaBuffer.writeUInt32BE(dataSize, 0);
228227
bytesWritten += fs.writeSync(this.fd, this.writeMetaBuffer, 0, 4);
229228
bytesWritten += fs.writeSync(this.fd, DOCUMENT_SEPARATOR);
@@ -250,7 +249,7 @@ class WritablePartition extends ReadablePartition {
250249
bytesWritten += this.writeDocumentHeader(this.writeBuffer, this.writeBufferCursor, dataSize, sequenceNumber);
251250
bytesWritten += this.writeBuffer.write(data, this.writeBufferCursor + bytesWritten, 'utf8');
252251
const padSize = alignTo(dataSize + DOCUMENT_FOOTER_SIZE, DOCUMENT_ALIGNMENT);
253-
bytesWritten += this.writeBuffer.write(DOCUMENT_PAD.substr(0, padSize), this.writeBufferCursor + bytesWritten, 'utf8');
252+
bytesWritten += this.writeBuffer.write(DOCUMENT_PAD.substring(0, padSize), this.writeBufferCursor + bytesWritten, 'utf8');
254253
this.writeBuffer.writeUInt32BE(dataSize, this.writeBufferCursor + bytesWritten);
255254
bytesWritten += 4;
256255
bytesWritten += this.writeBuffer.write(DOCUMENT_SEPARATOR, this.writeBufferCursor + bytesWritten, 'utf8');
@@ -400,9 +399,7 @@ class WritablePartition extends ReadablePartition {
400399
try {
401400
this.readFrom(after);
402401
} catch (e) {
403-
if (!(e instanceof CorruptFileError)) {
404-
throw new Error('Can only truncate on valid document boundaries.');
405-
}
402+
assert(e instanceof CorruptFileError, 'Can only truncate on valid document boundaries.');
406403
}
407404

408405
fs.truncateSync(this.fileName, this.headerSize + after);

src/Storage/ReadOnlyStorage.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ class ReadOnlyStorage extends ReadableStorage {
2323
* @returns {boolean}
2424
*/
2525
storageFilesFilter(filename) {
26-
return filename.substr(-7) !== '.branch' && filename.substr(0, this.storageFile.length) === this.storageFile;
26+
return !filename.endsWith('.branch') && filename.substring(0, this.storageFile.length) === this.storageFile;
2727
}
2828

2929
/**
@@ -46,8 +46,8 @@ class ReadOnlyStorage extends ReadableStorage {
4646
* @param {string} filename
4747
*/
4848
onStorageFileChanged(filename) {
49-
if (filename.substr(-6) === '.index') {
50-
const indexName = filename.substr(this.storageFile.length + 1, filename.length - this.storageFile.length - 7);
49+
if (filename.endsWith('.index')) {
50+
const indexName = filename.substring(this.storageFile.length + 1, filename.length - 6);
5151
// New indexes are not automatically opened in the reader
5252
this.emit('index-created', indexName);
5353
return;

src/Storage/WritableStorage.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,8 @@ class WritableStorage extends ReadableStorage {
232232
this.locked = true;
233233
} catch (e) {
234234
/* istanbul ignore if */
235-
if (e.code !== 'EEXIST') {
236-
throw new Error(`Error creating lock for storage ${this.storageFile}: ` + e.message);
237-
}
235+
assert(e.code === 'EEXIST', `Error creating lock for storage ${this.storageFile}: ` + e.message)
236+
238237
throw new StorageLockedError(`Storage ${this.storageFile} is locked by another process`);
239238
}
240239
return true;

src/utils/metadataUtil.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import crypto from 'crypto';
2-
import { assertEqual } from './util.js';
2+
import { assert, assertEqual } from './util.js';
33
import { BYTE_OPEN_OBJECT, indexOfSameLevel } from './jsonUtil.js';
44

55
function isPlainObject(value) {
@@ -97,9 +97,8 @@ function buildMatcherFromMetadata(matcherMetadata, hmac) {
9797
if (typeof matcherMetadata.matcher === 'object') {
9898
matcher = matcherMetadata.matcher;
9999
} else {
100-
if (matcherMetadata.hmac !== hmac(matcherMetadata.matcher)) {
101-
throw new Error('Invalid HMAC for matcher.');
102-
}
100+
assert(matcherMetadata.hmac === hmac(matcherMetadata.matcher), 'Invalid HMAC for matcher.');
101+
103102
matcher = eval('(' + matcherMetadata.matcher + ')').bind({}); // jshint ignore:line
104103
}
105104
return matcher;
@@ -132,9 +131,7 @@ function buildTypeMatcherFn(payloadPath) {
132131
* @returns {function(Buffer): boolean}
133132
*/
134133
function buildRawBufferMatcher(matcher = {}) {
135-
if (!matcher || typeof matcher !== 'object' || Array.isArray(matcher)) {
136-
throw new TypeError('Matcher must be an object.');
137-
}
134+
assert(matcher && typeof matcher ==='object' && !Array.isArray(matcher), 'Matcher must be an object.', TypeError);
138135

139136
const root = buildMatcherTree(matcher);
140137
if (root.children.length === 0) {

0 commit comments

Comments
 (0)