Skip to content

Mongo timeouts not handled #34

@jbockerstette

Description

@jbockerstette

For some reason, I am not sure why, but the Centos boxes I am installing on have a 2 minute timeout on mongo connections. When mongo times out, the rest api cannot recover and just hangs. I spent hours trying to fix this problem by adjusting various timeouts to no avail. The way I fixed it is by listening for the timeout and then closing and reconnecting. You must close any open db connections or you will leak them. You cannot just forget about them. I am providing my fix. Here you go....

In mongoHandler.js

/**
 Initialise gets invoked once for each resource that uses this handler.
 */
MongoStore.prototype.initialise = function(resourceConfig) {
  var self = this;
  if (!self._config.url) {
    return console.error("MongoDB url missing from configuration");
  }
  self.resourceConfig = resourceConfig;
  self.relationshipAttributeNames = MongoStore._getRelationshipAttributeNames(resourceConfig.attributes);
  mongodb.MongoClient.connect(self._config.url, {
    server: {
      reconnectTries: 999999999,
      reconnectInterval: 5000
    }
  }).then(function(db) {
    self._db = db;
    self._db.on("timeout", function() {
      self.ready = false;
      self._db.close();
      console.error("mongodb connection timeout.");
      self.initialise(resourceConfig);
    });
    self._db.on("close", function(err) {
      console.error("mongodb connection closed: ", err === undefined ? "timeout" : err.message);
      self.ready = false;
      self._db.collection("Nope").findOne({ _id: 0 }, { _id: 0 }, function() {
        console.error("mongodb connection is back");
        self.ready = true;
      });
    });
  }).catch(function(err) {
    console.error("mongodb connection failed:", err.message);
    setTimeout(function() {
      self.initialise(resourceConfig);
    }, 5000);
  }).then(function() {
    var resourceName = resourceConfig.resource;
    var collection = self._db.collection(resourceName);
    self._createIndexesForRelationships(collection, self.relationshipAttributeNames);
    self.ready = true;
  });
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions