Browse Source

Add Object.freeze on private enums

Improve code readability
master
Nicolas Dextraze 4 years ago
parent
commit
215708014c
  1. 44
      src/client.js
  2. 5
      src/clientOperations/appendToStreamOperation.js
  3. 1
      src/clientOperations/commitTransactionOperation.js
  4. 2
      src/clientOperations/connectToPersistentSubscriptionOperation.js
  5. 3
      src/clientOperations/createPersistentSubscriptionOperation.js
  6. 4
      src/clientOperations/deletePersistentSubscriptionOperation.js
  7. 1
      src/clientOperations/deleteStreamOperation.js
  8. 10
      src/clientOperations/operationBase.js
  9. 3
      src/clientOperations/readAllEventsBackwardOperation.js
  10. 3
      src/clientOperations/readAllEventsForwardOperation.js
  11. 3
      src/clientOperations/readEventOperation.js
  12. 3
      src/clientOperations/readStreamEventsBackwardOperation.js
  13. 3
      src/clientOperations/readStreamEventsForwardOperation.js
  14. 4
      src/clientOperations/startTransactionOperation.js
  15. 50
      src/clientOperations/subscriptionOperation.js
  16. 3
      src/clientOperations/transactionalWriteOperation.js
  17. 3
      src/clientOperations/updatePersistentSubscriptionOperation.js
  18. 3
      src/common/bufferSegment.js
  19. 2
      src/common/hash.js
  20. 6
      src/common/systemEventTypes.js
  21. 5
      src/common/systemMetadata.js
  22. 4
      src/common/systemStreams.js
  23. 29
      src/common/utils/ensure.js
  24. 27
      src/core/clusterDnsEndPointDiscoverer.js
  25. 56
      src/core/eventStoreConnectionLogicHandler.js
  26. 1
      src/core/messages.js
  27. 8
      src/core/operationsManager.js
  28. 9
      src/core/simpleQueuedHandler.js
  29. 2
      src/errors/projectionCommandFailedError.js
  30. 2
      src/eventData.js
  31. 10
      src/eventStoreAllCatchUpSubscription.js
  32. 39
      src/eventStoreCatchUpSubscription.js
  33. 6
      src/eventStoreConnection.js
  34. 13
      src/eventStoreNodeConnection.js
  35. 22
      src/eventStorePersistentSubscriptionBase.js
  36. 23
      src/eventStoreStreamCatchUpSubscription.js
  37. 2
      src/eventStoreSubscription.js
  38. 6
      src/gossipSeed.js
  39. 2
      src/persistentEventStoreSubscription.js
  40. 19
      src/persistentSubscriptionNakEventAction.js
  41. 6
      src/readDirection.js
  42. 56
      src/results.js
  43. 7
      src/sliceReadStatus.js
  44. 4
      src/subscriptionDropReason.js
  45. 7
      src/systemConsumerStrategies.js
  46. 4
      src/systemData/inspectionDecision.js
  47. 2
      src/systemData/inspectionResult.js
  48. 4
      src/systemData/statusCode.js
  49. 16
      src/systemData/tcpCommand.js
  50. 4
      src/systemData/tcpFlags.js
  51. 19
      src/systemData/tcpPackage.js
  52. 8
      src/transport/tcp/lengthPrefixMessageFramer.js
  53. 19
      src/transport/tcp/tcpConnection.js
  54. 16
      src/transport/tcp/tcpPackageConnection.js
  55. 2
      src/volatileEventStoreSubscription.js

44
src/client.js

@ -53,29 +53,29 @@ function createEventData(eventId, type, isJson, data, metadata) {
}
// Expose classes
module.exports.Position = results.Position;
module.exports.UserCredentials = require('./systemData/userCredentials');
module.exports.PersistentSubscriptionSettings = require('./persistentSubscriptionSettings');
module.exports.SystemConsumerStrategies = require('./systemConsumerStrategies');
module.exports.GossipSeed = require('./gossipSeed');
module.exports.EventStoreConnection = require('./eventStoreConnection');
module.exports.ProjectionsManager = require('./projections/projectionsManager');
exports.Position = results.Position;
exports.UserCredentials = require('./systemData/userCredentials');
exports.PersistentSubscriptionSettings = require('./persistentSubscriptionSettings');
exports.SystemConsumerStrategies = require('./systemConsumerStrategies');
exports.GossipSeed = require('./gossipSeed');
exports.EventStoreConnection = require('./eventStoreConnection');
exports.ProjectionsManager = require('./projections/projectionsManager');
// Expose errors
module.exports.WrongExpectedVersionError = require('./errors/wrongExpectedVersionError');
module.exports.StreamDeletedError = require('./errors/streamDeletedError');
module.exports.AccessDeniedError = require('./errors/accessDeniedError');
module.exports.ProjectionCommandFailedError = require('./errors/projectionCommandFailedError');
exports.WrongExpectedVersionError = require('./errors/wrongExpectedVersionError');
exports.StreamDeletedError = require('./errors/streamDeletedError');
exports.AccessDeniedError = require('./errors/accessDeniedError');
exports.ProjectionCommandFailedError = require('./errors/projectionCommandFailedError');
// Expose enums/constants
module.exports.expectedVersion = expectedVersion;
module.exports.positions = positions;
module.exports.streamPosition = streamPosition;
module.exports.systemMetadata = require('./common/systemMetadata');
module.exports.eventReadStatus = results.EventReadStatus;
module.exports.sliceReadStatus = require('./sliceReadStatus');
exports.expectedVersion = expectedVersion;
exports.positions = positions;
exports.streamPosition = streamPosition;
exports.systemMetadata = require('./common/systemMetadata');
exports.eventReadStatus = results.EventReadStatus;
exports.sliceReadStatus = require('./sliceReadStatus');
// Expose loggers
module.exports.NoopLogger = require('./common/log/noopLogger');
module.exports.FileLogger = require('./common/log/fileLogger');
exports.NoopLogger = require('./common/log/noopLogger');
exports.FileLogger = require('./common/log/fileLogger');
// Expose Helper functions
module.exports.createConnection = require('./eventStoreConnection').create;
module.exports.createJsonEventData = createJsonEventData;
module.exports.createEventData = createEventData;
exports.createConnection = require('./eventStoreConnection').create;
exports.createJsonEventData = createJsonEventData;
exports.createEventData = createEventData;

