Code coverage report for osc/Server.js

Statements: 92.78% (90 / 97)      Branches: 91.11% (41 / 45)      Functions: 100% (12 / 12)      Lines: 98.85% (86 / 87)      Ignored: none     

All files » osc/ » Server.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 215 216 217 218 219 220 221 222 223                                    1                       1 20 20 20 20 20 20     1         25 5 5 5 20         22 9   9 9 9 9 9         13 2 2   2 1   11       11 11 11 1 1     11         4 4         1 5 5 5 5     1         14 14 12     12 12 12                 12 12 12   12               12 4 4               13 12     12   12 12 12 12 12 12 12   1         14 13     14 12                 33     33 26           26 3         23 1       22 16 16 16   6       7 7 7               26 20        
/*
 * 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 _ = require('underscore')
  , async = require('async')
  , debug = require('debug')('rhizome.server.osc')
  , expect = require('chai').expect
  , coreMessages = require('../core/messages')
  , coreServer = require('../core/server')
  , coreValidation = require('../core/validation')
  , connections = require('../connections')
  , transport = require('./transport')
 
 
// Class to handle connections from OSC clients. 
var OSCConnection = function(args) {
  coreServer.Connection.call(this, args)
  this.ip = args[0]
  this.appPort = args[1]
  this.id = this.ip + ':' + this.appPort
  this.appClient = transport.createClient(this.ip, this.appPort, 'udp')
  this.appClient.on('error', (err) => this.emit('error', err))
}
 
_.extend(OSCConnection.prototype, coreServer.Connection.prototype, {
  
  namespace: 'osc',
 
  send: function(address, args) {
    if (this.blobClient && args.some((arg) => arg instanceof Buffer)) {
      debug(this.toString() + ' sending to blob client ' + address + ' ' + coreMessages.argsToString(args))
      args = [this.appPort].concat(args)
      this.blobClient.send(address, args)
    } else this.appClient.send(address, args)
  },
 
  onSysMessage: function(address, args) {
    // Change configuration of the client
    if (address === coreMessages.configureAddress) {
      var param = args[0]
 
      Eif (param === 'blobClient') {
        var blobsPort = args[1] || 44444
        this.setBlobClient(blobsPort)
        this.appClient.send(coreMessages.configuredAddress, [blobsPort])
        this.save()
      }
 
    // Receives the request to send a blob, first checks the address,
    // and then asks the blob client to send the requested blob
    } else if (this.blobClient && address === coreMessages.sendBlobAddress) {
      debug(this.toString() + ' asking blob client to send ' + coreMessages.argsToString(args))
      var originalAddress = args[0]
        , err = coreMessages.validateAddressForSend(originalAddress)
      if (err) this.appClient.send(coreMessages.errorAddress, [err])
      else this.blobClient.send(coreMessages.sendBlobAddress, args)
 
    } else coreServer.Connection.prototype.onSysMessage.apply(this, arguments)
  },
 
  setBlobClient: function(blobsPort) {
    this.infos.blobsPort = blobsPort
    this.blobClient = transport.createClient(this.ip, blobsPort, 'tcp')
    this.blobClient.on('error', (err) => {
      Eif (err.code === 'ECONNREFUSED')
        this.emit('error', new Error('blob client refused connection'))
      else this.emit('error', err)
    })
    debug(this.toString() + ' configured blob client to port ' + blobsPort)
  },
 
  // When deserializing the persisted connection, we need to restore blob client
  deserialize: function(data) {
    coreServer.Connection.prototype.deserialize.apply(this, arguments)
    if (this.infos.blobsPort) this.setBlobClient(this.infos.blobsPort)
  }
})
 
 
var OSCServer = module.exports = function(config) {
  coreServer.Server.call(this, config)
  this._server = null
  this._blobsServer = null
  this._config = config
}
 
_.extend(OSCServer.prototype, coreValidation.ValidateConfigMixin, coreServer.Server.prototype, {
 
  ConnectionClass: OSCConnection,
 
  start: function(done) {
    this.validateConfig((err) => {
      if (err) return done(err)
      coreServer.Server.prototype.start.apply(this)
 
      // This is the OSC server that receives normal messages
      this._server = transport.createServer(this._config.port, 'udp')
      this._server.on('message', this._onMessage.bind(this))
      this._server.on('error', (err) => this.emit('error', err))
 
      // This is the server on which we receive the blobs sent by the blob client.
      // When an app client wants to send a blob, it sends a message to the server, which then asks the
      // blob client to actually send the blob. That way the user never deals directly with the blob client :
      //    APP                this._server                     BLOB-CLIENT                  this._blobsServer
      //    sendBlobAddress ->
      //                    sendBlobAddress ->
      //                                           /some/address <blob>, <arg1>, <arg2>, ->
      this._blobsServer = transport.createServer(this._config.blobsPort, 'tcp')
      this._blobsServer.on('message', (address, args, rinfo) => connections.manager.send(address, args))
      this._blobsServer.on('error', (err) => this.emit('error', err))
 
      async.waterfall([
        this._server.start.bind(this._server),
        this._blobsServer.start.bind(this._blobsServer),
        connections.manager.listPersisted.bind(connections.manager, OSCConnection.prototype.namespace),
 
        // Immediately re-open OSC connections that were persisted. 
        // We need to do that because UDP OSC clients will not try to reconnect.
        (ids, next) => {
          async.each(ids, (id, nextId) => {
            var parts = id.split(':')
            this.openConnection([parts[0], parseInt(parts[1], 10)], nextId)
          }, next)
        }
      ], done)
    })
  },
 
  stop: function(done) {
    if (this._server) {
      async.series([
        this._server.stop.bind(this._server),
        this._blobsServer.stop.bind(this._blobsServer),
        (next) => coreServer.Server.prototype.stop.call(this, next)
      ], (err) => {
        this._server.removeAllListeners()
        this._blobsServer && this._blobsServer.removeAllListeners()
        this._server.on('error', () => {})
        this._blobsServer && this._blobsServer.on('error', () => {})
        this._server = null
        this._blobsServer = null
        done(err)
      })
    } else done()
  },
 
  configValidator: new coreValidation.ChaiValidator({
    blobsPort: function(val) {
      expect(val).to.be.a('number')
      expect(val).to.be.within(0, 65535)
    },
    port: function(val) {
      expect(val).to.be.a('number')
      expect(val).to.be.within(0, 65535)
    }
  }),
 
  configDefaults: {
    blobsPort: 44445
  },
 
  _onMessage: function (address, args, rinfo) {
    debug('message ' + address)
 
    // System messages should always have the appPort as first argument.
    if (coreMessages.sysAddressRe.exec(address)) {
      var appPort = args[0]
        , args = args.slice(1)
        , ip = rinfo.address
        , connection = this._findConnection(ip, appPort)
 
      // Quick port validation
      if (!_.isNumber(appPort) || appPort <= 0 || appPort >= 65536)
        return this.emit('error', new Error('Wrong sys message : "' + args + '" invalid port ' + appPort))
      // !!! We forbid to use the same port as rhizome server for osc clients. 
      // There is no problem when client is on a different machine, but if server and client
      // run on the same machine, the server will essentially send bogus messages to itself
      // and this will potentially lead to crashes that are hard to understand.
      if (appPort === this._config.port)
        return this.emit('error', new Error('Please keep port ' + appPort + ' reserved for the rhizome server'))
 
      // If connection doesn't exist, create it, open it and sends the sys message
      // once connection is open
      if (!connection) {
        this.openConnection([ip, appPort], (err, connection) => {
          Iif (err) return this.emit('error', err)
          connection.onSysMessage(address, args, rinfo)
        })
      } else connection.onSysMessage(address, args, rinfo)
 
    // If normal message, we traverse the namespaces from / to `address` and send to all sockets
    } else {
      var err = coreMessages.validateAddressForSend(address)
      Iif (err) debug('invalid address : ' + address + '(' + err + ')')
      else connections.manager.send(address, args)
    }
  },
 
  // Debug function for OSCServer
  debug: debug,
 
  _findConnection: function(ip, appPort) {
    return _.find(this.connections, (connection) => {
      return connection.ip === ip && connection.appPort === appPort
    })
  }
 
})