-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroutes.js
94 lines (88 loc) · 2.66 KB
/
routes.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
module.exports=(function() {
'use strict';
var
Master = require('./lib/ssh_master'),
Route = require('./lib/route');
function merge(globalConf, pathDef) {
var allowed = {ignore:1, include:1, exclude:1};
return Array.prototype.reduce.call(arguments, function(obj, source) {
var i;
for (i in source) {
if (allowed.hasOwnProperty(i)) {
obj[i] = source[i];
}
}
return obj;
}, {});
}
return {
routes : [],
masters : {},
spawn : function spawn(config) {
if (!config.routes) { return; }
// config.routes can be in two formats
// Object of source : destination
// Array of { source: '', destination: '' }
var pathDefs = config.routes.length
? /* array */ config.routes
: /* object */ Object.keys(config.routes).map(function(source) {
return {source: source, destination: this[source]};
}, config.routes),
routes = this.routes,
masters = this.masters,
watchers = {};
// async loop
(function spawnNext() {
if (!pathDefs.length) { return; }
var pathDef = pathDefs.shift(),
host = pathDef.destination.split(':'),
master, route;
function makeRoute(socket) {
try {
route = new Route(
watchers[pathDef.source] ||
{path: pathDef.source, ignore: pathDef.ignore},
{path: pathDef.destination, socket: socket},
merge(config, pathDef)
);
routes.push(route);
watchers[pathDef.source] = route.watcher;
console.log('Listening to '+pathDef.source);
}
catch (readErr) {
console.error(readErr.toString());
}
spawnNext();
}
if (host.length > 1) {
// There's a hostname, try to use a master connection
if ((master = masters[host[0]]) != null) {
makeRoute(master.socket);
return;
}
// No existing master connection, try to make one
master = new Master( host[0] );
master.on('connection', makeRoute);
masters[host[0]] = master;
}
else {
// Just make the route
makeRoute();
}
}());
},
destroy : function() {
var i;
if (Object.keys(this.masters).length) {
for (i in this.masters) {
this.masters[i].destroy();
}
}
if (this.routes.length) {
this.routes.forEach(function(route) {
route.destroy();
});
}
}
};
}());