all files / dist/satellites/ cache.js

88.89% Statements 176/198
70.94% Branches 83/117
94.23% Functions 49/52
88.95% Lines 161/181
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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617          14×         18×                                                                                                                                                 10× 10× 10×                                                                                                                       19×   19×     19× 19×       19× 12× 12×       19×               19× 19×     18×   18× 18×   18× 11×       18× 18× 18×                                       19×   19× 18× 18×       19×   19×         19× 19×       19×     16× 14× 14× 14×     14×   14×   10×           14× 14×         14× 14× 10×   14× 14× 14×                                               10×     10× 10×                                                                                                                                                                                                     55×     55×         55× 55×   55× 53×                                                                                                                                                                                                                                        
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _async = require('async');
 
var _async2 = _interopRequireDefault(_async);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
/**
 * Cache manager class.
 *
 * This class provides an easy way for developers to make use of a cache system.
 */
 
var CacheManager = function () {
 
  /**
   * Constructor.
   *
   * @param api API reference.
   */
 
 
  /**
   * Lock name.
   *
   * @type {String}
   */
 
 
  /**
   * Lock key prefix.
   *
   * @type {String}
   */
 
 
  /**
   * API reference.
   *
   * @type {null}
   */
 
  function CacheManager(api) {
    _classCallCheck(this, CacheManager);
 
    this.api = null;
    this.redisPrefix = null;
    this.lockPrefix = null;
    this.lockDuration = null;
    this.lockName = null;
    this.lockRetry = 100;
 
    this.api = api;
 
    this.redisPrefix = api.config.general.cachePrefix;
    this.lockPrefix = api.config.general.lockPrefix;
    this.lockDuration = api.config.general.lockDuration;
    this.lockName = api.id;
  }
 
  // ----------------------------------------------------------------------------------------------------------- [Basic]
 
  /**
   * Get all cached keys.
   *
   * @param next  Callback.
   */
 
 
  /**
   * Lock interval to retry.
   *
   * @type {Number}
   */
 
 
  /**
   * Lock duration.
   *
   * @type {Number}
   */
 
 
  /**
   * Cache key prefix.
   *
   * @type {String}
   */
 
 
  _createClass(CacheManager, [{
    key: 'keys',
    value: function keys(next) {
      var self = this;
      self.api.redis.clients.client.keys(this.redisPrefix + '*', function (err, keys) {
        next(err, keys);
      });
    }
 
    /**
     * Get the total number of cached items.
     *
     * @param next  Callback.
     */
 
  }, {
    key: 'size',
    value: function size(next) {
      var self = this;
 
      // get all cached keys
      self.keys(function (err, keys) {
        var length = 0;
 
        // get the keys length if present
        Eif (keys) {
          length = keys.length;
        }
 
        next(err, length);
      });
    }
 
    /**
     * Remove all cached items.
     *
     * @param next  Callback.
     */
 
  }, {
    key: 'clear',
    value: function clear(callback) {
      var self = this;
 
      // get all cached keys
      self.keys(function (err, keys) {
        Iif (err && typeof callback === 'function') {
          return callback(error);
        }
 
        // array with the jobs to be done
        var jobs = [];
 
        // iterate all keys and push a new jobs for the array
        keys.forEach(function (key) {
          return jobs.push(function (done) {
            return self.api.redis.clients.client.del(key, done);
          });
        });
 
        // execute all the jobs, this can be done in parallel
        _async2.default.parallel(jobs, function (error) {
          Eif (typeof callback === 'function') {
            return callback(error);
          }
        });
      });
    }
 
    /**
     * Save a new cache entry.
     *
     * @param key           Key to be saved.
     * @param value         Value to associate with the key.
     * @param expireTimeMS  Expire time in milliseconds.
     * @param callback      Callback function.
     */
 
  }, {
    key: 'save',
    value: function save(key, value, expireTimeMS, callback) {
      var self = this;
 
      if (typeof expireTimeMS === 'function' && typeof callback === 'undefined') {
        callback = expireTimeMS;
        expireTimeMS = null;
      }
 
      var expireTimeSeconds = null;
      var expireTimestamp = null;
 
      // if expireTimeMS is different than null we calculate the expire time in seconds
      // and the expire timestamp
      if (expireTimeMS !== null) {
        expireTimeSeconds = Math.ceil(expireTimeMS / 1000);
        expireTimestamp = new Date().getTime() + expireTimeMS;
      }
 
      // build the cache object
      var cacheObj = {
        value: value,
        expireTimestamp: expireTimestamp,
        createdAt: new Date().getTime(),
        readAt: null
      };
 
      // check if the key are locked
      self.checkLock(key, null, function (error, lockOk) {
        if (error || lockOk !== true) {
          Eif (typeof callback === 'function') {
            callback(new Error('Object locked'));
          }
        } else {
          (function () {
            // save the new key and value
            var keyToSave = self.redisPrefix + key;
            self.api.redis.clients.client.set(keyToSave, JSON.stringify(cacheObj), function (err) {
              // if the new cache entry has been saved define the expire date if needed
              if (err === null && expireTimeSeconds) {
                self.api.redis.clients.client.expire(keyToSave, expireTimeSeconds);
              }
 
              // execute the callback
              Eif (typeof callback === 'function') {
                process.nextTick(function () {
                  callback(err, true);
                });
              }
            });
          })();
        }
      });
    }
 
    /**
     * Get a cache entry by their key.
     *
     * @param key       Key to search.
     * @param options   Call options.
     * @param next      Callback function.
     */
 
  }, {
    key: 'load',
    value: function load(key, options, next) {
      var self = this;
 
      if (typeof options === 'function') {
        next = options;
        options = {};
      }
 
      // get the cache entry from redis server
      self.api.redis.clients.client.get(self.redisPrefix + key, function (err, cacheObj) {
        // log the error if exists
        Iif (err) {
          self.api.log(err, 'error');
        }
 
        // try parse the redis response
        try {
          cacheObj = JSON.parse(cacheObj);
        } catch (e) {}
 
        // check if the object exist
        if (!cacheObj) {
          Eif (typeof next === 'function') {
            process.nextTick(function () {
              next(new Error('Object not found'), null, null, null, null);
            });
          }
        } else if (cacheObj.expireTimestamp >= new Date().getTime() || cacheObj.expireTimestamp === null) {
          (function () {
            var lastReadAt = cacheObj.readAt;
            var expireTimeSeconds = void 0;
 
            // update the readAt property
            cacheObj.readAt = new Date().getTime();
 
            if (cacheObj.expireTimestamp) {
              // define the new expire time if requested
              if (options.expireTimeMS) {
                cacheObj.expireTimestamp = new Date().getTime() + options.expireTimeMS;
                expireTimeSeconds = Math.ceil(options.expireTimeMS / 1000);
              } else {
                expireTimeSeconds = Math.floor((cacheObj.expireTimestamp - new Date().getTime()) / 1000);
              }
            }
 
            // check the cache entry lock
            self.checkLock(key, options.retry, function (err, lockOk) {
              Iif (err || lockOk !== true) {
                if (typeof next === 'function') {
                  next(new Error('Object locked'));
                }
              } else {
                self.api.redis.clients.client.set(self.redisPrefix + key, JSON.stringify(cacheObj), function (err) {
                  if (typeof expireTimeSeconds === 'number') {
                    self.api.redis.clients.client.expire(self.redisPrefix + key, expireTimeSeconds);
                  }
                  Eif (typeof next === 'function') {
                    process.nextTick(function () {
                      next(err, cacheObj.value, cacheObj.expireTimestamp, cacheObj.createdAt, lastReadAt);
                    });
                  }
                });
              }
            });
          })();
        } else {
          Eif (typeof next === 'function') {
            process.nextTick(function () {
              next(new Error('Object expired'), null, null, null, null);
            });
          }
        }
      });
    }
 
    /**
     * Destroy a cache entry.
     *
     * @param key   Key to destroy.
     * @param next  Callback.
     */
 
  }, {
    key: 'destroy',
    value: function destroy(key, next) {
      var self = this;
 
      // check cache entry lock
      self.checkLock(key, null, function (err, lockOk) {
        if (err || lockOk !== true) {
          Eif (typeof next === 'function') {
            next(new Error('Object locked'));
          }
        } else {
          self.api.redis.clients.client.del(self.redisPrefix + key, function (err, count) {
            Iif (err) {
              self.api.log(err, 'error');
            }
            var resp = true;
            if (count !== 1) {
              resp = false;
            }
            Eif (typeof next === 'function') {
              next(null, resp);
            }
          });
        }
      });
    }
 
    // ------------------------------------------------------------------------------------------------------------ [Lock]
 
    /**
     * Get all existing locks.
     *
     * @param next Callback function.
     */
 
  }, {
    key: 'locks',
    value: function locks(next) {
      var self = this;
      self.api.redis.clients.client.keys(this.lockPrefix + '*', function (err, keys) {
        next(err, keys);
      });
    }
 
    /**
     * Lock a cache entry.
     *
     * @param key           Key to lock.
     * @param expireTimeMS  Expire time (optional)
     * @param callback      Callback function.
     */
 
  }, {
    key: 'lock',
    value: function lock(key, expireTimeMS, callback) {
      var self = this;
 
      // if the expireTimeMS is a function that means the developer don't set a expire time
      Iif (typeof expireTimeMS === 'function' && callback === null) {
        callback = expireTimeMS;
        expireTimeMS = null;
      }
 
      // assign the default expire time if the expireTimeMS is equals to null
      if (expireTimeMS === null) {
        expireTimeMS = self.lockDuration;
      }
 
      // check the lock state
      self.checkLock(key, null, function (error, lock) {
        // if there is an error or the lock already exists
        Iif (error || lock !== true) {
          return callback(error, false);
        }
 
        // create a new lock
        var lockKey = self.lockPrefix + key;
        self.api.redis.clients.client.setnx(lockKey, self.lockName, function (error) {
          // return the error if exists
          Iif (error) {
            return callback(error);
          }
 
          // set an expire date for the lock
          self.api.redis.clients.client.expire(lockKey, Math.ceil(expireTimeMS / 1000), function (error) {
            lock = !error;
            return callback(error, lock);
          });
        });
      });
    }
 
    /**
     * Unlock a cache entry.
     *
     * @param key       Key to unlock.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'unlock',
    value: function unlock(key, callback) {
      var self = this;
 
      // check the lock state, if already unlocked returns.
      self.checkLock(key, null, function (error, lock) {
        Iif (error || lock !== true) {
          return callback(error, false);
        }
 
        // remove the lock
        self.api.redis.clients.client.del(self.lockPrefix + key, function (error) {
          lock = true;
          Iif (error) {
            lock = false;
          }
          return callback(error, lock);
        });
      });
    }
 
    /**
     * Check if a cache entry is locked.
     *
     * @param key       Key to check.
     * @param retry     If defined keep retrying until the lock is free to be re-obtained.
     * @param callback      Callback function.
     * @param startTime This should not be used by the user.
     */
 
  }, {
    key: 'checkLock',
    value: function checkLock(key, retry, callback, startTime) {
      var self = this;
 
      // if the start time are not defined use the current timestamp
      Iif (startTime === null) {
        startTime = new Date().getTime();
      }
 
      // get the cache entry
      self.api.redis.clients.client.get(self.lockPrefix + key, function (error, lockedBy) {
        Iif (error) {
          return callback(error, false);
        } else if (lockedBy === self.lockName || lockedBy === null) {
          return callback(null, true);
        } else {
          // calculate the time variation between the request and the response
          var delta = new Date().getTime() - startTime;
 
          Eif (retry === null || retry === false || delta > retry) {
            return callback(null, false);
          }
 
          return setTimeout(function () {
            self.checkLock(key, retry, callback, startTime);
          }, self.lockRetry);
        }
      });
    }
 
    // ------------------------------------------------------------------------------------------------------------ [List]
 
    /**
     * Push a new object to a list.
     *
     * @param key       List key.
     * @param item      Item to cache.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'push',
    value: function push(key, item, callback) {
      var self = this;
 
      // stringify the data to save
      var object = JSON.stringify({ data: item });
 
      // push the new item to Redis
      self.api.redis.clients.client.rpush(self.redisPrefix + key, object, function (error) {
        Eif (typeof callback === 'function') {
          callback(error);
        }
      });
    }
 
    /**
     * Pop a value from a list.
     *
     * If the key not exists a null value will be returned.
     *
     * @param key       Key to search for.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'pop',
    value: function pop(key, callback) {
      var self = this;
 
      // pop the item from Redis
      self.api.redis.clients.client.lpop(self.redisPrefix + key, function (error, object) {
        // check if an error occurred during the request
        Iif (error) {
          return callback(error);
        }
 
        // if the object not exist return null
        if (!object) {
          return callback();
        }
 
        // try parse the item and return it
        var item = null;
 
        try {
          item = JSON.parse(object);
        } catch (e) {
          return callback(error);
        }
 
        // return the parsed object
        return callback(null, item.data);
      });
    }
 
    /**
     * Get the length of the list.
     *
     * @param key       Key to search for.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'listLength',
    value: function listLength(key, callback) {
      var self = this;
 
      // request the list's length to Redis
      self.api.redis.clients.client.llen(self.redisPrefix + key, callback);
    }
  }]);
 
  return CacheManager;
}();
 
/**
 * Cache initializer.
 */
 
 
var _class = function () {
  function _class() {
    _classCallCheck(this, _class);
 
    this.loadPriority = 300;
  }
 
  /**
   * Initializer load priority
   *
   * @type {number}
   */
 
 
  _createClass(_class, [{
    key: 'load',
 
 
    /**
     * Initializer load method.
     *
     * @param api
     * @param next
     */
    value: function load(api, next) {
      // put cache manager available to all API
      api.cache = new CacheManager(api);
 
      // finish the initializer loading
      next();
    }
  }]);
 
  return _class;
}();
 
exports.default = _class;
//# sourceMappingURL=cache.js.map