-
Notifications
You must be signed in to change notification settings - Fork 1
/
consul-services.js
90 lines (74 loc) · 2.22 KB
/
consul-services.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
'use strict';
var fastparallel = require('fastparallel');
var consul = require('./consul-client.js')();
var simplifyService = require('./simplify-service.js');
var cws = require('./consul-watch-services.js');
var parallel = fastparallel();
var servicesCmprStr = '[]';
module.exports = function consulServices (config, cb) {
if (!expectedServices(config).length) return cb(null, {});
cws(function (err, data) {
if (err) return cb(err);
iterateServices(config, function (err, results) {
if (err) return cb(err);
finish(results, cb);
});
});
};
function iterateServices (config, cb) {
var services = expectedServices(config);
var environment = config.environment;
parallel({}, fetchService, services, cb);
function fetchService (service, done) {
consul.health.service({
service: service,
tag: environment,
passing: true
}, function (err, result) {
if (err) return cb(err);
done(null, simplify(result));
});
}
}
function simplify (services) {
return services.map(simplifyService);
}
function finish (result, cb) {
// We don't wan't to send a callback if nothing changed.
if (!hasChanged(result)) return;
servicesCmprStr = JSON.stringify(result);
delayChanged(mergeUnderName(result), cb);
}
var delayChangedTimer;
function delayChanged (services, cb) {
clearTimeout(delayChangedTimer);
delayChangedTimer = setTimeout(function () {
// console.log('[magistrate][consul-services] recived services:', services);
cb(null, services);
}, 200);
}
function mergeUnderName (services) {
var serviceByName = {};
services = [].concat.apply([], services); // flatten
services.forEach(storeByName);
return serviceByName;
function storeByName (service) {
if (!serviceByName[service.name]) {
serviceByName[service.name] = [];
}
serviceByName[service.name].push({
host: service.host,
port: service.port
});
}
}
function hasChanged (services) {
var newCmpr = JSON.stringify(services);
// console.log(servicesCmprStr + '\n' + newCmpr);
return servicesCmprStr !== newCmpr;
}
function expectedServices (config) {
var hard = config.services || [];
var loose = config.loose_services || [];
return hard.concat(loose);
}