5
src/clientOperations/appendToStreamOperation.js

@ -44,8 +44,7 @@ AppendToStreamOperation.prototype._inspectResponse = function(response) {
switch (response.result)
{
case ClientMessage.OperationResult.Success:
if (this._wasCommitTimeout)
this.log.debug("IDEMPOTENT WRITE SUCCEEDED FOR %s.", this);
if (this._wasCommitTimeout) this.log.debug("IDEMPOTENT WRITE SUCCEEDED FOR %s.", this);
this._succeed();
return new InspectionResult(InspectionDecision.EndOperation, "Success");
case ClientMessage.OperationResult.PrepareTimeout:
@ -80,4 +79,4 @@ AppendToStreamOperation.prototype.toString = function() {
return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
};
module.exports = AppendToStreamOperation;
module.exports = AppendToStreamOperation;

1
src/clientOperations/commitTransactionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var InspectionDecision = require('../systemData/inspectionDecision');

2
src/clientOperations/connectToPersistentSubscriptionOperation.js

@ -124,4 +124,4 @@ ConnectToPersistentSubscriptionOperation.prototype.notifyEventsFailed = function
this._enqueueSend(pkg);
};
module.exports = ConnectToPersistentSubscriptionOperation;
module.exports = ConnectToPersistentSubscriptionOperation;

3
src/clientOperations/createPersistentSubscriptionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var ensure = require('../common/utils/ensure');
var OperationBase = require('../clientOperations/operationBase');
@ -84,4 +83,4 @@ CreatePersistentSubscriptionOperation.prototype.toString = function() {
return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
};
module.exports = CreatePersistentSubscriptionOperation;
module.exports = CreatePersistentSubscriptionOperation;

4
src/clientOperations/deletePersistentSubscriptionOperation.js

@ -1,7 +1,5 @@
var util = require('util');
var uuid = require('uuid');
var ensure = require('../common/utils/ensure');
var OperationBase = require('../clientOperations/operationBase');
var TcpCommand = require('../systemData/tcpCommand');
var ClientMessage = require('../messages/clientMessage');
@ -55,4 +53,4 @@ DeletePersistentSubscriptionOperation.prototype.toString = function() {
return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
};
module.exports = DeletePersistentSubscriptionOperation;
module.exports = DeletePersistentSubscriptionOperation;

1
src/clientOperations/deleteStreamOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var InspectionDecision = require('../systemData/inspectionDecision');

10
src/clientOperations/operationBase.js

@ -42,10 +42,11 @@ OperationBase.prototype._succeed = function() {
if (!this._completed) {
this._completed = true;
if (this._response)
if (this._response) {
this._cb(null, this._transformResponse(this._response));
else
} else {
this._cb(new Error("No result."))
}
}
};
@ -130,8 +131,7 @@ OperationBase.prototype._inspectNotHandled = function(pkg)
OperationBase.prototype._inspectUnexpectedCommand = function(pkg, expectedCommand)
{
if (pkg.command === expectedCommand)
throw new Error("Command shouldn't be " + TcpCommand.getName(pkg.command));
if (pkg.command === expectedCommand) throw new Error("Command shouldn't be " + TcpCommand.getName(pkg.command));
this.log.error("Unexpected TcpCommand received.\n"
+ "Expected: %s, Actual: %s, Flags: %s, CorrelationId: %s\n"
@ -145,4 +145,4 @@ OperationBase.prototype._inspectUnexpectedCommand = function(pkg, expectedComman
};
module.exports = OperationBase;
module.exports = OperationBase;

3
src/clientOperations/readAllEventsBackwardOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var ClientMessage = require('../messages/clientMessage');
@ -65,4 +64,4 @@ ReadAllEventsBackwardOperation.prototype.toString = function() {
this._position, this._maxCount, this._resolveLinkTos, this._requireMaster);
};
module.exports = ReadAllEventsBackwardOperation;
module.exports = ReadAllEventsBackwardOperation;

3
src/clientOperations/readAllEventsForwardOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var ClientMessage = require('../messages/clientMessage');
@ -65,4 +64,4 @@ ReadAllEventsForwardOperation.prototype.toString = function() {
this._position, this._maxCount, this._resolveLinkTos, this._requireMaster);
};
module.exports = ReadAllEventsForwardOperation;
module.exports = ReadAllEventsForwardOperation;

3
src/clientOperations/readEventOperation.js

@ -59,7 +59,6 @@ ReadEventOperation.prototype._transformResponse = function(response) {
return new results.EventReadResult(convert(response.result), this._stream, this._eventNumber, response.event);
};
function convert(result)
{
switch (result)
@ -82,4 +81,4 @@ ReadEventOperation.prototype.toString = function() {
this._stream, this._eventNumber, this._resolveLinkTos, this._requireMaster);
};
module.exports = ReadEventOperation;
module.exports = ReadEventOperation;

3
src/clientOperations/readStreamEventsBackwardOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var ClientMessage = require('../messages/clientMessage');
@ -77,4 +76,4 @@ ReadStreamEventsBackwardOperation.prototype.toString = function() {
this._stream, this._fromEventNumber, this._maxCount, this._resolveLinkTos, this._requireMaster);
};
module.exports = ReadStreamEventsBackwardOperation;
module.exports = ReadStreamEventsBackwardOperation;

