ExpressenAB / exp-leader-election

Leader election for nodejs applications
MIT License
7 stars 7 forks source link

404 response code from Consul leads to unhandled exception #7

Open ScavengerSpb opened 2 years ago

ScavengerSpb commented 2 years ago

Disclaimer: The issue occurred during debugging so it's unlikely to happen in wildlife.

Due to some reason the leader key was deleted so consul returned 404 error code for which consul library (0.40.0) has special handling. This resulted in undefined being pushed to callback as the call result of client.kv.get method. Console output with debug messages printed to console:

Read key .../leader result:  undefined
...\node_modules\consul\lib\kv.js:56
    if (res && res.statusCode === 404) return callback(undefined, undefined, res);
                                              ^
TypeError: Cannot read properties of undefined (reading 'ModifyIndex')
    at ...\node_modules\exp-leader-election\index.js:55:23
    at Consul.<anonymous> (...\node_modules\consul\lib\kv.js:56:47)
    at next (...\node_modules\papi\lib\client.js:313:25)

It seems when key to read is not found Consul library returns result as undefined to indicate call succeeded but key was not found. It's expected situation so error is not provided as well. Handling of the call result in consul package:

  this.consul._get(req, function(err, res) {
    if (res && res.statusCode === 404) return callback(undefined, undefined, res);
    if (err) return callback(err, undefined, res);
    if (opts.raw) return callback(null, res.body, res);

Callback passed to client.kv.get does not check result for null/undefined so this results in attempt to access property of undefined:

    client.kv.get(waitCmd, (err, res) => {
      if (handleError(err)) return;
      opts.debug("Read key", opts.key, "result: ", res);
      waitIndex = res.ModifyIndex;  <--- Exception is thrown here
      if (!res.Session) {
ScavengerSpb commented 2 years ago

Code to reproduce this issue:

const Consul = require('consul');
const leaderElection = require('exp-leader-election');

const config = {
    debug: console.log,
    key: 'test/leader',
    consul: {
        host: 'localhost',
        port: '8500'
    }
};

leaderElection(config).on('gainedLeadership', () => {
    setTimeout(() => {
        Consul(config.consul).kv.del(config.key, () => {});
    }, 100);
});