UNPKG

node-eventstore-client

Version:

A port of the EventStore .Net ClientAPI to Node.js

217 lines (185 loc) 17.9 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: core/cluster/clusterDiscoverer.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: core/cluster/clusterDiscoverer.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>const ClusterInfo = require('./clusterInfo'); const GossipSeed = require('../../gossipSeed'); const NodeEndPoints = require('./nodeEndpoints'); const shuffle = require('../../common/utils/shuffle'); function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * ClusterDiscoverer * @constructor * @class * @param {Logger} log - Logger instance * @param {Object} settings - Settings object * @param {Object} dnsService - DNS service to perform DNS lookup * @param {Object} httpService - HTTP service to perform http requests */ function ClusterDiscoverer(log, settings, dnsService, httpService) { if (!settings.clusterDns &amp;&amp; (!settings.seeds || settings.seeds.length === 0)) throw new Error('Both clusterDns and seeds are null/empty.'); this._log = log; this._settings = settings; this._dnsService = dnsService; this._httpService = httpService; } /** * Discover Cluster endpoints * @param {Object} failedTcpEndPoint - The failed TCP endpoint which were used by the handler * @returns {Promise.&lt;NodeEndPoints>} */ ClusterDiscoverer.prototype.discover = async function (failedTcpEndPoint) { let attempts = 0; while (attempts++ &lt; this._settings.maxDiscoverAttempts) { try { const candidates = await this._getGossipCandidates(this._settings.managerExternalHttpPort); const gossipSeeds = candidates.filter( (candidate) => !failedTcpEndPoint || !(candidate.endPoint.host === failedTcpEndPoint.host &amp;&amp; candidate.endPoint.port === failedTcpEndPoint.port) ); let gossipSeedsIndex = 0; let clusterInfo; do { try { clusterInfo = await this._clusterInfo(gossipSeeds[gossipSeedsIndex], this._settings.gossipTimeout); if (!clusterInfo.bestNode) { this._log.info( `Discovering attempt ${attempts}/${this._settings.maxDiscoverAttempts} failed: no candidate found.` ); continue; } } catch (err) {} } while (++gossipSeedsIndex &lt; gossipSeeds.length); if (clusterInfo) { return NodeEndPoints.createFromGossipMember(clusterInfo.bestNode); } } catch (err) { this._log.info( `Discovering attempt ${attempts}/${this._settings.maxDiscoverAttempts} failed with error: ${err}.\n${err.stack}` ); } await wait(this._settings.discoverDelay); } throw new Error(`Failed to discover candidate in ${this._settings.maxDiscoverAttempts} attempts.`); }; /** * Get gossip candidates either from DNS or from gossipSeeds settings * @private * @param {Number} managerExternalHttpPort - Http port of the manager (or the http port of the node for OSS clusters) * @returns {Promise.&lt;GossipSeed[]>} */ ClusterDiscoverer.prototype._getGossipCandidates = async function (managerExternalHttpPort) { const gossipSeeds = this._settings.seeds &amp;&amp; this._settings.seeds.length > 0 ? this._settings.seeds : (await this._resolveDns(this._settings.clusterDns)).map( (address) => new GossipSeed({ host: address, port: managerExternalHttpPort }, address, this._settings.clusterDns) ); return shuffle(gossipSeeds); }; /** * Resolve the cluster DNS discovery address to retrieve belonging ip addresses * @private * @param {String} clusterDns - Cluster DNS discovery address * @returns {Promise.&lt;String[]>} */ ClusterDiscoverer.prototype._resolveDns = async function (clusterDns) { const dnsOptions = { family: 4, hints: this._dnsService.ADDRCONFIG | this._dnsService.V4MAPPED, all: true, }; const result = await this._dnsService.lookup(clusterDns, dnsOptions); if (!result || result.length === 0) { throw new Error(`No result from dns lookup for ${clusterDns}`); } return result.map((address) => address.address); }; /** * Get cluster informations (gossip members) * @param {GossipSeed} candidate - candidate to get informations from * @param {Number} timeout - timeout for the http request * @returns {Promise.&lt;ClusterInfo>} */ ClusterDiscoverer.prototype._clusterInfo = async function (candidate, timeout) { var self = this; return new Promise((resolve, reject) => { const options = { host: candidate.endPoint.host, port: candidate.endPoint.port, path: '/gossip?format=json', timeout: timeout, rejectUnauthorized: self._settings.rejectUnauthorized }; if (candidate.hostHeader) { options.headers = { Host: candidate.hostHeader, }; } const request = this._httpService.request(options, (res) => { if (res.statusCode !== 200) { this._log.info('Trying to get gossip from', candidate, 'failed with status code:', res.statusCode); reject(new Error(`Gossip candidate returns a ${res.statusCode} error`)); return; } let result = ''; res.on('data', (chunk) => { result += chunk.toString(); }); res.on('end', function () { try { result = JSON.parse(result); } catch (e) { reject(new Error('Unable to parse gossip response')); } resolve(new ClusterInfo(result.members)); }); }); request.setTimeout(timeout); request.on('timeout', () => { this._log.info('Trying to get gossip from', candidate, 'timed out.'); request.destroy(); reject(new Error('Connection to gossip timed out')); }); request.on('error', (error) => { this._log.info('Trying to get gossip from', candidate, 'errored', error); request.destroy(); reject(new Error('Connection to gossip errored')); }); request.end(); }); }; module.exports = ClusterDiscoverer; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Namespaces</h3><ul><li><a href="EventStore.html">EventStore</a></li><li><a href="EventStore.Client.html">Client</a></li><li><a href="EventStore.Client.Messages.html">Messages</a></li></ul><h3>Classes</h3><ul><li><a href="AllEventsSlice.html">AllEventsSlice</a></li><li><a href="ClusterDiscoverer.html">ClusterDiscoverer</a></li><li><a href="DeleteResult.html">DeleteResult</a></li><li><a href="EventReadResult.html">EventReadResult</a></li><li><a href="EventStore.Client.Messages.CheckpointReached.html">CheckpointReached</a></li><li><a href="EventStore.Client.Messages.ClientIdentified.html">ClientIdentified</a></li><li><a href="EventStore.Client.Messages.ConnectToPersistentSubscription.html">ConnectToPersistentSubscription</a></li><li><a href="EventStore.Client.Messages.CreatePersistentSubscription.html">CreatePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.CreatePersistentSubscriptionCompleted.html">CreatePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.DeletePersistentSubscription.html">DeletePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.DeletePersistentSubscriptionCompleted.html">DeletePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.DeleteStream.html">DeleteStream</a></li><li><a href="EventStore.Client.Messages.DeleteStreamCompleted.html">DeleteStreamCompleted</a></li><li><a href="EventStore.Client.Messages.EventRecord.html">EventRecord</a></li><li><a href="EventStore.Client.Messages.Filter.html">Filter</a></li><li><a href="EventStore.Client.Messages.FilteredReadAllEvents.html">FilteredReadAllEvents</a></li><li><a href="EventStore.Client.Messages.FilteredReadAllEventsCompleted.html">FilteredReadAllEventsCompleted</a></li><li><a href="EventStore.Client.Messages.FilteredSubscribeToStream.html">FilteredSubscribeToStream</a></li><li><a href="EventStore.Client.Messages.IdentifyClient.html">IdentifyClient</a></li><li><a href="EventStore.Client.Messages.NewEvent.html">NewEvent</a></li><li><a href="EventStore.Client.Messages.NotHandled.html">NotHandled</a></li><li><a href="EventStore.Client.Messages.NotHandled.LeaderInfo.html">LeaderInfo</a></li><li><a href="EventStore.Client.Messages.PersistentSubscriptionAckEvents.html">PersistentSubscriptionAckEvents</a></li><li><a href="EventStore.Client.Messages.PersistentSubscriptionConfirmation.html">PersistentSubscriptionConfirmation</a></li><li><a href="EventStore.Client.Messages.PersistentSubscriptionNakEvents.html">PersistentSubscriptionNakEvents</a></li><li><a href="EventStore.Client.Messages.PersistentSubscriptionStreamEventAppeared.html">PersistentSubscriptionStreamEventAppeared</a></li><li><a href="EventStore.Client.Messages.ReadAllEvents.html">ReadAllEvents</a></li><li><a href="EventStore.Client.Messages.ReadAllEventsCompleted.html">ReadAllEventsCompleted</a></li><li><a href="EventStore.Client.Messages.ReadEvent.html">ReadEvent</a></li><li><a href="EventStore.Client.Messages.ReadEventCompleted.html">ReadEventCompleted</a></li><li><a href="EventStore.Client.Messages.ReadStreamEvents.html">ReadStreamEvents</a></li><li><a href="EventStore.Client.Messages.ReadStreamEventsCompleted.html">ReadStreamEventsCompleted</a></li><li><a href="EventStore.Client.Messages.ResolvedEvent.html">ResolvedEvent</a></li><li><a href="EventStore.Client.Messages.ResolvedIndexedEvent.html">ResolvedIndexedEvent</a></li><li><a href="EventStore.Client.Messages.ScavengeDatabase.html">ScavengeDatabase</a></li><li><a href="EventStore.Client.Messages.ScavengeDatabaseResponse.html">ScavengeDatabaseResponse</a></li><li><a href="EventStore.Client.Messages.StreamEventAppeared.html">StreamEventAppeared</a></li><li><a href="EventStore.Client.Messages.SubscribeToStream.html">SubscribeToStream</a></li><li><a href="EventStore.Client.Messages.SubscriptionConfirmation.html">SubscriptionConfirmation</a></li><li><a href="EventStore.Client.Messages.SubscriptionDropped.html">SubscriptionDropped</a></li><li><a href="EventStore.Client.Messages.TransactionCommit.html">TransactionCommit</a></li><li><a href="EventStore.Client.Messages.TransactionCommitCompleted.html">TransactionCommitCompleted</a></li><li><a href="EventStore.Client.Messages.TransactionStart.html">TransactionStart</a></li><li><a href="EventStore.Client.Messages.TransactionStartCompleted.html">TransactionStartCompleted</a></li><li><a href="EventStore.Client.Messages.TransactionWrite.html">TransactionWrite</a></li><li><a href="EventStore.Client.Messages.TransactionWriteCompleted.html">TransactionWriteCompleted</a></li><li><a href="EventStore.Client.Messages.UnsubscribeFromStream.html">UnsubscribeFromStream</a></li><li><a href="EventStore.Client.Messages.UpdatePersistentSubscription.html">UpdatePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.UpdatePersistentSubscriptionCompleted.html">UpdatePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.WriteEvents.html">WriteEvents</a></li><li><a href="EventStore.Client.Messages.WriteEventsCompleted.html">WriteEventsCompleted</a></li><li><a href="EventStoreCatchUpSubscription.html">EventStoreCatchUpSubscription</a></li><li><a href="EventStoreNodeConnection.html">EventStoreNodeConnection</a></li><li><a href="EventStoreTransaction.html">EventStoreTransaction</a></li><li><a href="PersistentSubscriptionCreateResult.html">PersistentSubscriptionCreateResult</a></li><li><a href="PersistentSubscriptionDeleteResult.html">PersistentSubscriptionDeleteResult</a></li><li><a href="PersistentSubscriptionUpdateResult.html">PersistentSubscriptionUpdateResult</a></li><li><a href="Position.html">Position</a></li><li><a href="ProjectionsManager.html">ProjectionsManager</a></li><li><a href="RawStreamMetadataResult.html">RawStreamMetadataResult</a></li><li><a href="RecordedEvent.html">RecordedEvent</a></li><li><a href="ResolvedEvent.html">ResolvedEvent</a></li><li><a href="StreamEventsSlice.html">StreamEventsSlice</a></li><li><a href="UserCredentials.html">UserCredentials</a></li><li><a href="WriteResult.html">WriteResult</a></li></ul><h3>Interfaces</h3><ul><li><a href="EventStore.Client.Messages.ICheckpointReached.html">ICheckpointReached</a></li><li><a href="EventStore.Client.Messages.IClientIdentified.html">IClientIdentified</a></li><li><a href="EventStore.Client.Messages.IConnectToPersistentSubscription.html">IConnectToPersistentSubscription</a></li><li><a href="EventStore.Client.Messages.ICreatePersistentSubscription.html">ICreatePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.ICreatePersistentSubscriptionCompleted.html">ICreatePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.IDeletePersistentSubscription.html">IDeletePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.IDeletePersistentSubscriptionCompleted.html">IDeletePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.IDeleteStream.html">IDeleteStream</a></li><li><a href="EventStore.Client.Messages.IDeleteStreamCompleted.html">IDeleteStreamCompleted</a></li><li><a href="EventStore.Client.Messages.IEventRecord.html">IEventRecord</a></li><li><a href="EventStore.Client.Messages.IFilter.html">IFilter</a></li><li><a href="EventStore.Client.Messages.IFilteredReadAllEvents.html">IFilteredReadAllEvents</a></li><li><a href="EventStore.Client.Messages.IFilteredReadAllEventsCompleted.html">IFilteredReadAllEventsCompleted</a></li><li><a href="EventStore.Client.Messages.IFilteredSubscribeToStream.html">IFilteredSubscribeToStream</a></li><li><a href="EventStore.Client.Messages.IIdentifyClient.html">IIdentifyClient</a></li><li><a href="EventStore.Client.Messages.INewEvent.html">INewEvent</a></li><li><a href="EventStore.Client.Messages.INotHandled.html">INotHandled</a></li><li><a href="EventStore.Client.Messages.IPersistentSubscriptionAckEvents.html">IPersistentSubscriptionAckEvents</a></li><li><a href="EventStore.Client.Messages.IPersistentSubscriptionConfirmation.html">IPersistentSubscriptionConfirmation</a></li><li><a href="EventStore.Client.Messages.IPersistentSubscriptionNakEvents.html">IPersistentSubscriptionNakEvents</a></li><li><a href="EventStore.Client.Messages.IPersistentSubscriptionStreamEventAppeared.html">IPersistentSubscriptionStreamEventAppeared</a></li><li><a href="EventStore.Client.Messages.IReadAllEvents.html">IReadAllEvents</a></li><li><a href="EventStore.Client.Messages.IReadAllEventsCompleted.html">IReadAllEventsCompleted</a></li><li><a href="EventStore.Client.Messages.IReadEvent.html">IReadEvent</a></li><li><a href="EventStore.Client.Messages.IReadEventCompleted.html">IReadEventCompleted</a></li><li><a href="EventStore.Client.Messages.IReadStreamEvents.html">IReadStreamEvents</a></li><li><a href="EventStore.Client.Messages.IReadStreamEventsCompleted.html">IReadStreamEventsCompleted</a></li><li><a href="EventStore.Client.Messages.IResolvedEvent.html">IResolvedEvent</a></li><li><a href="EventStore.Client.Messages.IResolvedIndexedEvent.html">IResolvedIndexedEvent</a></li><li><a href="EventStore.Client.Messages.IScavengeDatabase.html">IScavengeDatabase</a></li><li><a href="EventStore.Client.Messages.IScavengeDatabaseResponse.html">IScavengeDatabaseResponse</a></li><li><a href="EventStore.Client.Messages.IStreamEventAppeared.html">IStreamEventAppeared</a></li><li><a href="EventStore.Client.Messages.ISubscribeToStream.html">ISubscribeToStream</a></li><li><a href="EventStore.Client.Messages.ISubscriptionConfirmation.html">ISubscriptionConfirmation</a></li><li><a href="EventStore.Client.Messages.ISubscriptionDropped.html">ISubscriptionDropped</a></li><li><a href="EventStore.Client.Messages.ITransactionCommit.html">ITransactionCommit</a></li><li><a href="EventStore.Client.Messages.ITransactionCommitCompleted.html">ITransactionCommitCompleted</a></li><li><a href="EventStore.Client.Messages.ITransactionStart.html">ITransactionStart</a></li><li><a href="EventStore.Client.Messages.ITransactionStartCompleted.html">ITransactionStartCompleted</a></li><li><a href="EventStore.Client.Messages.ITransactionWrite.html">ITransactionWrite</a></li><li><a href="EventStore.Client.Messages.ITransactionWriteCompleted.html">ITransactionWriteCompleted</a></li><li><a href="EventStore.Client.Messages.IUnsubscribeFromStream.html">IUnsubscribeFromStream</a></li><li><a href="EventStore.Client.Messages.IUpdatePersistentSubscription.html">IUpdatePersistentSubscription</a></li><li><a href="EventStore.Client.Messages.IUpdatePersistentSubscriptionCompleted.html">IUpdatePersistentSubscriptionCompleted</a></li><li><a href="EventStore.Client.Messages.IWriteEvents.html">IWriteEvents</a></li><li><a href="EventStore.Client.Messages.IWriteEventsCompleted.html">IWriteEventsCompleted</a></li><li><a href="EventStore.Client.Messages.NotHandled.ILeaderInfo.html">ILeaderInfo</a></li></ul><h3>Global</h3><ul><li><a href="global.html#createConnection">createConnection</a></li><li><a href="global.html#createEventData">createEventData</a></li><li><a href="global.html#createJsonEventData">createJsonEventData</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.0</a> on Mon Jan 30 2023 16:18:36 GMT-0500 (Eastern Standard Time) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>