3
src/clientOperations/readStreamEventsForwardOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var ClientMessage = require('../messages/clientMessage');
@ -77,4 +76,4 @@ ReadStreamEventsForwardOperation.prototype.toString = function() {
this._stream, this._fromEventNumber, this._maxCount, this._resolveLinkTos, this._requireMaster);
};
module.exports = ReadStreamEventsForwardOperation;
module.exports = ReadStreamEventsForwardOperation;

4
src/clientOperations/startTransactionOperation.js

@ -1,12 +1,10 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var InspectionDecision = require('../systemData/inspectionDecision');
var InspectionResult = require('./../systemData/inspectionResult');
var ClientMessage = require('../messages/clientMessage');
var EventStoreTransaction = require('../eventStoreTransaction');
var results = require('../results');
var AccessDeniedError = require('../errors/accessDeniedError');
var WrongExpectedVersionError = require('../errors/wrongExpectedVersionError');
var StreamDeletedError = require('../errors/streamDeletedError');
@ -68,4 +66,4 @@ StartTransactionOperation.prototype.toString = function() {
return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
};
module.exports = StartTransactionOperation;
module.exports = StartTransactionOperation;

50
src/clientOperations/subscriptionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var TcpCommand = require('../systemData/tcpCommand');
var TcpFlags = require('../systemData/tcpFlags');
@ -46,8 +45,7 @@ SubscriptionOperation.prototype._enqueueSend = function(pkg) {
SubscriptionOperation.prototype.subscribe = function(correlationId, connection) {
if (connection === null) throw new TypeError("connection is null.");
if (this._subscription !== null || this._unsubscribed)
return false;
if (this._subscription !== null || this._unsubscribed) return false;
this._correlationId = correlationId;
connection.enqueueSend(this._createSubscriptionPackage());
@ -76,9 +74,7 @@ SubscriptionOperation.prototype.inspectPackage = function(pkg) {
try
{
var result = this._inspectPackage(pkg);
if (result !== null) {
return result;
}
if (result !== null) return result;
switch (pkg.command)
{
@ -128,8 +124,9 @@ SubscriptionOperation.prototype.inspectPackage = function(pkg) {
case TcpCommand.NotHandled:
{
if (this._subscription !== null)
if (this._subscription !== null) {
throw new Error("NotHandled command appeared while we already subscribed.");
}
var message = ClientMessage.NotHandled.decode(pkg.data.toBuffer());
switch (message.reason)
@ -172,8 +169,7 @@ SubscriptionOperation.prototype.connectionClosed = function() {
};
SubscriptionOperation.prototype.timeOutSubscription = function() {
if (this._subscription !== null)
return false;
if (this._subscription !== null) return false;
this.dropSubscription(SubscriptionDropReason.SubscribingError, null);
return true;
};
@ -182,9 +178,10 @@ SubscriptionOperation.prototype.dropSubscription = function(reason, err, connect
if (!this._unsubscribed)
{
this._unsubscribed = true;
if (this._verboseLogging)
if (this._verboseLogging) {
this._log.debug("Subscription %s to %s: closing subscription, reason: %s, exception: %s...",
this._correlationId, this._streamId || "<all>", reason, err);
this._correlationId, this._streamId || "<all>", reason, err);
}
if (reason !== SubscriptionDropReason.UserInitiated && this._subscription === null)
{
@ -193,24 +190,31 @@ SubscriptionOperation.prototype.dropSubscription = function(reason, err, connect
return;
}
if (reason === SubscriptionDropReason.UserInitiated && this._subscription !== null && connection !== null)
if (reason === SubscriptionDropReason.UserInitiated && this._subscription !== null && connection !== null) {
connection.enqueueSend(this._createUnsubscriptionPackage());
}
var self = this;
if (this._subscription !== null)
this._executeAction(function() { self._subscriptionDropped(self._subscription, reason, err); });
if (this._subscription !== null) {
this._executeAction(function () {
self._subscriptionDropped(self._subscription, reason, err);
});
}
}
};
SubscriptionOperation.prototype._confirmSubscription = function(lastCommitPosition, lastEventNumber) {
if (lastCommitPosition < -1)
if (lastCommitPosition < -1) {
throw new Error(util.format("Invalid lastCommitPosition %s on subscription confirmation.", lastCommitPosition));
if (this._subscription !== null)
}
if (this._subscription !== null) {
throw new Error("Double confirmation of subscription.");
}
if (this._verboseLogging)
if (this._verboseLogging) {
this._log.debug("Subscription %s to %s: subscribed at CommitPosition: %d, EventNumber: %d.",
this._correlationId, this._streamId || "<all>", lastCommitPosition, lastEventNumber);
this._correlationId, this._streamId || "<all>", lastCommitPosition, lastEventNumber);
}
this._subscription = this._createSubscriptionObject(lastCommitPosition, lastEventNumber);
this._cb(null, this._subscription);
@ -221,15 +225,15 @@ SubscriptionOperation.prototype._createSubscriptionObject = function(lastCommitP
};
SubscriptionOperation.prototype._onEventAppeared = function(e) {
if (this._unsubscribed)
return;
if (this._unsubscribed) return;
if (this._subscription === null) throw new Error("Subscription not confirmed, but event appeared!");
if (this._verboseLogging)
if (this._verboseLogging) {
this._log.debug("Subscription %s to %s: event appeared (%s, %d, %s @ %s).",
this._correlationId, this._streamId || "<all>",
e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
this._correlationId, this._streamId || "<all>",
e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
}
var self = this;
this._executeAction(function() { return self._eventAppeared(self._subscription, e); });

3
src/clientOperations/transactionalWriteOperation.js

@ -64,5 +64,4 @@ TransactionalWriteOperation.prototype.toString = function() {
return util.format("TransactionId: %s", this._transactionId);
};
module.exports = TransactionalWriteOperation;
module.exports = TransactionalWriteOperation;

3
src/clientOperations/updatePersistentSubscriptionOperation.js

@ -1,5 +1,4 @@
var util = require('util');
var uuid = require('uuid');
var ensure = require('../common/utils/ensure');
var OperationBase = require('../clientOperations/operationBase');
@ -84,4 +83,4 @@ UpdatePersistentSubscriptionOperation.prototype.toString = function() {
return util.format("Stream: %s, Group Name: %s", this._stream, this._groupName);
};
module.exports = UpdatePersistentSubscriptionOperation;
module.exports = UpdatePersistentSubscriptionOperation;

3
src/common/bufferSegment.js

@ -19,8 +19,7 @@ BufferSegment.prototype.toString = function() {
};
BufferSegment.prototype.toBuffer = function() {
if (this.offset === 0 && this.count === this.buffer.length)
return this.buffer;
if (this.offset === 0 && this.count === this.buffer.length) return this.buffer;
return this.buffer.slice(this.offset, this.offset + this.count);
};

2
src/common/hash.js

@ -39,4 +39,4 @@ Hash.prototype.remove = function(key) {
};
module.exports = Hash;
module.exports = Hash;

6
src/common/systemEventTypes.js

@ -1,5 +1,5 @@
const SystemEventTypes = {
const SystemEventTypes = Object.freeze({
StreamMetadata: '$metadata'
};
});
module.exports = SystemEventTypes;
module.exports = SystemEventTypes;

5
src/common/systemMetadata.js

@ -1,4 +1,4 @@
const SystemMetadata = {
const SystemMetadata = Object.freeze({
maxAge: '$maxAge',
maxCount: '$maxCount',
truncateBefore: '$tb',
@ -11,7 +11,6 @@ const SystemMetadata = {
aclMetaWrite: '$mw',
userStreamAcl: '$userStreamAcl',
systemStreamAcl: '$systemStreamAcl'
};
Object.freeze(SystemMetadata);
});
module.exports = SystemMetadata;

4
src/common/systemStreams.js

@ -1,6 +1,6 @@
module.exports.metastreamOf = function(stream) {
exports.metastreamOf = function(stream) {
return '$$' + stream;
};
module.exports.isMetastream = function(stream) {
exports.isMetastream = function(stream) {
return stream.indexOf('$$') === 0;
};

29
src/common/utils/ensure.js

@ -1,20 +1,16 @@
var Long = require('long');
module.exports.notNullOrEmpty = function(value, name) {
if (value === null)
throw new TypeError(name + " should not be null.");
if (value === '')
throw new Error(name + " should not be empty.");
if (value === null) throw new TypeError(name + " should not be null.");
if (value === '') throw new Error(name + " should not be empty.");
};
module.exports.notNull = function(value, name) {
if (value === null)
throw new TypeError(name + " should not be null.");
if (value === null) throw new TypeError(name + " should not be null.");
};
function isInteger(value, name) {
if (typeof value !== 'number' || value % 1 !== 0)
throw new TypeError(name + " should be an integer.");
if (typeof value !== 'number' || value % 1 !== 0) throw new TypeError(name + " should be an integer.");
}
module.exports.isInteger = isInteger;
@ -27,24 +23,23 @@ module.exports.isLongOrInteger = function(value, name) {
};
module.exports.isArrayOf = function(expectedType, value, name) {
if (!Array.isArray(value))
throw new TypeError(name + " should be an array.");
if (!value.every(function(x) { return x instanceof expectedType; }))
if (!Array.isArray(value)) throw new TypeError(name + " should be an array.");
if (!value.every(function(x) { return x instanceof expectedType; })) {
throw new TypeError([name, " should be an array of ", expectedType.name, "."].join(""));
}
};
module.exports.isTypeOf = function(expectedType, value, name, nullAllowed) {
if (nullAllowed && value === null) return;
if (!(value instanceof expectedType))
throw new TypeError([name, " should be of type '", expectedType.name, "'", nullAllowed ? " or null": "", "."].join(""));
if (!(value instanceof expectedType)) {
throw new TypeError([name, " should be of type '", expectedType.name, "'", nullAllowed ? " or null" : "", "."].join(""));
}
};
module.exports.positive = function(value, name) {
if (value <= 0)
throw new Error(name + " should be positive.");
if (value <= 0) throw new Error(name + " should be positive.");
};
module.exports.nonNegative = function(value, name) {
if (value < 0)
throw new Error(name + " should be non-negative.");
if (value < 0) throw new Error(name + " should be non-negative.");
};

27
src/core/clusterDnsEndPointDiscoverer.js

@ -34,18 +34,19 @@ ClusterDnsEndPointDiscoverer.prototype.discover = function(failedTcpEndPoint) {
function discover(resolve, reject) {
self._discoverEndPoint(failedTcpEndPoint)
.then(function (endPoints) {
if (!endPoints)
if (!endPoints) {
self._log.info(util.format("Discovering attempt %d/%d failed: no candidate found.", attempt, self._maxDiscoverAttempts));
}
return endPoints;
})
.catch(function (exc) {
self._log.info(util.format("Discovering attempt %d/%d failed with error: %s.\n%s", attempt, self._maxDiscoverAttempts, exc, exc.stack));
})
.then(function (endPoints) {
if (endPoints)
return resolve(endPoints);
if (attempt++ === self._maxDiscoverAttempts)
if (endPoints) return resolve(endPoints);
if (attempt++ === self._maxDiscoverAttempts) {
return reject(new Error('Failed to discover candidate in ' + self._maxDiscoverAttempts + ' attempts.'));
}
setTimeout(discover, 500, resolve, reject);
});
}
@ -74,8 +75,7 @@ ClusterDnsEndPointDiscoverer.prototype._discoverEndPoint = function (failedTcpEn
if (endPoints) return endPoints;
return self._tryGetGossipFrom(gossipCandidates[j++])
.then(function (gossip) {
if (!gossip || !gossip.members || gossip.members.length === 0)
return;
if (!gossip || !gossip.members || gossip.members.length === 0) return;
var bestNode = self._tryDetermineBestNode(gossip.members);
if (bestNode) {
self._oldGossip = gossip.members;
@ -105,10 +105,11 @@ ClusterDnsEndPointDiscoverer.prototype._arrangeGossipCandidates = function (memb
var j = members.length;
for (var k = 0; k < members.length; ++k)
{
if (members[k].state === 'Manager')
if (members[k].state === 'Manager') {
result[--j] = new GossipSeed({host: members[k].externalHttpIp, port: members[k].externalHttpPort});
else
} else {
result[++i] = new GossipSeed({host: members[k].externalHttpIp, port: members[k].externalHttpPort});
}
}
this._randomShuffle(result, 0, i); // shuffle nodes
this._randomShuffle(result, j, members.length - 1); // shuffle managers
@ -122,8 +123,7 @@ ClusterDnsEndPointDiscoverer.prototype._getGossipCandidatesFromDns = function ()
var endpoints = self._gossipSeeds;
self._randomShuffle(endpoints, 0, endpoints.length - 1);
resolve(endpoints);
}
else {
} else {
const dnsOptions = {
family: 4,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
@ -192,7 +192,7 @@ ClusterDnsEndPointDiscoverer.prototype._tryGetGossipFrom = function (endPoint) {
});
};
const VNodeStates = {
const VNodeStates = Object.freeze({
'Initializing': 0,
'Unknown': 1,
'PreReplica': 2,
@ -204,7 +204,7 @@ const VNodeStates = {
'Manager': 8,
'ShuttingDown': 9,
'Shutdown': 10
};
});
ClusterDnsEndPointDiscoverer.prototype._tryDetermineBestNode = function (members) {
var notAllowedStates = [
@ -240,8 +240,7 @@ function rndNext(min, max) {
}
ClusterDnsEndPointDiscoverer.prototype._randomShuffle = function (arr, i, j) {
if (i >= j)
return;
if (i >= j) return;
for (var k = i; k <= j; ++k)
{
var index = rndNext(k, j + 1);

56
src/core/eventStoreConnectionLogicHandler.js

@ -17,14 +17,14 @@ var TcpCommand = require('../systemData/tcpCommand');
var TcpFlags = require('../systemData/tcpFlags');
var InspectionDecision = require('../systemData/inspectionDecision');
const ConnectionState = {
const ConnectionState = Object.freeze({
Init: 'init',
Connecting: 'connecting',
Connected: 'connected',
Closed: 'closed'
};
});
const ConnectingPhase = {
const ConnectingPhase = Object.freeze({
Invalid: 'invalid',
Reconnecting: 'reconnecting',
EndPointDiscovery: 'endpointDiscovery',
@ -32,7 +32,7 @@ const ConnectingPhase = {
Authentication: 'authentication',
Identification: 'identification',
Connected: 'connected'
};
});
const TimerPeriod = 200;
const TimerTickMessage = new messages.TimerTickMessage();
@ -187,8 +187,7 @@ EventStoreConnectionLogicHandler.prototype._closeConnection = function(reason, e
this._logInfo("Closed. Reason: %s", reason);
if (error)
this.emit('error', error);
if (error) this.emit('error', error);
this.emit('closed', reason);
};
@ -205,7 +204,7 @@ EventStoreConnectionLogicHandler.prototype._closeTcpConnection = function(reason
this._connection = null;
};
var _nextSeqNo = -1;
var _nextSeqNo = 0;
function createOperationItem(operation, maxRetries, timeout) {
var operationItem = {
seqNo: _nextSeqNo++,
@ -283,10 +282,11 @@ EventStoreConnectionLogicHandler.prototype._startSubscription = function(msg) {
this._state === ConnectionState.Connected ? "fire" : "enqueue",
operation.constructor.name, operation, msg.maxRetries, msg.timeout);
var subscription = createSubscriptionItem(operation, msg.maxRetries, msg.timeout);
if (this._state === ConnectionState.Connecting)
if (this._state === ConnectionState.Connecting) {
this._subscriptions.enqueueSubscription(subscription);
else
} else {
this._subscriptions.startSubscription(subscription, this._connection);
}
break;
case ConnectionState.Closed:
msg.cb(new Error("Connection closed. Connection: " + this._esConnection.connectionName));
@ -312,10 +312,11 @@ EventStoreConnectionLogicHandler.prototype._startPersistentSubscription = functi
this._state === ConnectionState.Connected ? "fire" : "enqueue",
operation.constructor.name, operation, msg.maxRetries, msg.timeout);
var subscription = createSubscriptionItem(operation, msg.maxRetries, msg.timeout);
if (this._state === ConnectionState.Connecting)
if (this._state === ConnectionState.Connecting) {
this._subscriptions.enqueueSubscription(subscription);
else
} else {
this._subscriptions.startSubscription(subscription, this._connection);
}
break;
case ConnectionState.Closed:
msg.cb(new Error("Connection closed. " + this._esConnection.connectionName));
@ -561,8 +562,9 @@ EventStoreConnectionLogicHandler.prototype._handleTcpPackage = function(connecti
default:
throw new Error("Unknown InspectionDecision: " + result.decision);
}
if (this._state === ConnectionState.Connected)
if (this._state === ConnectionState.Connected) {
this._operations.scheduleWaitingOperations(connection);
}
return;
}
@ -609,8 +611,7 @@ EventStoreConnectionLogicHandler.prototype._reconnectTo = function(endPoints) {
return;
}
if (this._state !== ConnectionState.Connected || this._connection.remoteEndPoint === endPoint)
return;
if (this._state !== ConnectionState.Connected || this._connection.remoteEndPoint === endPoint) return;
var msg = util.format("EventStoreConnection '%s': going to reconnect to [%j]. Current endpoint: [%j, L%j].",
this._esConnection.connectionName, endPoint, this._connection.remoteEndPoint, this._connection.localEndPoint);
@ -627,30 +628,26 @@ EventStoreConnectionLogicHandler.prototype._timerTick = function() {
{
case ConnectionState.Init: break;
case ConnectionState.Connecting:
if (this._connectingPhase === ConnectingPhase.Reconnecting && (Date.now() - this._reconnInfo.timeStamp) >= this._settings.reconnectionDelay)
{
if (this._connectingPhase === ConnectingPhase.Reconnecting && (Date.now() - this._reconnInfo.timeStamp) >= this._settings.reconnectionDelay) {
this._logDebug("TimerTick checking reconnection...");
this._reconnInfo = {reconnectionAttempt: this._reconnInfo.reconnectionAttempt + 1, timeStamp: Date.now()};
if (this._settings.maxReconnections >= 0 && this._reconnInfo.reconnectionAttempt > this._settings.maxReconnections)
if (this._settings.maxReconnections >= 0 && this._reconnInfo.reconnectionAttempt > this._settings.maxReconnections) {
this._closeConnection("Reconnection limit reached.");
else
{
} else {
this.emit('reconnecting', {});
this._discoverEndpoint(null);
}
}
else if (this._connectingPhase === ConnectingPhase.Authentication && (Date.now() - this._authInfo.timeStamp) >= this._settings.operationTimeout)
{
} else if (this._connectingPhase === ConnectingPhase.Authentication && (Date.now() - this._authInfo.timeStamp) >= this._settings.operationTimeout) {
this.emit('authenticationFailed', "Authentication timed out.");
if (this._clientVersion === 1) {
this._goToIdentifiedState();
} else {
this._goToConnectedState();
}
}
else if (this._connectingPhase === ConnectingPhase.Authentication || this._connectingPhase === ConnectingPhase.Connected)
} else if (this._connectingPhase === ConnectingPhase.Authentication || this._connectingPhase === ConnectingPhase.Connected) {
this._manageHeartbeats();
}
break;
case ConnectionState.Connected:
// operations timeouts are checked only if connection is established and check period time passed
@ -677,8 +674,7 @@ EventStoreConnectionLogicHandler.prototype._manageHeartbeats = function() {
if (this._connection === null) return;
var timeout = this._heartbeatInfo.isIntervalStage ? this._settings.heartbeatInterval : this._settings.heartbeatTimeout;
if ((Date.now() - this._heartbeatInfo.timeStamp) < timeout)
return;
if ((Date.now() - this._heartbeatInfo.timeStamp) < timeout) return;
var packageNumber = this._packageNumber;
if (this._heartbeatInfo.lastPackageNumber !== packageNumber)
@ -711,15 +707,17 @@ EventStoreConnectionLogicHandler.prototype._manageHeartbeats = function() {
EventStoreConnectionLogicHandler.prototype._logDebug = function(message) {
if (!this._settings.verboseLogging) return;
if (arguments.length > 1)
message = util.format.apply(util, Array.prototype.slice.call(arguments));
if (arguments.length > 1) {
message = util.format.apply(util, Array.prototype.slice.call(arguments));
}
this._settings.log.debug("EventStoreConnection '%s': %s", this._esConnection.connectionName, message);
};
EventStoreConnectionLogicHandler.prototype._logInfo = function(message){
if (arguments.length > 1)
if (arguments.length > 1) {
message = util.format.apply(util, Array.prototype.slice.call(arguments));
}
this._settings.log.info("EventStoreConnection '%s': %s", this._esConnection.connectionName, message);
};

1
src/core/messages.js

@ -1,5 +1,4 @@
var util = require('util');
var ensure = require('../common/utils/ensure');
function Message() {
}

8
src/core/operationsManager.js

@ -110,8 +110,7 @@ OperationsManager.prototype.checkTimeoutsAndRetry = function(connection) {
};
OperationsManager.prototype.scheduleOperationRetry = function(operation) {
if (!this.removeOperation(operation))
return;
if (!this.removeOperation(operation)) return;
this._logDebug("ScheduleOperationRetry for %s.", operation);
if (operation.maxRetries >= 0 && operation.retryCount >= operation.maxRetries)
@ -166,10 +165,11 @@ OperationsManager.prototype.scheduleOperation = function(operation, connection)
OperationsManager.prototype._logDebug = function(message) {
if (!this._settings.verboseLogging) return;
if (arguments.length > 1)
if (arguments.length > 1) {
message = util.format.apply(util, Array.prototype.slice.call(arguments));
}
this._settings.log.debug("EventStoreConnection '%s': %s.", this._connectionName, message);
};
module.exports = OperationsManager;
module.exports = OperationsManager;

9
src/core/simpleQueuedHandler.js

@ -1,8 +1,6 @@
function typeName(t) {
if (typeof t === 'function')
return t.name;
if (typeof t === 'object')
return t.constructor.name;
if (typeof t === 'function') return t.name;
if (typeof t === 'object') return t.constructor.name;
throw new TypeError('type must be a function or object, not ' + typeof t);
}
@ -36,8 +34,7 @@ SimpleQueuedHandler.prototype._processQueue = function() {
while(message) {
var typeId = typeName(message);
var handler = this._handlers[typeId];
if (!handler)
throw new Error("No handler registered for message " + typeId);
if (!handler) throw new Error("No handler registered for message " + typeId);
setImmediate(handler, message);
message = this._messages.shift();
}

2
src/errors/projectionCommandFailedError.js

@ -7,4 +7,4 @@ function ProjectionCommandFailedError(httpStatusCode, message) {
}
util.inherits(ProjectionCommandFailedError, Error);
module.exports = ProjectionCommandFailedError;
module.exports = ProjectionCommandFailedError;

2
src/eventData.js

@ -1,5 +1,3 @@
var uuid = require('uuid');
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isValidId(id) {
if (typeof id !== 'string') return false;

10
src/eventStoreAllCatchUpSubscription.js

@ -45,8 +45,7 @@ EventStoreAllCatchUpSubscription.prototype._readEventsTill = function(
});
})
.then(function(done) {
if (done || self._shouldStop)
return;
if (done || self._shouldStop) return;
return readNext();
});
}
@ -69,10 +68,11 @@ EventStoreAllCatchUpSubscription.prototype._tryProcess = function(e) {
this._lastProcessedPosition = e.originalPosition;
processed = true;
}
if (this._verbose)
if (this._verbose) {
this._log.debug("Catch-up Subscription to %s: %s event (%s, %d, %s @ %s).",
this.streamId || '<all>', processed ? "processed" : "skipping",
e.originalEvent.eventStreamId, e.originalEvent.eventNumber, e.originalEvent.eventType, e.originalPosition);
this.streamId || '<all>', processed ? "processed" : "skipping",
e.originalEvent.eventStreamId, e.originalEvent.eventNumber, e.originalEvent.eventType, e.originalPosition);
}
return (promise && promise.then) ? promise : Promise.resolve();
};

39
src/eventStoreCatchUpSubscription.js

@ -1,7 +1,6 @@
var util = require('util');
var SubscriptionDropReason = require('./subscriptionDropReason');
var results = require('./results');
const DefaultReadBatchSize = 500;
const DefaultMaxPushQueueSize = 10000;
@ -68,9 +67,9 @@ function EventStoreCatchUpSubscription(
var self = this;
this._onReconnect = function() {
if (self._verbose) self._log.debug("Catch-up Subscription to %s: recovering after reconnection.", self._streamId || '<all>');
if (self._verbose) self._log.debug("Catch-up Subscription to %s: unhooking from connection.Connected.", self._streamId || '<all>');
self._connection.removeListener('connected', self._onReconnect);
if (self._verbose) self._log.debug("Catch-up Subscription to %s: recovering after reconnection.", self._streamId || '<all>');
self._runSubscription();
}
}
@ -133,10 +132,11 @@ EventStoreCatchUpSubscription.prototype._runSubscription = function() {
.then(function() {
if (self._shouldStop) return;
if (self._verbose) self._log.debug("Catch-up Subscription to %s: subscribing...", logStreamName);
if (self._streamId === '')
if (self._streamId === '') {
return self._connection.subscribeToAll(self._resolveLinkTos, self._enqueuePushedEvent.bind(self), self._serverSubscriptionDropped.bind(self), self._userCredentials);
else
} else {
return self._connection.subscribeToStream(self._streamId, self._resolveLinkTos, self._enqueuePushedEvent.bind(self), self._serverSubscriptionDropped.bind(self), self._userCredentials);
}
})
.then(function(subscription) {
if (subscription === undefined) return;
@ -155,12 +155,13 @@ EventStoreCatchUpSubscription.prototype._runSubscription = function() {
return;
}
if (self._verbose) self._log.debug("Catch-up Subscription to %s: processing live events...", logStreamName);
if (self._liveProcessingStarted)
if (self._liveProcessingStarted) {
try {
self._liveProcessingStarted(self);
} catch(e) {
} catch (e) {
self._log.error(e, "Catch-up Subscription to %s: liveProcessingStarted callback failed.", logStreamName);
}
}
if (self._verbose) self._log.debug("Catch-up Subscription to %s: hooking to connection.Connected", logStreamName);
self._connection.on('connected', self._onReconnect);
self._allowProcessing = true;
@ -169,10 +170,11 @@ EventStoreCatchUpSubscription.prototype._runSubscription = function() {
};
EventStoreCatchUpSubscription.prototype._enqueuePushedEvent = function(subscription, e) {
if (this._verbose)
if (this._verbose) {
this._log.debug("Catch-up Subscription to %s: event appeared (%s, %d, %s @ %s).",
this._streamId || '<all>',
e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
this._streamId || '<all>',
e.originalStreamId, e.originalEventNumber, e.originalEvent.eventType, e.originalPosition);
}
if (this._liveQueue.length >= this.maxPushQueueSize)
{
@ -183,8 +185,7 @@ EventStoreCatchUpSubscription.prototype._enqueuePushedEvent = function(subscript
this._liveQueue.push(e);
if (this._allowProcessing)
this._ensureProcessingPushQueue();
if (this._allowProcessing) this._ensureProcessingPushQueue();
};
EventStoreCatchUpSubscription.prototype._serverSubscriptionDropped = function(subscription, reason, err) {
@ -196,8 +197,7 @@ EventStoreCatchUpSubscription.prototype._enqueueSubscriptionDropNotification = f
if (this._dropData) return;
this._dropData = {reason: reason, error: error};
this._liveQueue.push(new DropSubscriptionEvent());
if (this._allowProcessing)
this._ensureProcessingPushQueue();
if (this._allowProcessing) this._ensureProcessingPushQueue();
};
EventStoreCatchUpSubscription.prototype._ensureProcessingPushQueue = function() {
@ -244,18 +244,19 @@ EventStoreCatchUpSubscription.prototype._dropSubscription = function(reason, err
if (this._isDropped) return;
this._isDropped = true;
if (this._verbose)
if (this._verbose) {
this._log.debug("Catch-up Subscription to %s: dropping subscription, reason: %s %s.",
this._streamId || '<all>', reason, error);
this._streamId || '<all>', reason, error);
}
if (this._subscription)
this._subscription.unsubscribe();
if (this._subscriptionDropped)
if (this._subscription) this._subscription.unsubscribe();
if (this._subscriptionDropped) {
try {
this._subscriptionDropped(this, reason, error);
} catch(e) {
} catch (e) {
this._log.error(e, "Catch-up Subscription to %s: subscriptionDropped callback failed.", this._streamId || '<all>');
}
}
this._stopped = true;
};

6
src/eventStoreConnection.js

@ -4,7 +4,7 @@ var ClusterDnsEndPointDiscoverer = require('./core/clusterDnsEndPointDiscoverer'
var NoopLogger = require('./common/log/noopLogger');
var ensure = require('./common/utils/ensure');
var defaultConnectionSettings = {
var defaultConnectionSettings = Object.freeze({
log: new NoopLogger(),
verboseLogging: false,
@ -34,7 +34,7 @@ var defaultConnectionSettings = {
maxDiscoverAttempts: 10,
externalGossipPort: 0,
gossipTimeout: 1000
};
});
function merge(a,b) {
@ -151,4 +151,4 @@ module.exports.create = function(settings, endPointOrGossipSeeds, connectionName
if (typeof endPointOrGossipSeeds === 'object') return createFromTcpEndpoint(settings, endPointOrGossipSeeds, connectionName);
if (typeof endPointOrGossipSeeds === 'string') return createFromStringEndpoint(settings, endPointOrGossipSeeds, connectionName);
throw new TypeError('endPointOrGossipSeeds must be an object, a string or an array.');
};
};

13
src/eventStoreNodeConnection.js

@ -140,8 +140,7 @@ EventStoreNodeConnection.prototype.appendToStream = function(stream, expectedVer
ensure.notNullOrEmpty(stream, "stream");
ensure.isLongOrInteger(expectedVersion, "expectedVersion");
expectedVersion = Long.fromValue(expectedVersion);
if (!Array.isArray(events))
events = [events];
if (!Array.isArray(events)) events = [events];
ensure.isArrayOf(EventData, events, "events");
userCredentials = userCredentials || null;
@ -413,8 +412,7 @@ EventStoreNodeConnection.prototype.subscribeToStream = function(
) {
ensure.notNullOrEmpty(stream, "stream");
ensure.isTypeOf(Function, eventAppeared, "eventAppeared");
if (subscriptionDropped)
ensure.isTypeOf(Function, subscriptionDropped, "subscriptionDropped");
if (subscriptionDropped) ensure.isTypeOf(Function, subscriptionDropped, "subscriptionDropped");
var self = this;
return new Promise(function(resolve,reject) {
@ -641,8 +639,9 @@ EventStoreNodeConnection.prototype.setStreamMetadataRaw = function(
stream, expectedMetastreamVersion, metadata, userCredentials
) {
ensure.notNullOrEmpty(stream, "stream");
if (systemStreams.isMetastream(stream))
if (systemStreams.isMetastream(stream)) {
throw new Error(util.format("Setting metadata for metastream '%s' is not supported.", stream));
}
ensure.isLongOrInteger(expectedMetastreamVersion, "expectedMetastreamVersion");
expectedMetastreamVersion = Long.fromValue(expectedMetastreamVersion);
var self = this;
@ -713,7 +712,7 @@ EventStoreNodeConnection.prototype._enqueueOperation = function(operation) {
var message = new messages.StartOperationMessage(operation, self._settings.maxRetries, self._settings.operationTimeout);
function tryEnqueue() {
if (self._handler.totalOperationCount >= self._settings.maxQueueSize) {
setImmediate(tryEnqueue);
setTimeout(tryEnqueue, 0);
return;
}
self._handler.enqueueMessage(message);
@ -721,4 +720,4 @@ EventStoreNodeConnection.prototype._enqueueOperation = function(operation) {
setImmediate(tryEnqueue)
};
module.exports = EventStoreNodeConnection;
module.exports = EventStoreNodeConnection;

22
src/eventStorePersistentSubscriptionBase.js

@ -56,8 +56,7 @@ EventStorePersistentSubscriptionBase.prototype.acknowledge = function(events) {
ensure.notNull(events, "events");
if (this._subscription === null) throw new Error("Invalid operation. Subscription is not active yet.");
if (!Array.isArray(events))
events = [events];
if (!Array.isArray(events)) events = [events];
var ids = events.map(function(x) { return x.originalEvent.eventId; });
this._subscription.notifyEventsProcessed(ids);
};
@ -73,8 +72,7 @@ EventStorePersistentSubscriptionBase.prototype.fail = function(events, action, r
ensure.notNull(reason, "reason");
if (this._subscription === null) throw new Error("Invalid operation. Subscription is not active yet.");
if (!Array.isArray(events))
events = [events];
if (!Array.isArray(events)) events = [events];
var ids = events.map(function(x) { return x.originalEvent.eventId; });
this._subscription.notifyEventsFailed(ids, action, reason);
};
@ -145,12 +143,12 @@ EventStorePersistentSubscriptionBase.prototype._processQueue = function() {
return self._eventAppeared(self, ev);
})
.then(function() {
if(self._autoAck)
self._subscription.notifyEventsProcessed([ev.originalEvent.eventId]);
if (self._verbose)
if(self._autoAck) self._subscription.notifyEventsProcessed([ev.originalEvent.eventId]);
if (self._verbose) {
self._log.debug("Persistent Subscription to %s: processed event (%s, %d, %s @ %d).",
self._streamId, ev.originalEvent.eventStreamId, ev.originalEvent.eventNumber, ev.originalEvent.eventType,
ev.originalEventNumber);
}
return false;
}, function(err) {
//TODO GFY should we autonak here?
@ -168,12 +166,12 @@ EventStorePersistentSubscriptionBase.prototype._dropSubscription = function(reas
if (!this._isDropped)
{
this._isDropped = true;
if (this._verbose)
if (this._verbose) {
this._log.debug("Persistent Subscription to %s: dropping subscription, reason: %s %s.",
this._streamId, reason, error);
this._streamId, reason, error);
}
if (this._subscription !== null)
this._subscription.unsubscribe();
if (this._subscription !== null) this._subscription.unsubscribe();
if (this._subscriptionDropped !== null) {
try {
this._subscriptionDropped(this, reason, error);
@ -185,4 +183,4 @@ EventStorePersistentSubscriptionBase.prototype._dropSubscription = function(reas
}
};
module.exports = EventStorePersistentSubscriptionBase;
module.exports = EventStorePersistentSubscriptionBase;

23
src/eventStoreStreamCatchUpSubscription.js

@ -49,19 +49,18 @@ EventStoreStreamCatchUpSubscription.prototype._readEventsTill = function(
.then(function()