Code coverage report for connections/ConnectionManager.js

Statements: 90.32% (84 / 93)      Branches: 76.32% (29 / 38)      Functions: 100% (14 / 14)      Lines: 92.86% (78 / 84)      Ignored: none     

All files » connections/ » ConnectionManager.js
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                                    1                     1 52   52     52       52     52     1       74         73 73       73     74     73 73 1     73 132 132     73           70 70 436 436   70 70 70 70 70           116   116   116   116       116 116 116 116 116           85     85 598 85 85         239 239 239     239 239 893   239 239           58     58 58   55 55 53 53   55         8 8           5 5 4 1         4 8 6         33         12                     76 4 4 3 3     72 71       76        
/*
 * Copyright 2014-2016, Sébastien Piquemal <sebpiq@gmail.com>
 *
 * rhizome is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * rhizome is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with rhizome.  If not, see <http://www.gnu.org/licenses/>.
 */
"use strict";
 
var EventEmitter = require('events').EventEmitter
  , _ = require('underscore')
  , async = require('async')
  , debug = require('debug')('rhizome.server.connections')
  , expect = require('chai').expect
  , coreMessages = require('../core/messages')
  , coreUtils = require('../core/utils')
  , coreValidation = require('../core/validation')
  , persistence = require('./persistence')
 
 
var ConnectionManager = module.exports = function(config) {
  EventEmitter.apply(this)
 
  this._config = config
 
  // List of all the connections currently opened
  this._openConnections = []
 
  // This contains all the clients (OSC and websockets) which have subscribed to an address,
  // and therefore receive messages sent there.
  this._nsTree = coreUtils.createNsTree()
 
  // Handle for the queue interval 
  this._storeWriteInt = null
}
 
_.extend(ConnectionManager.prototype, EventEmitter.prototype, coreValidation.ValidateConfigMixin, {
 
  // Starts the connection manager, initializes the persistence layer, etc ...
  start: function(done) {
    async.series([
      this.validateConfig.bind(this),
 
      // Start store, and make sure we bubble-up its errors
      (next) => {
        this._config.store.on('error', (err) => this.emit('error', err))
        this._config.store.start(next)
      },
 
      // Restore previous state of the ConnectionManager
      (next) => this._config.store.managerRestore(next)
    
    ], (err, results) => {
      if (err) return done(err)
 
      // Restore saved state of the ConnectionManager
      var restoredManagerState = results.pop()
      if (restoredManagerState !== null)
        this._nsTree.fromJSON(restoredManagerState.nsTree)
 
      // Interval that will handle store operations by batches
      this._storeWriteInt = setInterval(() => {
        var managerState = { nsTree: this._nsTree.toJSON() }
        this._config.store.managerSave(managerState, (err) => { err && this.emit('error', err) })
      }, this._config.storeWriteTime)
 
      done()
    })
  },
 
  // Removes all the subscribed connections.
  stop: function(done) {
    this._openConnections = []
    this._nsTree.get('/').forEach((ns) => {
      ns.connections = []
      ns.lastMessage = null
    })
    clearInterval(this._storeWriteInt)
    this._storeWriteInt = null
    this._config.store.removeAllListeners()
    this._config.store.on('error', () => {})
    this._config.store.stop(done)
  },
 
  // Opens (and restore) a connection, takes care of persistence.
  // Connection is identified by `connection.id` and `connection.namespace`
  open: function(connection, done) {
    Iif (_.contains(this._openConnections, connection))
      return done(new Error('connection ' + connection + ' is already open'))
    Iif (!connection.namespace)
      return done(new Error('connection should define a namespace'))
    Iif (connection.id === null && connection.autoId !== true)
      return done(new Error('connection should have an id'))
    Iif (connection.id && !_.isString(connection.id))
      return done(new Error('connection ' + connection + ' unvalid id : ' + connection.id))
 
    // Try to retrieve the persisted connection, otherwise save a new connection with that id.
    this._config.store.connectionInsertOrRestore(connection, (err) => {
      Iif (err) return done(err)
      this._openConnections.push(connection)
      this.send(coreMessages.connectionOpenAddress + '/' + connection.namespace, [connection.id])
      done()
    })
  },
 
  // Removes all subscriptions from `connection`.
  close: function(connection, done) {
    Iif (!_.contains(this._openConnections, connection))
      return done(new Error('connection not open ' + connection))
 
    this._openConnections = _.without(this._openConnections, connection)
    this._nsTree.get('/').forEach((ns) => ns.connections = _.without(ns.connections, connection))
    this.send(coreMessages.connectionCloseAddress + '/' + connection.namespace, [connection.id])
    done()
  },
 
  // Sends a message to `address` with arguments `args`. Only connections subscribed to `address` will receive it.
  send: function(address, args) {
    address = coreMessages.normalizeAddress(address)
    var argsErr = coreMessages.validateArgs(args)
    Iif (argsErr) return this.emit('error', new Error(argsErr))
 
    // Send the message to all connections subscribed to a parent namespace
    debug('send ' + address + ' ' + coreMessages.argsToString(args))
    var ns = this._nsTree.get(address, (ns) => {
      ns.connections.forEach((connection) => connection.send(address, args))
    })
    ns.lastMessage = args
    return null
  },
 
  // Subscribes `connection` to all messages sent to `address`.
  // Returns `null` if all went well, an error message otherwise
  subscribe: function(connection, address) {
    Iif (!_.contains(this._openConnections, connection))
      return this.emit('error', new Error('connection not open ' + connection))
 
    var addrErr = coreMessages.validateAddressForSub(address)
    if (addrErr !== null) return addrErr
 
    var addrConnections = this._nsTree.get(address).connections
    if (addrConnections.indexOf(connection) === -1) {
      addrConnections.push(connection)
      debug(connection.toString() + ' subscribed to ' + address)
    }
    return null
  },
 
  // Returns `true` if `connection` is subscribed to `address`, `false` otherwise. 
  isSubscribed: function(connection, address) {
    var addrConnections = this._nsTree.get(address).connections
    return addrConnections.indexOf(connection) !== -1
  },
 
  // Returns the last message sent at `address`.
  // If no message at this address, returns `null`.
  getLastMessage: function(address) {
    address = coreMessages.normalizeAddress(address)
    if (this._nsTree.has(address))
      return this._nsTree.get(address).lastMessage || []
    else return null
  },
 
  // Returns the list of connections id for `namespace`
  getOpenConnectionsIds: function(namespace) {
    return this._openConnections
      .filter((connection) => connection.namespace === namespace)
      .map((connection) => connection.id)
  },
 
  // Updates a connection that has already been inserted in the store
  connectionUpdate: function(connection, done) {
    this._config.store.connectionUpdate(connection, done)
  },
 
  // List ids of connections from `namespace` that have been persisted in db.
  listPersisted: function(namespace, done) {
    this._config.store.connectionIdList(namespace, done)
  },
 
  configDefaults: {
    store: new persistence.NoStore(),
    storeWriteTime: 30000
  },
 
  configValidator: new coreValidation.ChaiValidator({
    // If `store` is a string, we take it as a path and use NEDBStore
    store: function(val, done) {
      if (_.isString(val)) {
        coreUtils.assertDirExists(val, (err) => {
          if (err) return done(err)
          this.store = new persistence.NEDBStore(val)
          done()
        })
      } else {
        expect(val).to.be.an('object')
        done()
      }
    },
    storeWriteTime: function(val) {
      expect(val).to.be.a('number')
    }
  })
 
})