-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
proxy.js
62 lines (54 loc) · 1.61 KB
/
proxy.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
'use strict' ;
var _ = require('lodash') ;
var Cluster = require('./cluster') ;
var cluster = new Cluster() ;
var config = require('./config') ;
var logger = require('../app').logger ;
var offset = 0 ;
/* add the initial set of Fsw servers to the cluster */
cluster.addServer(config.targets, config.localAddress) ;
/**
* rotate the list of targets so that we'll round robin the requests to them
* @param {Array} targets - Array of Fsw
* @return {Array} re-ordered array of Fsw to use for the current INVITE
*/
function shiftTargets( targets ) {
if( offset >= targets.length ) { offset = 0 ;}
if( targets.length <= 1) { return targets; }
for( var i = 0; i < offset; i++ ) {
var fsw = targets.shift() ;
targets.push( fsw ) ;
}
offset++ ;
return targets ;
}
/**
* proxy a request downstream
* @param {Request} req - drachtio Request object
* @param {Response} res - drachtio Response object
*/
function proxy( req, res ) {
var targets = shiftTargets( cluster.getOnlineServers() ) ;
if( 0 === targets.length ) {
logger.error('returning 480 as there are no online servers') ;
return res.send(480) ;
}
var dest = _.map( targets, function(t) { return t.sipAddress + ':' + (t.sipPort || 5060); }) ;
if( config.maxTargets ) {
dest = dest.slice(0,config.maxTargets) ;
}
req.proxy({
remainInDialog: false,
handleRedirects: true,
provisionalTimeout: '1s',
destination: dest
}, function(err) {
if( err ) {
logger.error('Error proxying request: ', err) ;
}
}) ;
}
exports = module.exports = function(srf) {
srf.invite( proxy ) ;
srf.register( proxy ) ;
} ;