Mosca lib/persistence/redis.js

    Description

    Copyright (c) 2013-2014 Matteo Collina, http://matteocollina.com

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.

    Source

    "use strict";
    
    var AbstractPersistence = require("./abstract");
    var redis = require("redis");
    var util = require("util");
    var Matcher = require("./matcher");
    var async = require("async");
    var extend = require("extend");
    var shortid = require("shortid");
    var defaults = {
      channel: "$SYS/moscaSync",
      ttl: {
        // TTL for subscriptions is 1 hour
        subscriptions: 60 * 60 * 1000,
    
        // TTL for packets is 1 hour
        packets: 60 * 60 * 1000,
    
        // the checkFrequency is 1 minute
        checkFrequency: 60 * 1000
      }
    };

    RedisPersistence

    function
    RedisPersistence()
    • @param: {Object}optionsThe options to create this persistance
    • @param: {Function}callback

    Description

    A Redis-based persistance.

    The current options include:
    - port, the Redis' port.
    - host, the Redis' host.
    - db, the Redis' database.
    - password, the Redis' password.
    - redisOpts, the options for the Redis client.
    - channel, the pub/sub channel that will be used to synchronize
    the various clients. Defaults to 'moscaSync'.
    - ttl, an object containing three values:
    * subscriptions, the time (ms) after which subscriptions
    will expire. It defaults to 1 hour.
    * packets, the time (ms) after which packets will expire.

    Source

    function RedisPersistence(options, callback) {
      if (!(this instanceof RedisPersistence)) {
        return new RedisPersistence(options, callback);
      }
    
      this.options = extend(true, {}, defaults, options);
    
      this._subMatcher = new Matcher();
    
      this._client = this._buildClient();
      this._pubSubClient = this._buildClient();
      this._id = shortid.generate();
    
      this._packetKeyTTL = this.options.ttl.packets;
      this._listKeyTTL = this._packetKeyTTL * 2; // list key should live longer than packet key
    
      var newSub = function(key, cb, retried) {
        that._client.get(key, function(err, result) {
          if (err) {
            if (cb) {
              cb(err);
            } else {
              return;
            }
          }
    
          var id = key.split(":")[2];
          var subs = JSON.parse(result);
    
          if (!result || typeof subs !== 'object') {
            if (!retried) {
              setTimeout(newSub.bind(null, key, cb, true), 500);
            }
            return;
          }
    
          Object.keys(subs).forEach(function(sub) {
            that._subMatcher.add(sub, id);
          });
    
          var redisError = null;
          var redisVersions = that._client.server_info.versions;
          if ( (redisVersions[0] * 1000 + redisVersions[1]) < 2006 ) {
            redisError = 'redis instance version should be no less than 2.6';
          }
    
          if (cb) {
            cb(redisError);
          } else {
            if (redisError) {
              throw redisError;
            }
          }
        });
      };
    
      var that = this;
    
      this._pubSubClient.subscribe(this.options.channel);
      this._pubSubClient.on("message", function(channel, message) {
        var parsed = JSON.parse(message);
        if (parsed.process !== that._id) {
          newSub(parsed.key);
        }
      });
    
      this._pubSubClient.on("subscribe", function() {
        that._client.keys("client:sub:*", function(err, keys) {
          async.each(keys, newSub, function(err) {
            if (callback) {
              callback(err, that);
            }
          });
        });
      });
    }
    
    util.inherits(RedisPersistence, AbstractPersistence);

    exports

    property
    module.exports

      Description

      Export it as a module

      Source

      module.exports = RedisPersistence;