All files / copacetic/lib copacetic.js

97.87% Statements 92/94
87.17% Branches 34/39
97.29% Functions 36/37
97.72% Lines 86/88

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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 3791x   1x 1x 1x 1x   1x 1x   1x                   36x   36x 36x 36x 36x 36x             10x 13x 13x             14x                           3x                       124x 41x     83x               62x                 40x   40x         38x 38x   38x                 3x   3x       2x   2x 3x   2x                     2x   2x                                                                             5x 5x 5x 1x 4x   5x 5x   5x 3x         3x     5x     5x   5x       5x     5x         5x 5x   5x             5x 5x                 5x         4x                                                                     11x   11x 6x 5x   11x 4x     7x 5x             2x             3x     7x 2x             2x     7x                                     2x   2x 1x           1x     1x   1x                 20x         20x                       9x 8x 11x       1x 2x         36x    
const EventEmitter = require('events')
 
const precond = require('precond')
const isObject = require('lodash.isobject')
const cloneDeep = require('lodash.clonedeep')
const humanInterval = require('human-interval')
 
const promiseAllSilent = require('./util/promise-all-silent')
const promiseSeriesSilent = require('./util/promise-series-silent')
 
module.exports = (Dependency) => {
  /**
   * @class
   * @extends EventEmitter
   */
  class Copacetic extends EventEmitter {
    /**
     * @param {String} [name=''] The name of your service
     */
    constructor (name = '', eventEmitterMode = true) {
      super()
 
      this.isPolling = false
      this.name = name
      this.eventEmitterMode = eventEmitterMode
      this.dependencyNames = []
      this.dependencyIndex = {}
    }
 
    /**
     * @return {Boolean} Copacetic is healthy when all hard dependencies are healthy
     */
    get isHealthy () {
      return !this
        .dependencyNames.map(s => this.getDependency(s).healthSummary)
        .some(health => health.level === 'HARD' && health.healthy === false)
    }
 
    /**
     * @return {Array<DependencyHealth>} Health information on all dependencies
     */
    get healthInfo () {
      return this.dependencyNames.map(s => this.getDependency(s).healthSummary)
    }
 
    /**
     * @return {HealthReport} A full report of health information and dependencies
     */
    get healthReport () {
      /**
       * The full health report including isHealthy and dependencies
       * @typedef {Object} HealthReport
       * @property {Boolean} isHealthy The result of {@link Copacetic#isHealthy}
       * @property {String} Name
       * @property {Array<DependencyHealth>} dependencies The result of {@link Copacetic#healthInfo}
       */
      return {
        name: this.name,
        isHealthy: this.isHealthy,
        dependencies: this.healthInfo
      }
    }
 
    /**
     * @param {Dependency|String} dependency
     * @return {Dependency}
     */
    getDependency (dependency) {
      if (isObject(dependency)) {
        return this.dependencyIndex[dependency.name]
      }
 
      return this.dependencyIndex[dependency]
    }
 
    /**
     * @param {Dependency|String} dependency
     * @return {Boolean} Whether the dependency has been registered
     */
    isDependencyRegistered (dependency) {
      return !!this.getDependency(dependency)
    }
 
    /**
     * Adds a dependency to a Copacetic instance
     * @param {Object} opts The configuration for a dependency
     * @return {Copacetic}
     */
    registerDependency (opts) {
      const dependency = Dependency(opts)
 
      precond.checkState(
        this.isDependencyRegistered(dependency) === false,
        `Dependency ${dependency.name} was already registered`
      )
 
      this.dependencyNames.push(dependency.name)
      this.dependencyIndex[dependency.name] = dependency
 
      return this
    }
 
    /**
     * Removes a dependency from a Copacetic instance
     * @param {String} name The name used to identify a dependency
     * @return {Copacetic}
     */
    deregisterDependency (dependency) {
      const resolved = this.getDependency(dependency)
 
      precond.checkIsDef(
        resolved,
        'Tried to deregister dependency, but dependency is not registered'
      )
      resolved.cleanup()
 
      delete this.dependencyIndex[resolved.name]
      this.dependencyNames = this.dependencyNames.filter(n => n !== resolved.name)
 
      return this
    }
 
    /**
     * Polls the health of all registered dependencies
     * @param {String} [interval='5 seconds']
     * @param {Boolean} [parallel=true]
     * @param {String} [schedule='start']
     * @return {Copacetic}
     */
    pollAll ({ interval, parallel, schedule } = {}) {
      this.poll({ dependencies: 'all', interval, parallel, schedule })
 
      return this
    }
 
    /**
     * Polls the health of a set of dependencies
     * @example
     * copacetic.poll({
     *   dependencies: [
     *     { name: 'my-dep' },
     *     { name: 'my-other-dep', retries: 2, maxDelay: '2 seconds' }
     *   ],
     *   schedule: 'end',
     *   interval: '1 minute 30 seconds'
     * })
     * .on('health', (serviceHealth, stop) => {
     *   // Do something with the result
     *   // [{ name: String, health: Boolean, level: HARD/SOFT, lastCheck: Date }]
     *   // stop polling
     *   stop()
     * })
     * @example
     * copacetic.poll({ name: 'my-dependency' })
     * .on('health', () => { ... Do something })
     * @fires Copacetic#health
     * @param {String} [name] The identifier of a single dependency to be checked
     * @param {Array<Object>} [dependencies] An explicit set of dependencies to be polled
     * @param {String} [interval='5 seconds']
     * @param {Boolean} [parallel=true] Kick of health checks in parallel or series
     * @param {String} [schedule='start'] Schedule the next check to start (interval - ms) | ms
     * @return {Copacetic}
     */
    poll ({
      name,
      dependencies,
      interval = '5 seconds',
      maxDelay = '30 seconds',
      parallel = true,
      schedule = 'start'
    } = {}) {
      const intervalMs = humanInterval(interval)
      const start = process.hrtime()
      const _check = name
        ? () => this._checkOne(name, 1, humanInterval(maxDelay))
        : (_dependencies) => this._checkMany(_dependencies, parallel)
 
      const loop = () => {
        let _dependencies = []
 
        if (dependencies === 'all') {
          _dependencies = this.dependencyNames.map(s => ({
            name: this.getDependency(s).name,
            retries: 1
          }))
        } else {
          _dependencies = dependencies
        }
 
        _check(_dependencies)
          .catch(e => e)
          .then((res) => {
            this.emit('health', res, this.stop.bind(this))
 
            const delay = schedule === 'start'
              ? intervalMs - (process.hrtime(start)[1] * 1e-6)
              : intervalMs
 
            Iif (this.isPolling !== false) {
              this.pollTimeout = setTimeout(loop, delay)
            } else {
              this.emit('stopped')
            }
          })
      }
 
      this.isPolling = true
      loop()
 
      return this
    }
 
    /**
     * stops polling registered dependencies
     */
    stop () {
      this.isPolling = false
      clearTimeout(this.pollTimeout)
    }
 
    /**
     * Checks the health of all registered dependencies
     * @param {Boolean} [parallel=true] Kick of health checks in parallel or series
     * @return {Copacetic}
     */
    checkAll (parallel) {
      const dependencies = this.dependencyNames.map(s => ({
        name: this.getDependency(s).name,
        retries: 1
      }))
 
      return this.check({ dependencies, parallel })
    }
 
    /**
     * Checks the health of a set, or single dependency
     * @example
     * copacetic.check({ name: 'my-dependency' })
     * @example
     * copacetic.check({ name: 'my-dependency', retries: 5 })
     * .on('healthy', serviceHealth => { ... Do stuff })
     * .on('unhealthy', serviceHealth => { ... Handle degraded state })
     * @example
     * copacetic.check({ dependencies: [
     *   { name: 'my-dep' },
     *   { name: 'my-other-dep', retries: 2, maxDelay: '1 second' }
     * ] })
     * .on('health', (servicesHealth) => {
     *   // Do something with the result
     *   // [{ name: String, health: Boolean, level: HARD/SOFT, lastCheck: Date }]
     * })
     * @example
     * copacetic.check({ name: 'my-dependency' })
     * .then((health) => { ... Do Stuff })
     * .catch((err) => { ... Handle degraded state })
     * @fires Copacetic#health
     * @fires Copacetic#healthy
     * @fires Copacetic#unhealthy
     * @param {String} [name] The identifier of a single dependency to be checked
     * @param {Array<Object>} [dependencies] An explicit set of dependencies to be checked
     * @param {Integer} [retries=1] How many times should a dependency be checked, until it
     * is deemed unhealthy
     * @param {Boolean} [parallel=true] Kick of health checks in parallel or series
     * @return {Copacetic}
     */
    check ({ name, dependencies, retries = 1, maxDelay = '30 seconds', parallel = true } = {}) {
      precond.checkIsNumber(retries, 'retries must be an integer')
 
      const doCheck = name
        ? () => this._checkOne(name, retries, humanInterval(maxDelay))
        : () => this._checkMany(dependencies, parallel)
 
      if (!this.eventEmitterMode) {
        return doCheck()
      }
 
      if (name) {
        doCheck()
          /**
           * Health information on a single dependency
           *
           * @event Copacetic#healthy
           * @type {HealthInfo}
           */
          .then(s => this.emit('healthy', s))
          /**
           * Health information on a single dependency
           *
           * @event Copacetic#unhealthy
           * @type {HealthInfo}
           */
          .catch(s => this.emit('unhealthy', s))
      }
 
      if (dependencies) {
        doCheck()
          /**
           * Health information on a set of dependencies
           *
           * @event Copacetic#health
           * @type {Array<HealthInfo>}
           */
          .then(s => this.emit('health', s))
      }
 
      return this
    }
 
    /**
     * Convenience method that waits for a single, or set of dependencies
     * to become healthy. Calling this means copacetic will keep re-checking
     * indefinitely until the dependency(s) become healthy. If you want more
     * control, use .check().
     * @example
     * // wait indefinitely
     * copacetic.waitFor({ name: 'my-dependency'})
     * .on('healthy', serviceHealth => { ... Do stuff })
     * @example
     * // give up after 5 tries
     * copacetic.waitFor({ name: 'my-dependency', retries: 5})
     * .on('healthy', serviceHealth => { ... Do stuff })
     * @param {Object} opts - options accepted by check()
     */
    waitFor (opts = {}) {
      const _opts = cloneDeep(opts)
 
      if (opts.dependencies) {
        _opts.dependencies = _opts.dependencies.map((d) => ({
          name: d.name,
          retries: 0,
          maxDelay: d.maxDelay || 0
        }))
 
        return this.check(_opts)
      }
 
      _opts.retries = 0
 
      return this.check(_opts)
    }
 
    /**
     * @param {String} name The name used to identify a dependency
     * @param {Integer} maxDelay The maximum interval of time to wait when retrying
     * @return {Promise}
     */
    _checkOne (name, retries, maxDelay) {
      precond.checkState(
        this.isDependencyRegistered(name) === true,
        `Tried to check dependency - ${name}, but dependency is not registered`
      )
 
      return this
        .getDependency(name)
        .check(retries, maxDelay)
    }
 
    /**
     * Checks an array of dependencies in parallel or sequantially
     * @param {Array<Dependency>} dependencies
     * @param {Boolean} parallel
     * @return {Promise}
     */
    _checkMany (dependencies, parallel) {
      if (parallel) {
        return promiseAllSilent(
          dependencies.map(s => this._checkOne(s.name, s.retries, s.maxDelay))
        )
      }
 
      return promiseSeriesSilent(
        dependencies.map(s => this._checkOne(s.name, s.retries, s.maxDelay))
      )
    }
  }
 
  return (name, mode) => new Copacetic(name, mode)
}