thenativeweb / node-eventstore

EventStore Implementation in node.js
http://eventstore.js.org/
MIT License
539 stars 117 forks source link

Calling `es.init()` multiple times causes multiple `connect` & `disconnect` listeners to be added #153

Closed kerdany closed 4 years ago

kerdany commented 4 years ago

Hi, I would first like to thank you for the nice and very useful library.

I'm writing down code to ensure that the connection to the database (currently using MongoDB) is always up, by handling cases like:

I tried to handle this in a retry function that calls es.init(), however, calling init multiple times causes the following warnings to be fired:

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connect listeners added. Use emitter.setMaxListeners() to increase limit

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 disconnect listeners added. Use emitter.setMaxListeners() to increase limit

This also causes any connect and disconnect handlers to be called multiple times, and I'm also concerned that init wasn't written with these scenarios in mind, which might cause other issues.

I understand that the implementation of init already handles the retry part while connecting -for the first time- (via the tolerance library), but it doesn't handle the "reconnect after a disconnection" scenarios, and external code initiating the library might have reasons to reconnect/reinitiate for any other reasons.

Is there a workaround? For example by calling es.store.connect() directly (to reconnect)? And if so, will that cause any problem initiating the dispatcher?

Thanks

adrai commented 4 years ago

May I ask how your mongodb options look like? There’s a possibility to define autoReconnect for mongodb...

kerdany commented 4 years ago

Thanks @adrai, autoReconnect did the trick, my bad!

To answer your question, here're the options (after enabling autoReconnect):

const store = eventstore({
  type: "mongodb",
  host: "mongo",
  port: 27017,
  dbName: MONGODB_DATABASE,
  authSource: MONGODB_DATABASE,
  username: MONGODB_USERNAME,
  password: MONGODB_PASSWORD,
  eventsCollectionName: "events",
  snapshotsCollectionName: "snapshots",
  transactionsCollectionName: "transactions",
  positionsCollectionName: "positions",
  timeout: Number(RETRY_ATTEMPTS) * Number(RETRY_INTERVAL),
  options: {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    poolSize: Number(MONGODB_POOLSIZE),
    autoReconnect: true,
    reconnectTries: Number(RETRY_ATTEMPTS),
    reconnectInterval: Number(RETRY_INTERVAL),
    //loggerLevel: 'debug',
    appname: 'EventStore'
  }
});