All files / lib health.js

94.33% Statements 100/106
95.55% Branches 43/45
96% Functions 24/25
94.05% Lines 95/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233    1x 1x 1x 1x 1x   1x                   21x   21x         21x           21x               1x 1x           1x 1x                 1x 4x   4x 4x 4x 4x 4x   4x 4x 4x 3x 3x   3x 2x 2x 1x   1x 1x 1x     1x   1x 1x       1x     1x                               4x       4x 4x 4x 2x   2x         4x 2x 2x     1x   5x 5x   5x     5x 2x       5x 5x 1x 1x 1x 1x     5x     1x 6x     26x 6x       26x     6x 30x 26x             6x 2x 2x   6x       6x 6x 26x 4x             6x         6x 26x 26x 6x   6x 26x   26x 13x 7x       13x 3x           6x     1x   5x   5x 5x         5x     1x  
'use strict';
 
const cache = require('memory-cache');
const fs = require('fs');
const i18n = require('i18n');
const path = require('path');
const url = require('url');
 
const Result = require('./result');
 
/**
 * class Health
 *
 * @param {Object} opts
 * - setup: health check setup object:
 *   each must have uri field, with optional ttl field (in milliseconds), and type-specific fields
 */
function Health(opts) {
    opts = opts || {};
 
    this.opts = {
        setup: opts.setup || 'health.json',
        locale: opts.locale || 'en'
    };
 
    i18n.configure({
        locales: ['en', 'id'],
        defaultLocale: 'en',
        directory: path.join(__dirname, '../locales'),
        updateFiles: false
    });
    i18n.setLocale(this.opts.locale);
}
 
/**
 * Create a sample health.json setup file in current working directory.
 *
 * @param {Function} cb: standard cb(err, result) callback
 */
Health.prototype.init = function (cb) {
    fs.copyFile(path.join(__dirname, '../examples/health.json'), 'health.json', cb);
};
 
/**
 * Clear all cached check result for all resources.
 */
Health.prototype.clearCache = function () {
    cache.clear();
};
 
/**
 * Execute the checks contained in setup, in parallel.
 * Each result will be cached depends on TTL setting for each URI,
 *
 * @param {Function} cb: standard cb(err, result) callback
 */
Health.prototype.check = function (cb) {
    const TTL = 1;
 
    var tasks = [],
        self = this;
    this.opts.setup.forEach(function (setup) {
        var taskFn = function (setup, cb) {
            Promise.resolve(setup.uri)
                .then(function (uri) {
                    setup.uri = uri;
                    var checker = self._checker(setup.uri, setup.checker);
                    if (checker) {
                        var cached = cache.get(setup.uri),
                            startTime = Date.now();
 
                        if (cached === null) {
                            checker.check(setup, function (err, result) {
                                if (err) {
                                    cb(err);
                                } else {
                                    var endTime = Date.now();
                                    result.setDuration(endTime - startTime);
                                    result.setTimestamp(new Date(endTime));
 
                                    // apply rules to each single result
                                    result = self._singleResultRules(result, setup);
 
                                    cache.put(setup.uri, result, setup.ttl || TTL);
                                    cb(null, result);
                                }
                            });
                        } else {
                            cb(null, cached);
                        }
                    } else {
                        cb(new Error(i18n.__('Unsupported protocol for URI %s', uri)));
                    }
                })
                .catch(function (err) {
                    var result = new Result();
                    result.addError(err.message);
                    result.setStatusByStats();
 
                    setup.uri = '';
 
                    result = self._singleResultRules(result, setup);
 
                    cb(null, result);
                });
        };
 
        tasks.push(taskFn.bind(this, setup));
    });
 
    // Convert callback-based tasks to Promise-based tasks
    const promiseTasks = tasks.map(task => new Promise((resolve, reject) => {
        task((err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    }));
 
    Promise.all(promiseTasks)
        .then(results => cb(null, results))
        .catch(err => cb(err));
};
 
Health.prototype._singleResultRules = function (result, setup) {
    // basic info
    Eif (setup.name) {
        result.setName(setup.name);
    }
    result.setUri(setup.uri);
 
    // camouflage fail status as warn when lenient is true
    if (setup.lenient === true && (result.isFail() || result.isError())) {
        result.warning();
    }
 
    // mask password
    var parsedUri = url.parse(result.getUri());
    if (parsedUri.auth) {
        var userPass = parsedUri.auth.split(':');
        userPass[1] = userPass[1].replace(/./g, '*');
        parsedUri.auth = userPass.join(':');
        result.setUri(url.format(parsedUri));
    }
 
    return result;
};
 
Health.prototype._multiResultsRules = function (results, setup) {
    var groups = {};
 
    function addToGroup(result, group, index) {
        if (!groups[group]) {
            groups[group] = [];
        }
        // store index to avoid re-iterating the whole result
        // for each group when changing the status
        groups[group].push({ index: index, result: result });
    }
 
    for (var i = 0, ln = results.length; i < ln; i += 1) {
        if (setup[i].group) {
            addToGroup(results[i], setup[i].group, i);
        }
    }
 
    // threshold is specified as suffix in group name
    function _getThreshold(group) {
        var threshold;
        if (group.match(/\-[0-9]{1,3}$/)) {
            var elems = group.split('-');
            threshold = parseInt(elems[elems.length - 1], 10);
        }
        return threshold;
    }
 
    function _isSuccess(members, threshold) {
        var successCount = 0;
        members.forEach(function (member) {
            if (member.isSuccess()) {
                successCount += 1;
            }
        });
        // if threshold is undefined, it's considered a success as
        // long as the calculated threshold is greater than 0 (at least one success).
        // if threshold is defined, then it's considered a success
        // when the calculated threshold is equal or greater to the threshold
        return threshold ?
            (successCount * 100 / members.length) >= threshold :
            (successCount * 100 / members.length) > 0;
    }
 
    Object.keys(groups).forEach(function (group) {
        var members = groups[group].map(item => item.result),
            indices = groups[group].map(item => item.index),
            isSuccess = _isSuccess(members, _getThreshold(group));
 
        indices.forEach(function (index) {
            var result = results[index];
            // if group check is considered a success, change all error and fail to warning
            if (isSuccess) {
                if (result.isFail() || result.isError()) {
                    result.warning();
                }
                // if group check is not considered a success, change warning to fail
            } else {
                if (result.isWarning()) {
                    result.fail();
                }
            }
        });
    });
 
    return results;
};
 
Health.prototype._checker = function (uri, checkerName) {
    var checker,
        protocol = uri.match(/^(.+):\/\//);
 
    try {
        checker = require('./checkers/' + (checkerName || protocol[1]));
    } catch (e) {
        // unsupported protocol
    }
 
    return checker;
};
 
module.exports = Health;