@brimble/consul 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -0
- package/README.md +2423 -0
- package/lib/acl/legacy.d.ts +75 -0
- package/lib/acl/legacy.js +167 -0
- package/lib/acl.d.ts +37 -0
- package/lib/acl.js +49 -0
- package/lib/agent/check.d.ts +113 -0
- package/lib/agent/check.js +164 -0
- package/lib/agent/service.d.ts +63 -0
- package/lib/agent/service.js +113 -0
- package/lib/agent.d.ts +77 -0
- package/lib/agent.js +162 -0
- package/lib/catalog/connect.d.ts +11 -0
- package/lib/catalog/connect.js +37 -0
- package/lib/catalog/node.d.ts +30 -0
- package/lib/catalog/node.js +57 -0
- package/lib/catalog/service.d.ts +32 -0
- package/lib/catalog/service.js +61 -0
- package/lib/catalog.d.ts +118 -0
- package/lib/catalog.js +113 -0
- package/lib/constants.js +21 -0
- package/lib/consul.d.ts +93 -0
- package/lib/consul.js +98 -0
- package/lib/errors.js +29 -0
- package/lib/event.d.ts +43 -0
- package/lib/event.js +91 -0
- package/lib/health.d.ts +77 -0
- package/lib/health.js +126 -0
- package/lib/index.d.ts +18 -0
- package/lib/index.js +3 -0
- package/lib/intention.d.ts +73 -0
- package/lib/intention.js +180 -0
- package/lib/kv.d.ts +80 -0
- package/lib/kv.js +180 -0
- package/lib/query.d.ts +84 -0
- package/lib/query.js +244 -0
- package/lib/resolver/algorithms.js +127 -0
- package/lib/resolver/dns.js +182 -0
- package/lib/resolver/health.js +51 -0
- package/lib/resolver/metrics.js +199 -0
- package/lib/resolver/scoring.js +95 -0
- package/lib/resolver/types.js +28 -0
- package/lib/resolver.d.ts +76 -0
- package/lib/resolver.js +290 -0
- package/lib/session.d.ts +92 -0
- package/lib/session.js +164 -0
- package/lib/status.d.ts +19 -0
- package/lib/status.js +43 -0
- package/lib/transaction.d.ts +50 -0
- package/lib/transaction.js +58 -0
- package/lib/utils.js +655 -0
- package/lib/watch.d.ts +22 -0
- package/lib/watch.js +183 -0
- package/package.json +55 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { log } = require("@brimble/utils");
|
|
4
|
+
|
|
5
|
+
class MetricsManager {
|
|
6
|
+
constructor(redis, cachePrefix, metrics, cacheEnabled, debug) {
|
|
7
|
+
this.redis = redis;
|
|
8
|
+
this.cachePrefix = cachePrefix;
|
|
9
|
+
this.metrics = metrics;
|
|
10
|
+
this.cacheEnabled = cacheEnabled;
|
|
11
|
+
this.debug = debug;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
getConnectionKey(serviceId) {
|
|
15
|
+
return `${this.cachePrefix}:connections:${serviceId}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async getServicesMetrics(services) {
|
|
19
|
+
const metricsMap = new Map();
|
|
20
|
+
const pipeline = this.redis?.pipeline();
|
|
21
|
+
|
|
22
|
+
if (this.cacheEnabled) {
|
|
23
|
+
services.forEach((service) => {
|
|
24
|
+
pipeline?.get(service.Service.ID);
|
|
25
|
+
pipeline?.get(this.getConnectionKey(service.Service.ID));
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const results = await pipeline?.exec();
|
|
31
|
+
if (!results) {
|
|
32
|
+
services.forEach((service) => {
|
|
33
|
+
metricsMap.set(service.Service.ID, { ...this.metrics });
|
|
34
|
+
});
|
|
35
|
+
return metricsMap;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
services.forEach((service, index) => {
|
|
39
|
+
const serviceId = service.Service.ID;
|
|
40
|
+
const metricsResult = results[index * 2];
|
|
41
|
+
const connectionsResult = results[index * 2 + 1];
|
|
42
|
+
|
|
43
|
+
let metrics;
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
if (metricsResult?.[1]) {
|
|
47
|
+
metrics = JSON.parse(metricsResult[1]);
|
|
48
|
+
} else {
|
|
49
|
+
metrics = { ...this.metrics };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (connectionsResult?.[1]) {
|
|
53
|
+
const connData = JSON.parse(connectionsResult[1]);
|
|
54
|
+
metrics.activeConnections = connData.activeConnections || 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
metricsMap.set(serviceId, metrics);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (this.debug) {
|
|
60
|
+
log.error(
|
|
61
|
+
`Error processing metrics for service ${serviceId}:`,
|
|
62
|
+
error,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
metricsMap.set(serviceId, { ...this.metrics });
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (this.debug) {
|
|
70
|
+
log.error("Error executing Redis pipeline:", error);
|
|
71
|
+
}
|
|
72
|
+
services.forEach((service) => {
|
|
73
|
+
metricsMap.set(service.Service.ID, { ...this.metrics });
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return metricsMap;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async incrementConnections(serviceId) {
|
|
81
|
+
try {
|
|
82
|
+
const connectionKey = this.getConnectionKey(serviceId);
|
|
83
|
+
const existingMetrics = await this.redis?.get(connectionKey);
|
|
84
|
+
let metrics;
|
|
85
|
+
|
|
86
|
+
if (existingMetrics) {
|
|
87
|
+
metrics = JSON.parse(existingMetrics);
|
|
88
|
+
metrics.activeConnections = (metrics.activeConnections || 0) + 1;
|
|
89
|
+
} else {
|
|
90
|
+
metrics = {
|
|
91
|
+
...this.metrics,
|
|
92
|
+
activeConnections: 1,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (this.cacheEnabled) {
|
|
97
|
+
await this.redis?.set(
|
|
98
|
+
connectionKey,
|
|
99
|
+
JSON.stringify(metrics),
|
|
100
|
+
"EX",
|
|
101
|
+
24 * 60 * 60,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (this.debug) {
|
|
106
|
+
log.error(
|
|
107
|
+
`Failed to increment connections for service ${serviceId}:`,
|
|
108
|
+
error,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async decrementConnections(serviceId) {
|
|
115
|
+
try {
|
|
116
|
+
const connectionKey = this.getConnectionKey(serviceId);
|
|
117
|
+
const existingMetrics = await this.redis?.get(connectionKey);
|
|
118
|
+
let metrics;
|
|
119
|
+
|
|
120
|
+
if (existingMetrics) {
|
|
121
|
+
metrics = JSON.parse(existingMetrics);
|
|
122
|
+
metrics.activeConnections = Math.max(
|
|
123
|
+
0,
|
|
124
|
+
(metrics.activeConnections || 1) - 1,
|
|
125
|
+
);
|
|
126
|
+
} else {
|
|
127
|
+
metrics = {
|
|
128
|
+
...this.metrics,
|
|
129
|
+
activeConnections: 0,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (this.cacheEnabled) {
|
|
134
|
+
await this.redis?.set(
|
|
135
|
+
connectionKey,
|
|
136
|
+
JSON.stringify(metrics),
|
|
137
|
+
"EX",
|
|
138
|
+
24 * 60 * 60,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (this.debug) {
|
|
143
|
+
log.error(
|
|
144
|
+
`Failed to decrement connections for service ${serviceId}:`,
|
|
145
|
+
error,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async updateSelectionMetrics(serviceId) {
|
|
152
|
+
try {
|
|
153
|
+
const connectionKey = this.getConnectionKey(serviceId);
|
|
154
|
+
const existingMetrics = await this.redis?.get(connectionKey);
|
|
155
|
+
let metrics;
|
|
156
|
+
|
|
157
|
+
if (existingMetrics) {
|
|
158
|
+
metrics = JSON.parse(existingMetrics);
|
|
159
|
+
} else {
|
|
160
|
+
metrics = { ...this.metrics };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
metrics.lastSelectedTime = Date.now();
|
|
164
|
+
|
|
165
|
+
if (this.cacheEnabled) {
|
|
166
|
+
await this.redis?.set(
|
|
167
|
+
connectionKey,
|
|
168
|
+
JSON.stringify(metrics),
|
|
169
|
+
"EX",
|
|
170
|
+
24 * 60 * 60,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (this.debug) {
|
|
175
|
+
log.error(
|
|
176
|
+
`Failed to update selection metrics for service ${serviceId}:`,
|
|
177
|
+
error,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async getSelectionMetrics(serviceId) {
|
|
184
|
+
try {
|
|
185
|
+
if (!this.cacheEnabled) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const metrics = await this.redis?.get(this.getConnectionKey(serviceId));
|
|
189
|
+
return metrics ? JSON.parse(metrics) : null;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (this.debug) {
|
|
192
|
+
log.error("Error getting service metrics:", error);
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
exports.MetricsManager = MetricsManager;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { DEFAULT_WEIGHTS } = require("./types");
|
|
4
|
+
|
|
5
|
+
function calculateHealthScore(service) {
|
|
6
|
+
const checks = service.Checks;
|
|
7
|
+
const totalChecks = checks.length;
|
|
8
|
+
if (totalChecks === 0) return 0;
|
|
9
|
+
|
|
10
|
+
const passingChecks = checks.filter(
|
|
11
|
+
(check) => check.Status === "passing",
|
|
12
|
+
).length;
|
|
13
|
+
return passingChecks / totalChecks;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function normalizeScore(value, max, inverse = false) {
|
|
17
|
+
const normalized = Math.max(0, Math.min(1, value / max));
|
|
18
|
+
return inverse ? 1 - normalized : normalized;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function calculateResourceScore(metrics) {
|
|
22
|
+
const cpuScore = normalizeScore(metrics.cpuUsage, 100, true);
|
|
23
|
+
const memoryScore = normalizeScore(metrics.memoryUsage, 100, true);
|
|
24
|
+
return (cpuScore + memoryScore) / 2;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function calculateDistributionScore(lastSelectedTime) {
|
|
28
|
+
if (!lastSelectedTime) return 1;
|
|
29
|
+
|
|
30
|
+
const timeSinceLastSelection = Date.now() - lastSelectedTime;
|
|
31
|
+
|
|
32
|
+
return Math.min(timeSinceLastSelection / (5 * 60 * 1000), 1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function rankServices(services, metrics, weights = DEFAULT_WEIGHTS) {
|
|
36
|
+
return services
|
|
37
|
+
.map((service) => {
|
|
38
|
+
const serviceId = service.Service.ID;
|
|
39
|
+
|
|
40
|
+
const serviceMetrics = metrics.get(serviceId);
|
|
41
|
+
|
|
42
|
+
if (!serviceMetrics) {
|
|
43
|
+
throw new Error(`No metrics found for service ${serviceId}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const healthScore = calculateHealthScore(service);
|
|
47
|
+
const responseTimeScore = normalizeScore(
|
|
48
|
+
serviceMetrics.responseTime,
|
|
49
|
+
500,
|
|
50
|
+
true,
|
|
51
|
+
);
|
|
52
|
+
const errorRateScore = normalizeScore(
|
|
53
|
+
serviceMetrics.errorRate,
|
|
54
|
+
100,
|
|
55
|
+
true,
|
|
56
|
+
);
|
|
57
|
+
const resourceScore = calculateResourceScore(serviceMetrics);
|
|
58
|
+
const connectionScore = normalizeScore(
|
|
59
|
+
serviceMetrics.activeConnections,
|
|
60
|
+
1000,
|
|
61
|
+
true,
|
|
62
|
+
);
|
|
63
|
+
const distributionScore = calculateDistributionScore(
|
|
64
|
+
serviceMetrics.lastSelectedTime,
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const totalScore =
|
|
68
|
+
healthScore * weights.health +
|
|
69
|
+
responseTimeScore * weights.responseTime +
|
|
70
|
+
errorRateScore * weights.errorRate +
|
|
71
|
+
resourceScore * weights.resources +
|
|
72
|
+
connectionScore * weights.connections +
|
|
73
|
+
distributionScore * weights.distribution;
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
score: totalScore,
|
|
77
|
+
id: serviceId,
|
|
78
|
+
service,
|
|
79
|
+
};
|
|
80
|
+
})
|
|
81
|
+
.sort((a, b) => b.score - a.score);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function combineHealthAndDNSWeights(service, dnsWeight, maxDNSWeight) {
|
|
85
|
+
const healthScore = calculateHealthScore(service);
|
|
86
|
+
const normalizedDNSWeight = dnsWeight / maxDNSWeight;
|
|
87
|
+
return healthScore * 0.7 + normalizedDNSWeight * 0.3;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
exports.calculateHealthScore = calculateHealthScore;
|
|
91
|
+
exports.calculateResourceScore = calculateResourceScore;
|
|
92
|
+
exports.calculateDistributionScore = calculateDistributionScore;
|
|
93
|
+
exports.normalizeScore = normalizeScore;
|
|
94
|
+
exports.rankServices = rankServices;
|
|
95
|
+
exports.combineHealthAndDNSWeights = combineHealthAndDNSWeights;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const DEFAULT_WEIGHTS = {
|
|
4
|
+
health: 0.25,
|
|
5
|
+
responseTime: 0.2,
|
|
6
|
+
errorRate: 0.2,
|
|
7
|
+
resources: 0.15,
|
|
8
|
+
connections: 0.1,
|
|
9
|
+
distribution: 0.1,
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
const DEFAULT_METRICS = {
|
|
13
|
+
responseTime: 100,
|
|
14
|
+
errorRate: 0,
|
|
15
|
+
cpuUsage: 50,
|
|
16
|
+
memoryUsage: 50,
|
|
17
|
+
activeConnections: 0,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const SelectionAlgorithm = {
|
|
21
|
+
RoundRobin: "round-robin",
|
|
22
|
+
LeastConnection: "least-connection",
|
|
23
|
+
WeightedRoundRobin: "weighted-round-robin",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
exports.DEFAULT_WEIGHTS = DEFAULT_WEIGHTS;
|
|
27
|
+
exports.DEFAULT_METRICS = DEFAULT_METRICS;
|
|
28
|
+
exports.SelectionAlgorithm = SelectionAlgorithm;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Agent as httpAgent } from "http";
|
|
2
|
+
import { Agent as httpsAgent } from "https";
|
|
3
|
+
import { Redis as IORedis } from "ioredis";
|
|
4
|
+
import { Consul } from "./consul";
|
|
5
|
+
|
|
6
|
+
export interface ConsulResolverConfig {
|
|
7
|
+
redis?: IORedis;
|
|
8
|
+
cacheEnabled: boolean;
|
|
9
|
+
cachePrefix: string;
|
|
10
|
+
debug?: boolean;
|
|
11
|
+
weights?: {
|
|
12
|
+
health: number;
|
|
13
|
+
responseTime: number;
|
|
14
|
+
errorRate: number;
|
|
15
|
+
resources: number;
|
|
16
|
+
connections: number;
|
|
17
|
+
distribution: number;
|
|
18
|
+
};
|
|
19
|
+
metrics?: {
|
|
20
|
+
responseTime: number;
|
|
21
|
+
errorRate: number;
|
|
22
|
+
cpuUsage: number;
|
|
23
|
+
memoryUsage: number;
|
|
24
|
+
activeConnections: number;
|
|
25
|
+
};
|
|
26
|
+
cacheTTL?: number;
|
|
27
|
+
dnsEndpoints?: string[];
|
|
28
|
+
dnsTimeout?: number;
|
|
29
|
+
dnsRetries?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ServiceInfo {
|
|
33
|
+
ip: string;
|
|
34
|
+
port: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface OptimalServiceResult {
|
|
38
|
+
selected: ServiceInfo | null;
|
|
39
|
+
services: ServiceInfo[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ServiceMetrics {
|
|
43
|
+
responseTime: number;
|
|
44
|
+
errorRate: number;
|
|
45
|
+
cpuUsage: number;
|
|
46
|
+
memoryUsage: number;
|
|
47
|
+
activeConnections: number;
|
|
48
|
+
lastSelectedTime?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export enum SelectionAlgorithm {
|
|
52
|
+
RoundRobin = "round-robin",
|
|
53
|
+
LeastConnection = "least-connection",
|
|
54
|
+
WeightedRoundRobin = "weighted-round-robin",
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
declare class Resolver {
|
|
58
|
+
constructor(consul: Consul, config: ConsulResolverConfig);
|
|
59
|
+
|
|
60
|
+
consul: Consul;
|
|
61
|
+
|
|
62
|
+
selectOptimalService(
|
|
63
|
+
service: string,
|
|
64
|
+
algorithm?: SelectionAlgorithm,
|
|
65
|
+
): Promise<OptimalServiceResult>;
|
|
66
|
+
|
|
67
|
+
incrementConnections(serviceId: string): Promise<void>;
|
|
68
|
+
|
|
69
|
+
decrementConnections(serviceId: string): Promise<void>;
|
|
70
|
+
|
|
71
|
+
getSelectionMetrics(serviceId: string): Promise<ServiceMetrics | null>;
|
|
72
|
+
|
|
73
|
+
refresh(): Promise<void>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { Resolver };
|
package/lib/resolver.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { log } = require("@brimble/utils");
|
|
4
|
+
const {
|
|
5
|
+
leastConnectionSelection,
|
|
6
|
+
roundRobinSelection,
|
|
7
|
+
weightedRandomSelection,
|
|
8
|
+
} = require("./resolver/algorithms");
|
|
9
|
+
const { DNSManager } = require("./resolver/dns");
|
|
10
|
+
const { HealthCheckManager } = require("./resolver/health");
|
|
11
|
+
const { MetricsManager } = require("./resolver/metrics");
|
|
12
|
+
const {
|
|
13
|
+
combineHealthAndDNSWeights,
|
|
14
|
+
rankServices,
|
|
15
|
+
} = require("./resolver/scoring");
|
|
16
|
+
const {
|
|
17
|
+
DEFAULT_METRICS,
|
|
18
|
+
DEFAULT_WEIGHTS,
|
|
19
|
+
SelectionAlgorithm,
|
|
20
|
+
} = require("./resolver/types");
|
|
21
|
+
|
|
22
|
+
class Resolver {
|
|
23
|
+
constructor(consul, config) {
|
|
24
|
+
this.consul = consul;
|
|
25
|
+
this.currentIndex = 0;
|
|
26
|
+
this.debug = config.debug || false;
|
|
27
|
+
this.cachePrefix = config.cachePrefix;
|
|
28
|
+
this.cacheEnabled = config.cacheEnabled;
|
|
29
|
+
this.weights = config.weights || DEFAULT_WEIGHTS;
|
|
30
|
+
this.metrics = config.metrics || DEFAULT_METRICS;
|
|
31
|
+
this.redis = config.redis;
|
|
32
|
+
|
|
33
|
+
this.cacheTTL = Math.floor((config.cacheTTL || 60 * 1000) / 1000);
|
|
34
|
+
|
|
35
|
+
if (this.cacheEnabled && config.redis) {
|
|
36
|
+
this.redis = config.redis;
|
|
37
|
+
this.cacheEnabled = true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
this.metricsManager = new MetricsManager(
|
|
41
|
+
this.redis,
|
|
42
|
+
this.cachePrefix,
|
|
43
|
+
this.metrics,
|
|
44
|
+
this.cacheEnabled,
|
|
45
|
+
this.debug,
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
this.dnsManager = new DNSManager(
|
|
49
|
+
this.redis,
|
|
50
|
+
this.cachePrefix,
|
|
51
|
+
this.cacheTTL,
|
|
52
|
+
this.cacheEnabled,
|
|
53
|
+
this.debug,
|
|
54
|
+
config.dnsEndpoints,
|
|
55
|
+
config.dnsTimeout,
|
|
56
|
+
config.dnsRetries,
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
this.healthCheckManager = new HealthCheckManager(
|
|
60
|
+
this.consul,
|
|
61
|
+
this.redis,
|
|
62
|
+
this.cachePrefix,
|
|
63
|
+
this.cacheTTL,
|
|
64
|
+
this.cacheEnabled,
|
|
65
|
+
this.debug,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Select the optimal service based on the specified algorithm
|
|
71
|
+
*/
|
|
72
|
+
async selectOptimalService(
|
|
73
|
+
service,
|
|
74
|
+
algorithm = SelectionAlgorithm.RoundRobin,
|
|
75
|
+
) {
|
|
76
|
+
try {
|
|
77
|
+
const [healthChecks, dnsRecords] = await Promise.all([
|
|
78
|
+
this.healthCheckManager.getHealthChecks(service),
|
|
79
|
+
this.dnsManager.resolveDNS(service),
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
if (
|
|
83
|
+
(!healthChecks || healthChecks.length === 0) &&
|
|
84
|
+
dnsRecords.length === 0
|
|
85
|
+
) {
|
|
86
|
+
return { selected: null, services: [] };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const sortedByPriority = this.dnsManager.sortByPriority(dnsRecords);
|
|
90
|
+
|
|
91
|
+
const lowestPriorityValue = sortedByPriority[0]?.priority;
|
|
92
|
+
const highestPriorityRecords = sortedByPriority.filter(
|
|
93
|
+
(record) => record.priority === lowestPriorityValue,
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
if (!healthChecks || healthChecks.length === 0) {
|
|
97
|
+
const { selected, nextIndex } = this.dnsManager.selectFromSrvRecords(
|
|
98
|
+
highestPriorityRecords,
|
|
99
|
+
algorithm,
|
|
100
|
+
this.currentIndex,
|
|
101
|
+
);
|
|
102
|
+
this.currentIndex = nextIndex;
|
|
103
|
+
|
|
104
|
+
if (!selected) {
|
|
105
|
+
return { selected: null, services: [] };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
await this.metricsManager.updateSelectionMetrics(selected.name);
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
selected: {
|
|
112
|
+
ip: selected.ip,
|
|
113
|
+
port: selected.port,
|
|
114
|
+
},
|
|
115
|
+
services: sortedByPriority.map((record) => ({
|
|
116
|
+
ip: record.ip,
|
|
117
|
+
port: record.port,
|
|
118
|
+
})),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const dnsWeights = new Map(
|
|
123
|
+
dnsRecords.map((record) => [
|
|
124
|
+
record.ip,
|
|
125
|
+
{
|
|
126
|
+
weight: record.weight,
|
|
127
|
+
port: record.port,
|
|
128
|
+
priority: record.priority,
|
|
129
|
+
},
|
|
130
|
+
]),
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
const matchedHealthChecks = healthChecks.filter((check) =>
|
|
134
|
+
dnsWeights.has(check.Service.Address),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
if (matchedHealthChecks.length === 0) {
|
|
138
|
+
if (this.debug) {
|
|
139
|
+
log.debug(
|
|
140
|
+
"No matching services found between DNS and Consul health checks",
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const { selected, nextIndex } = this.dnsManager.selectFromSrvRecords(
|
|
144
|
+
highestPriorityRecords,
|
|
145
|
+
algorithm,
|
|
146
|
+
this.currentIndex,
|
|
147
|
+
);
|
|
148
|
+
this.currentIndex = nextIndex;
|
|
149
|
+
|
|
150
|
+
if (!selected) {
|
|
151
|
+
return { selected: null, services: [] };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
await this.metricsManager.updateSelectionMetrics(selected.name);
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
selected: {
|
|
158
|
+
ip: selected.ip,
|
|
159
|
+
port: selected.port,
|
|
160
|
+
},
|
|
161
|
+
services: sortedByPriority.map((record) => ({
|
|
162
|
+
ip: record.ip,
|
|
163
|
+
port: record.port,
|
|
164
|
+
})),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const highPriorityIPs = new Set(
|
|
169
|
+
highestPriorityRecords.map((record) => record.ip),
|
|
170
|
+
);
|
|
171
|
+
const highPriorityHealthChecks = matchedHealthChecks.filter((check) =>
|
|
172
|
+
highPriorityIPs.has(check.Service.Address),
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const targetHealthChecks =
|
|
176
|
+
highPriorityHealthChecks.length > 0
|
|
177
|
+
? highPriorityHealthChecks
|
|
178
|
+
: matchedHealthChecks;
|
|
179
|
+
|
|
180
|
+
const maxDNSWeight = Math.max(...dnsRecords.map((r) => r.weight || 1));
|
|
181
|
+
|
|
182
|
+
const enhancedHealthChecks = targetHealthChecks.map((check) => ({
|
|
183
|
+
...check,
|
|
184
|
+
dnsWeight: combineHealthAndDNSWeights(
|
|
185
|
+
check,
|
|
186
|
+
dnsWeights.get(check.Service.Address)?.weight || 0,
|
|
187
|
+
maxDNSWeight,
|
|
188
|
+
),
|
|
189
|
+
}));
|
|
190
|
+
|
|
191
|
+
const metrics =
|
|
192
|
+
await this.metricsManager.getServicesMetrics(targetHealthChecks);
|
|
193
|
+
let selectedService;
|
|
194
|
+
|
|
195
|
+
switch (algorithm) {
|
|
196
|
+
case SelectionAlgorithm.RoundRobin: {
|
|
197
|
+
const rrResult = roundRobinSelection(
|
|
198
|
+
enhancedHealthChecks,
|
|
199
|
+
this.currentIndex,
|
|
200
|
+
);
|
|
201
|
+
this.currentIndex = rrResult.nextIndex;
|
|
202
|
+
selectedService = { id: rrResult.id, service: rrResult.service };
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
case SelectionAlgorithm.LeastConnection:
|
|
206
|
+
selectedService = leastConnectionSelection(
|
|
207
|
+
enhancedHealthChecks,
|
|
208
|
+
metrics,
|
|
209
|
+
this.metrics,
|
|
210
|
+
);
|
|
211
|
+
break;
|
|
212
|
+
case SelectionAlgorithm.WeightedRoundRobin: {
|
|
213
|
+
const rankedServices = rankServices(
|
|
214
|
+
enhancedHealthChecks,
|
|
215
|
+
metrics,
|
|
216
|
+
this.weights,
|
|
217
|
+
);
|
|
218
|
+
rankedServices.forEach((ranked) => {
|
|
219
|
+
const dnsInfo = dnsWeights.get(ranked.service.Service.Address);
|
|
220
|
+
if (dnsInfo) {
|
|
221
|
+
ranked.score *= 1 + dnsInfo.weight / maxDNSWeight;
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
selectedService = weightedRandomSelection(rankedServices);
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
await this.metricsManager.updateSelectionMetrics(selectedService.id);
|
|
230
|
+
|
|
231
|
+
const selectedDNSInfo = dnsWeights.get(
|
|
232
|
+
selectedService.service.Service.Address,
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
selected: {
|
|
237
|
+
ip: selectedService.service.Service.Address,
|
|
238
|
+
port: selectedDNSInfo?.port || selectedService.service.Service.Port,
|
|
239
|
+
},
|
|
240
|
+
services: matchedHealthChecks.map((check) => {
|
|
241
|
+
const dnsInfo = dnsWeights.get(check.Service.Address);
|
|
242
|
+
return {
|
|
243
|
+
ip: check.Service.Address,
|
|
244
|
+
port: dnsInfo?.port || check.Service.Port,
|
|
245
|
+
};
|
|
246
|
+
}),
|
|
247
|
+
};
|
|
248
|
+
} catch (error) {
|
|
249
|
+
if (this.debug) {
|
|
250
|
+
log.error("Error selecting optimal service:", error);
|
|
251
|
+
}
|
|
252
|
+
return { selected: null, services: [] };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async incrementConnections(serviceId) {
|
|
257
|
+
return this.metricsManager.incrementConnections(serviceId);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async decrementConnections(serviceId) {
|
|
261
|
+
return this.metricsManager.decrementConnections(serviceId);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async getSelectionMetrics(serviceId) {
|
|
265
|
+
return this.metricsManager.getSelectionMetrics(serviceId);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async refresh() {
|
|
269
|
+
try {
|
|
270
|
+
if (!this.cacheEnabled) {
|
|
271
|
+
if (this.debug) {
|
|
272
|
+
log.debug("Cache is disabled, no need to refresh");
|
|
273
|
+
}
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const pattern = `${this.cachePrefix}:*`;
|
|
277
|
+
const keys = await this.redis?.keys(pattern);
|
|
278
|
+
|
|
279
|
+
if (keys && keys.length > 0) {
|
|
280
|
+
await this.redis?.del(...keys);
|
|
281
|
+
}
|
|
282
|
+
} catch (error) {
|
|
283
|
+
console.log("Error refreshing Redis caches:", error);
|
|
284
|
+
throw new Error(`Failed to refresh caches: ${error.message}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
exports.Resolver = Resolver;
|
|
290
|
+
exports.SelectionAlgorithm = SelectionAlgorithm;
|