@vtex/api 6.51.3 → 6.52.0
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/CHANGELOG.md +25 -0
- package/lib/service/master.d.ts +2 -0
- package/lib/service/master.js +15 -3
- package/lib/service/metrics/clusterMetricsAggregator.d.ts +72 -0
- package/lib/service/metrics/clusterMetricsAggregator.js +181 -0
- package/lib/service/metrics/requestHandlerLabel.d.ts +26 -0
- package/lib/service/metrics/requestHandlerLabel.js +30 -0
- package/lib/service/metrics/requestMetricsMiddleware.js +5 -4
- package/lib/service/worker/index.d.ts +1 -0
- package/lib/service/worker/index.js +16 -4
- package/lib/service/worker/runtime/builtIn/middlewares.d.ts +1 -1
- package/lib/service/worker/runtime/builtIn/middlewares.js +7 -2
- package/lib/service/worker/runtime/statusTrack.js +4 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [6.52.0]
|
|
11
|
+
### Added
|
|
12
|
+
- Cluster-wide Prometheus `/metrics` aggregation. Each cluster worker keeps its own
|
|
13
|
+
prom-client registry, so serving `/metrics` from a single round-robin selected
|
|
14
|
+
worker exposed only that worker's counters; Prometheus read the per-scrape braid
|
|
15
|
+
of independent monotonic counters as counter resets and inflated `rate()` /
|
|
16
|
+
`increase()` on `runtime_http_*` counters by orders of magnitude. In multi-worker
|
|
17
|
+
mode the worker answering a scrape now asks the master for a merged, monotonic
|
|
18
|
+
view built from every worker's registry over the existing cluster IPC (via
|
|
19
|
+
prom-client's `AggregatorRegistry`), with a bounded timeout and a local-registry
|
|
20
|
+
fallback. Single-worker mode (`workers === 1`, includes `LINKED`) is unchanged.
|
|
21
|
+
Backport of #667 to the 6.x line.
|
|
22
|
+
### Fixed
|
|
23
|
+
- `runtime_http_*` metrics no longer emit samples without a `handler` label. Requests
|
|
24
|
+
that never reach a named handler (unmatched paths, replica-level rate limit
|
|
25
|
+
rejections, errors before the route pipeline) were counted with
|
|
26
|
+
`handler: undefined`; Node's cluster IPC serializes worker registries as JSON, which
|
|
27
|
+
drops `undefined` values, so the aggregated `/metrics` exposed a second, unnamed
|
|
28
|
+
series that Prometheus reads as `handler=""`. Those requests are now labelled
|
|
29
|
+
`handler="undefined"` — the same value prom-client rendered locally before cluster
|
|
30
|
+
aggregation — keeping dashboards and alerts that filter on it working. Backport of
|
|
31
|
+
#673 to the 6.x line.
|
|
32
|
+
- `/_status` requests are now reported as `handler="builtin:status-track"`, matching
|
|
33
|
+
the other builtin handlers, instead of falling into the unnamed bucket.
|
|
34
|
+
|
|
10
35
|
## [6.51.0] - 2026-06-23
|
|
11
36
|
### Added
|
|
12
37
|
- Base `IOClients` getter `janusCatalogSystem` (Janus Catalog) and
|
package/lib/service/master.d.ts
CHANGED
package/lib/service/master.js
CHANGED
|
@@ -3,11 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.startMaster = void 0;
|
|
6
|
+
exports.startMaster = exports.onMessage = void 0;
|
|
7
7
|
const cluster_1 = __importDefault(require("cluster"));
|
|
8
8
|
const os_1 = require("os");
|
|
9
9
|
const constants_1 = require("../constants");
|
|
10
10
|
const logger_1 = require("./logger");
|
|
11
|
+
const clusterMetricsAggregator_1 = require("./metrics/clusterMetricsAggregator");
|
|
11
12
|
const listeners_1 = require("./worker/listeners");
|
|
12
13
|
const statusTrack_1 = require("./worker/runtime/statusTrack");
|
|
13
14
|
let handledSignal;
|
|
@@ -19,7 +20,12 @@ const onMessage = (worker, message) => {
|
|
|
19
20
|
(0, statusTrack_1.trackStatus)();
|
|
20
21
|
(0, statusTrack_1.broadcastStatusTrack)();
|
|
21
22
|
}
|
|
22
|
-
else {
|
|
23
|
+
else if ((0, clusterMetricsAggregator_1.isAggMetricsRequest)(message)) {
|
|
24
|
+
(0, clusterMetricsAggregator_1.handleWorkerMetricsRequest)(worker, message);
|
|
25
|
+
}
|
|
26
|
+
else if (!(0, clusterMetricsAggregator_1.isPromClientMessage)(message)) {
|
|
27
|
+
// prom-client's own cluster messages are handled by its cluster listener;
|
|
28
|
+
// anything else that reaches here is genuinely unexpected.
|
|
23
29
|
listeners_1.logger.warn({
|
|
24
30
|
content: message,
|
|
25
31
|
message: 'Worker sent message',
|
|
@@ -27,6 +33,7 @@ const onMessage = (worker, message) => {
|
|
|
27
33
|
});
|
|
28
34
|
}
|
|
29
35
|
};
|
|
36
|
+
exports.onMessage = onMessage;
|
|
30
37
|
const onExit = (worker, code, signal) => {
|
|
31
38
|
if (!constants_1.LINKED && worker.exitedAfterDisconnect === false) {
|
|
32
39
|
listeners_1.logger.error({
|
|
@@ -70,6 +77,11 @@ const startMaster = (service) => {
|
|
|
70
77
|
if (service.deterministicVary) {
|
|
71
78
|
process.env.DETERMINISTIC_VARY = 'true';
|
|
72
79
|
}
|
|
80
|
+
// Set up the master-side Prometheus aggregator so workers can request a
|
|
81
|
+
// merged, monotonic /metrics view across the whole cluster over IPC.
|
|
82
|
+
if (numWorkers > 1) {
|
|
83
|
+
(0, clusterMetricsAggregator_1.initMasterAggregatorRegistry)();
|
|
84
|
+
}
|
|
73
85
|
// Setup dubugger
|
|
74
86
|
if (constants_1.LINKED) {
|
|
75
87
|
cluster_1.default.setupMaster({ inspectPort: constants_1.INSPECT_DEBUGGER_PORT });
|
|
@@ -82,7 +94,7 @@ const startMaster = (service) => {
|
|
|
82
94
|
}
|
|
83
95
|
cluster_1.default.on('online', onOnline);
|
|
84
96
|
cluster_1.default.on('exit', onExit);
|
|
85
|
-
cluster_1.default.on('message', onMessage);
|
|
97
|
+
cluster_1.default.on('message', exports.onMessage);
|
|
86
98
|
process.on('SIGINT', handleSignal(SIGINT_TIMEOUT_S));
|
|
87
99
|
process.on('SIGTERM', handleSignal(shutdownTimeout));
|
|
88
100
|
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Worker } from 'cluster';
|
|
2
|
+
import { AggregatorRegistry } from 'prom-client';
|
|
3
|
+
/**
|
|
4
|
+
* Cluster-wide Prometheus metrics aggregation.
|
|
5
|
+
*
|
|
6
|
+
* In multi-worker mode each cluster worker keeps its own prom-client default
|
|
7
|
+
* registry. Serving `/metrics` from a single (round-robin selected) worker
|
|
8
|
+
* therefore exposes only that worker's local counters, which makes Prometheus
|
|
9
|
+
* treat the per-scrape braid of independent counters as counter resets and
|
|
10
|
+
* inflates `rate()`/`increase()` by orders of magnitude.
|
|
11
|
+
*
|
|
12
|
+
* This module uses prom-client's `AggregatorRegistry` cluster IPC protocol so
|
|
13
|
+
* that the worker answering a scrape asks the master for a merged, monotonic
|
|
14
|
+
* view built from every worker's registry in one pass (no double-counting of
|
|
15
|
+
* the answering worker).
|
|
16
|
+
*/
|
|
17
|
+
/** Tagged IPC message: worker -> master, "please build the cluster aggregate". */
|
|
18
|
+
export declare const AGG_METRICS_REQ = "vtex-api:aggMetricsReq";
|
|
19
|
+
/** Tagged IPC message: master -> worker, carries the aggregate (or an error). */
|
|
20
|
+
export declare const AGG_METRICS_RES = "vtex-api:aggMetricsRes";
|
|
21
|
+
export interface AggMetricsReqMessage {
|
|
22
|
+
type: typeof AGG_METRICS_REQ;
|
|
23
|
+
id: number;
|
|
24
|
+
}
|
|
25
|
+
export interface AggMetricsResMessage {
|
|
26
|
+
type: typeof AGG_METRICS_RES;
|
|
27
|
+
id: number;
|
|
28
|
+
body?: string;
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
export declare const isAggMetricsRequest: (message: any) => message is AggMetricsReqMessage;
|
|
32
|
+
export declare const isAggMetricsResponse: (message: any) => message is AggMetricsResMessage;
|
|
33
|
+
/**
|
|
34
|
+
* prom-client's cluster protocol emits its own tagged IPC messages
|
|
35
|
+
* (`prom-client:getMetricsReq` / `prom-client:getMetricsRes`). They are handled
|
|
36
|
+
* by prom-client's own cluster listeners, so our `onMessage` handlers must
|
|
37
|
+
* ignore them instead of warning about "unknown" messages.
|
|
38
|
+
*/
|
|
39
|
+
export declare const isPromClientMessage: (message: any) => boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Constructs the master-side `AggregatorRegistry` (idempotent). Its constructor
|
|
42
|
+
* installs prom-client's master `cluster.on('message')` collector, which is
|
|
43
|
+
* what makes `clusterMetrics()` work. Must be called in the master before any
|
|
44
|
+
* worker can answer a scrape.
|
|
45
|
+
*/
|
|
46
|
+
export declare const initMasterAggregatorRegistry: () => AggregatorRegistry;
|
|
47
|
+
/**
|
|
48
|
+
* Handles an `AGG_METRICS_REQ` from a worker: builds the cluster aggregate and
|
|
49
|
+
* replies to that worker only. prom-client fans the request out to *all*
|
|
50
|
+
* connected workers (including the requester), so the requester is one of the N
|
|
51
|
+
* merged sources and is never double-counted.
|
|
52
|
+
*/
|
|
53
|
+
export declare const handleWorkerMetricsRequest: (worker: Worker, message: AggMetricsReqMessage) => Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Constructs the worker-side `AggregatorRegistry` (idempotent). Its constructor
|
|
56
|
+
* installs prom-client's worker `process.on('message')` responder that answers
|
|
57
|
+
* the master's `getMetricsReq` with this worker's registry JSON.
|
|
58
|
+
*/
|
|
59
|
+
export declare const ensureWorkerAggregatorRegistry: () => AggregatorRegistry;
|
|
60
|
+
/**
|
|
61
|
+
* Requests the cluster aggregate from the master over IPC and resolves with the
|
|
62
|
+
* merged exposition string. On timeout or any error it falls back to this
|
|
63
|
+
* worker's local `register.metrics()` so `/metrics` always answers promptly.
|
|
64
|
+
*/
|
|
65
|
+
export declare const requestAggregatedMetrics: () => Promise<string>;
|
|
66
|
+
/**
|
|
67
|
+
* Resolves the pending `requestAggregatedMetrics` promise correlated by id when
|
|
68
|
+
* the master replies. On error it falls back to the local registry.
|
|
69
|
+
*/
|
|
70
|
+
export declare const handleMasterMetricsResponse: (message: AggMetricsResMessage) => void;
|
|
71
|
+
/** Test-only helper to reset module state between test cases. */
|
|
72
|
+
export declare const __resetForTests: () => void;
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.__resetForTests = exports.handleMasterMetricsResponse = exports.requestAggregatedMetrics = exports.ensureWorkerAggregatorRegistry = exports.handleWorkerMetricsRequest = exports.initMasterAggregatorRegistry = exports.isPromClientMessage = exports.isAggMetricsResponse = exports.isAggMetricsRequest = exports.AGG_METRICS_RES = exports.AGG_METRICS_REQ = void 0;
|
|
4
|
+
const prom_client_1 = require("prom-client");
|
|
5
|
+
const listeners_1 = require("../worker/listeners");
|
|
6
|
+
/**
|
|
7
|
+
* Cluster-wide Prometheus metrics aggregation.
|
|
8
|
+
*
|
|
9
|
+
* In multi-worker mode each cluster worker keeps its own prom-client default
|
|
10
|
+
* registry. Serving `/metrics` from a single (round-robin selected) worker
|
|
11
|
+
* therefore exposes only that worker's local counters, which makes Prometheus
|
|
12
|
+
* treat the per-scrape braid of independent counters as counter resets and
|
|
13
|
+
* inflates `rate()`/`increase()` by orders of magnitude.
|
|
14
|
+
*
|
|
15
|
+
* This module uses prom-client's `AggregatorRegistry` cluster IPC protocol so
|
|
16
|
+
* that the worker answering a scrape asks the master for a merged, monotonic
|
|
17
|
+
* view built from every worker's registry in one pass (no double-counting of
|
|
18
|
+
* the answering worker).
|
|
19
|
+
*/
|
|
20
|
+
/** Tagged IPC message: worker -> master, "please build the cluster aggregate". */
|
|
21
|
+
exports.AGG_METRICS_REQ = 'vtex-api:aggMetricsReq';
|
|
22
|
+
/** Tagged IPC message: master -> worker, carries the aggregate (or an error). */
|
|
23
|
+
exports.AGG_METRICS_RES = 'vtex-api:aggMetricsRes';
|
|
24
|
+
/**
|
|
25
|
+
* Upper bound for a worker waiting on the master aggregate. prom-client's own
|
|
26
|
+
* `clusterMetrics()` has a 5s timeout collecting worker registries; we guard
|
|
27
|
+
* slightly above that and fall back to the local registry on expiry so that
|
|
28
|
+
* `/metrics` never hangs or returns empty.
|
|
29
|
+
*/
|
|
30
|
+
const AGG_METRICS_TIMEOUT_MS = 6000;
|
|
31
|
+
const isAggMetricsRequest = (message) => (message === null || message === void 0 ? void 0 : message.type) === exports.AGG_METRICS_REQ && typeof (message === null || message === void 0 ? void 0 : message.id) === 'number';
|
|
32
|
+
exports.isAggMetricsRequest = isAggMetricsRequest;
|
|
33
|
+
const isAggMetricsResponse = (message) => (message === null || message === void 0 ? void 0 : message.type) === exports.AGG_METRICS_RES && typeof (message === null || message === void 0 ? void 0 : message.id) === 'number';
|
|
34
|
+
exports.isAggMetricsResponse = isAggMetricsResponse;
|
|
35
|
+
/**
|
|
36
|
+
* prom-client's cluster protocol emits its own tagged IPC messages
|
|
37
|
+
* (`prom-client:getMetricsReq` / `prom-client:getMetricsRes`). They are handled
|
|
38
|
+
* by prom-client's own cluster listeners, so our `onMessage` handlers must
|
|
39
|
+
* ignore them instead of warning about "unknown" messages.
|
|
40
|
+
*/
|
|
41
|
+
const isPromClientMessage = (message) => typeof (message === null || message === void 0 ? void 0 : message.type) === 'string' && message.type.startsWith('prom-client:');
|
|
42
|
+
exports.isPromClientMessage = isPromClientMessage;
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// Master side
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
let masterAggregatorRegistry;
|
|
47
|
+
/**
|
|
48
|
+
* Constructs the master-side `AggregatorRegistry` (idempotent). Its constructor
|
|
49
|
+
* installs prom-client's master `cluster.on('message')` collector, which is
|
|
50
|
+
* what makes `clusterMetrics()` work. Must be called in the master before any
|
|
51
|
+
* worker can answer a scrape.
|
|
52
|
+
*/
|
|
53
|
+
const initMasterAggregatorRegistry = () => {
|
|
54
|
+
if (!masterAggregatorRegistry) {
|
|
55
|
+
masterAggregatorRegistry = new prom_client_1.AggregatorRegistry();
|
|
56
|
+
}
|
|
57
|
+
return masterAggregatorRegistry;
|
|
58
|
+
};
|
|
59
|
+
exports.initMasterAggregatorRegistry = initMasterAggregatorRegistry;
|
|
60
|
+
/**
|
|
61
|
+
* Handles an `AGG_METRICS_REQ` from a worker: builds the cluster aggregate and
|
|
62
|
+
* replies to that worker only. prom-client fans the request out to *all*
|
|
63
|
+
* connected workers (including the requester), so the requester is one of the N
|
|
64
|
+
* merged sources and is never double-counted.
|
|
65
|
+
*/
|
|
66
|
+
const handleWorkerMetricsRequest = async (worker, message) => {
|
|
67
|
+
var _a, _b;
|
|
68
|
+
const aggregator = (0, exports.initMasterAggregatorRegistry)();
|
|
69
|
+
let response;
|
|
70
|
+
try {
|
|
71
|
+
const body = await aggregator.clusterMetrics();
|
|
72
|
+
response = { type: exports.AGG_METRICS_RES, id: message.id, body };
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
response = { type: exports.AGG_METRICS_RES, id: message.id, error: (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : String(err) };
|
|
76
|
+
}
|
|
77
|
+
// `worker.send` can throw (e.g. the worker disconnected between the request
|
|
78
|
+
// and the reply). This handler is invoked without `await` from the master's
|
|
79
|
+
// message listener, so a thrown send would surface as an unhandled rejection
|
|
80
|
+
// in the master process. Swallow and log it instead.
|
|
81
|
+
try {
|
|
82
|
+
worker.send(response);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
listeners_1.logger.warn({
|
|
86
|
+
content: (_b = err === null || err === void 0 ? void 0 : err.message) !== null && _b !== void 0 ? _b : String(err),
|
|
87
|
+
message: 'Failed to send aggregated cluster metrics to worker',
|
|
88
|
+
pid: process.pid,
|
|
89
|
+
workerId: worker.id,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
exports.handleWorkerMetricsRequest = handleWorkerMetricsRequest;
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// Worker side
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
let workerAggregatorRegistry;
|
|
98
|
+
const pendingRequests = new Map();
|
|
99
|
+
let requestCounter = 0;
|
|
100
|
+
/**
|
|
101
|
+
* Constructs the worker-side `AggregatorRegistry` (idempotent). Its constructor
|
|
102
|
+
* installs prom-client's worker `process.on('message')` responder that answers
|
|
103
|
+
* the master's `getMetricsReq` with this worker's registry JSON.
|
|
104
|
+
*/
|
|
105
|
+
const ensureWorkerAggregatorRegistry = () => {
|
|
106
|
+
if (!workerAggregatorRegistry) {
|
|
107
|
+
workerAggregatorRegistry = new prom_client_1.AggregatorRegistry();
|
|
108
|
+
}
|
|
109
|
+
return workerAggregatorRegistry;
|
|
110
|
+
};
|
|
111
|
+
exports.ensureWorkerAggregatorRegistry = ensureWorkerAggregatorRegistry;
|
|
112
|
+
/**
|
|
113
|
+
* Requests the cluster aggregate from the master over IPC and resolves with the
|
|
114
|
+
* merged exposition string. On timeout or any error it falls back to this
|
|
115
|
+
* worker's local `register.metrics()` so `/metrics` always answers promptly.
|
|
116
|
+
*/
|
|
117
|
+
const requestAggregatedMetrics = async () => {
|
|
118
|
+
if (typeof process.send !== 'function') {
|
|
119
|
+
return prom_client_1.register.metrics();
|
|
120
|
+
}
|
|
121
|
+
const id = requestCounter++;
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
var _a;
|
|
124
|
+
const timer = setTimeout(() => {
|
|
125
|
+
pendingRequests.delete(id);
|
|
126
|
+
listeners_1.logger.warn({
|
|
127
|
+
message: 'Timed out waiting for aggregated cluster metrics; falling back to local registry',
|
|
128
|
+
pid: process.pid,
|
|
129
|
+
});
|
|
130
|
+
prom_client_1.register.metrics().then(resolve).catch(() => resolve(''));
|
|
131
|
+
}, AGG_METRICS_TIMEOUT_MS);
|
|
132
|
+
pendingRequests.set(id, { resolve, timer });
|
|
133
|
+
try {
|
|
134
|
+
process.send({ type: exports.AGG_METRICS_REQ, id });
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
pendingRequests.delete(id);
|
|
139
|
+
listeners_1.logger.warn({
|
|
140
|
+
content: (_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : String(err),
|
|
141
|
+
message: 'Failed to request aggregated cluster metrics; falling back to local registry',
|
|
142
|
+
pid: process.pid,
|
|
143
|
+
});
|
|
144
|
+
prom_client_1.register.metrics().then(resolve).catch(() => resolve(''));
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
exports.requestAggregatedMetrics = requestAggregatedMetrics;
|
|
149
|
+
/**
|
|
150
|
+
* Resolves the pending `requestAggregatedMetrics` promise correlated by id when
|
|
151
|
+
* the master replies. On error it falls back to the local registry.
|
|
152
|
+
*/
|
|
153
|
+
const handleMasterMetricsResponse = (message) => {
|
|
154
|
+
const pending = pendingRequests.get(message.id);
|
|
155
|
+
if (!pending) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
pendingRequests.delete(message.id);
|
|
159
|
+
clearTimeout(pending.timer);
|
|
160
|
+
if (message.error != null || message.body == null) {
|
|
161
|
+
listeners_1.logger.warn({
|
|
162
|
+
content: message.error,
|
|
163
|
+
message: 'Master failed to aggregate cluster metrics; falling back to local registry',
|
|
164
|
+
pid: process.pid,
|
|
165
|
+
});
|
|
166
|
+
prom_client_1.register.metrics().then(pending.resolve).catch(() => pending.resolve(''));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
pending.resolve(message.body);
|
|
170
|
+
};
|
|
171
|
+
exports.handleMasterMetricsResponse = handleMasterMetricsResponse;
|
|
172
|
+
/** Test-only helper to reset module state between test cases. */
|
|
173
|
+
// tslint:disable-next-line:variable-name
|
|
174
|
+
const __resetForTests = () => {
|
|
175
|
+
masterAggregatorRegistry = undefined;
|
|
176
|
+
workerAggregatorRegistry = undefined;
|
|
177
|
+
pendingRequests.forEach((p) => clearTimeout(p.timer));
|
|
178
|
+
pendingRequests.clear();
|
|
179
|
+
requestCounter = 0;
|
|
180
|
+
};
|
|
181
|
+
exports.__resetForTests = __resetForTests;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Label value reported for requests that never reached a named handler: unmatched
|
|
3
|
+
* paths (Koa answers its default 404), requests rejected before the route pipeline
|
|
4
|
+
* (replica-level rate limiter, errors in compress/recorder), and handlers that
|
|
5
|
+
* don't set `ctx.requestHandlerName`.
|
|
6
|
+
*
|
|
7
|
+
* The value must be a non-empty string. `ctx.requestHandlerName` is `undefined`
|
|
8
|
+
* for those requests, and Node's cluster IPC serializes each worker's registry as
|
|
9
|
+
* JSON, which drops properties whose value is `undefined`. The sample then reaches
|
|
10
|
+
* the aggregated `/metrics` with the `handler` label missing altogether, which
|
|
11
|
+
* Prometheus reads as `handler=""` — a distinct, unnamed series that shows up as
|
|
12
|
+
* an extra "Value" line in dashboards.
|
|
13
|
+
*
|
|
14
|
+
* `'undefined'` is deliberate rather than a nicer word: prom-client's local
|
|
15
|
+
* exposition already rendered `handler: undefined` as `handler="undefined"` before
|
|
16
|
+
* the cluster aggregation was introduced, so keeping that value makes the
|
|
17
|
+
* aggregated output match the historical series identity and keeps existing
|
|
18
|
+
* dashboards, filters and alerts (e.g. `handler!~"builtin:.*|undefined"`) working.
|
|
19
|
+
*/
|
|
20
|
+
export declare const UNNAMED_REQUEST_HANDLER = "undefined";
|
|
21
|
+
/**
|
|
22
|
+
* Resolves the `handler` label value for a request, falling back to
|
|
23
|
+
* {@link UNNAMED_REQUEST_HANDLER} when the pipeline never named the handler.
|
|
24
|
+
* Empty strings fall back too, so the label is never emitted empty.
|
|
25
|
+
*/
|
|
26
|
+
export declare const requestHandlerLabel: (requestHandlerName?: string) => string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requestHandlerLabel = exports.UNNAMED_REQUEST_HANDLER = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Label value reported for requests that never reached a named handler: unmatched
|
|
6
|
+
* paths (Koa answers its default 404), requests rejected before the route pipeline
|
|
7
|
+
* (replica-level rate limiter, errors in compress/recorder), and handlers that
|
|
8
|
+
* don't set `ctx.requestHandlerName`.
|
|
9
|
+
*
|
|
10
|
+
* The value must be a non-empty string. `ctx.requestHandlerName` is `undefined`
|
|
11
|
+
* for those requests, and Node's cluster IPC serializes each worker's registry as
|
|
12
|
+
* JSON, which drops properties whose value is `undefined`. The sample then reaches
|
|
13
|
+
* the aggregated `/metrics` with the `handler` label missing altogether, which
|
|
14
|
+
* Prometheus reads as `handler=""` — a distinct, unnamed series that shows up as
|
|
15
|
+
* an extra "Value" line in dashboards.
|
|
16
|
+
*
|
|
17
|
+
* `'undefined'` is deliberate rather than a nicer word: prom-client's local
|
|
18
|
+
* exposition already rendered `handler: undefined` as `handler="undefined"` before
|
|
19
|
+
* the cluster aggregation was introduced, so keeping that value makes the
|
|
20
|
+
* aggregated output match the historical series identity and keeps existing
|
|
21
|
+
* dashboards, filters and alerts (e.g. `handler!~"builtin:.*|undefined"`) working.
|
|
22
|
+
*/
|
|
23
|
+
exports.UNNAMED_REQUEST_HANDLER = 'undefined';
|
|
24
|
+
/**
|
|
25
|
+
* Resolves the `handler` label value for a request, falling back to
|
|
26
|
+
* {@link UNNAMED_REQUEST_HANDLER} when the pipeline never named the handler.
|
|
27
|
+
* Empty strings fall back too, so the label is never emitted empty.
|
|
28
|
+
*/
|
|
29
|
+
const requestHandlerLabel = (requestHandlerName) => requestHandlerName || exports.UNNAMED_REQUEST_HANDLER;
|
|
30
|
+
exports.requestHandlerLabel = requestHandlerLabel;
|
|
@@ -4,6 +4,7 @@ exports.addRequestMetricsMiddleware = void 0;
|
|
|
4
4
|
const stream_1 = require("stream");
|
|
5
5
|
const utils_1 = require("../../utils");
|
|
6
6
|
const instruments_1 = require("../tracing/metrics/instruments");
|
|
7
|
+
const requestHandlerLabel_1 = require("./requestHandlerLabel");
|
|
7
8
|
const addRequestMetricsMiddleware = () => {
|
|
8
9
|
const concurrentRequests = (0, instruments_1.createConcurrentRequestsInstrument)();
|
|
9
10
|
const requestTimings = (0, instruments_1.createRequestsTimingsInstrument)();
|
|
@@ -13,7 +14,7 @@ const addRequestMetricsMiddleware = () => {
|
|
|
13
14
|
return async function addRequestMetrics(ctx, next) {
|
|
14
15
|
const start = process.hrtime();
|
|
15
16
|
concurrentRequests.inc(1);
|
|
16
|
-
ctx.req.once('aborted', () => abortedRequests.inc({ ["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: ctx.requestHandlerName }, 1));
|
|
17
|
+
ctx.req.once('aborted', () => abortedRequests.inc({ ["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName) }, 1));
|
|
17
18
|
let responseClosed = false;
|
|
18
19
|
ctx.res.once('close', () => (responseClosed = true));
|
|
19
20
|
try {
|
|
@@ -22,15 +23,15 @@ const addRequestMetricsMiddleware = () => {
|
|
|
22
23
|
finally {
|
|
23
24
|
const responseLength = ctx.response.length;
|
|
24
25
|
if (responseLength) {
|
|
25
|
-
responseSizes.observe({ ["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: ctx.requestHandlerName }, responseLength);
|
|
26
|
+
responseSizes.observe({ ["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName) }, responseLength);
|
|
26
27
|
}
|
|
27
28
|
totalRequests.inc({
|
|
28
|
-
["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: ctx.requestHandlerName,
|
|
29
|
+
["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
|
|
29
30
|
["status_code" /* RequestsMetricLabels.STATUS_CODE */]: ctx.response.status,
|
|
30
31
|
}, 1);
|
|
31
32
|
const onResFinished = () => {
|
|
32
33
|
requestTimings.observe({
|
|
33
|
-
["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: ctx.requestHandlerName,
|
|
34
|
+
["handler" /* RequestsMetricLabels.REQUEST_HANDLER */]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
|
|
34
35
|
}, (0, utils_1.hrToMillisFloat)(process.hrtime(start)));
|
|
35
36
|
concurrentRequests.dec(1);
|
|
36
37
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import Koa from 'koa';
|
|
2
2
|
import { MetricsAccumulator } from '../../metrics/MetricsAccumulator';
|
|
3
3
|
import { ServiceJSON } from './runtime/typings';
|
|
4
|
+
export declare const onMessage: (service: ServiceJSON) => (message: any) => void;
|
|
4
5
|
export declare const startWorker: (serviceJSON: ServiceJSON) => Koa<Koa.DefaultState, Koa.DefaultContext>;
|
|
5
6
|
declare global {
|
|
6
7
|
namespace NodeJS {
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.startWorker = void 0;
|
|
6
|
+
exports.startWorker = exports.onMessage = void 0;
|
|
7
7
|
const http_1 = require("http");
|
|
8
8
|
const koa_1 = __importDefault(require("koa"));
|
|
9
9
|
const koa_compress_1 = __importDefault(require("koa-compress"));
|
|
@@ -14,6 +14,7 @@ const MetricsAccumulator_1 = require("../../metrics/MetricsAccumulator");
|
|
|
14
14
|
const loaders_1 = require("../loaders");
|
|
15
15
|
const console_1 = require("../logger/console");
|
|
16
16
|
const loggerTypes_1 = require("../logger/loggerTypes");
|
|
17
|
+
const clusterMetricsAggregator_1 = require("../metrics/clusterMetricsAggregator");
|
|
17
18
|
const requestMetricsMiddleware_1 = require("../metrics/requestMetricsMiddleware");
|
|
18
19
|
const TracerSingleton_1 = require("../tracing/TracerSingleton");
|
|
19
20
|
const tracingMiddlewares_1 = require("../tracing/tracingMiddlewares");
|
|
@@ -54,7 +55,12 @@ const onMessage = (service) => (message) => {
|
|
|
54
55
|
else if ((0, statusTrack_1.isStatusTrack)(message)) {
|
|
55
56
|
(0, statusTrack_1.trackStatus)();
|
|
56
57
|
}
|
|
57
|
-
else {
|
|
58
|
+
else if ((0, clusterMetricsAggregator_1.isAggMetricsResponse)(message)) {
|
|
59
|
+
(0, clusterMetricsAggregator_1.handleMasterMetricsResponse)(message);
|
|
60
|
+
}
|
|
61
|
+
else if (!(0, clusterMetricsAggregator_1.isPromClientMessage)(message)) {
|
|
62
|
+
// prom-client's own cluster messages are handled by its worker listener;
|
|
63
|
+
// anything else that reaches here is genuinely unexpected.
|
|
58
64
|
listeners_1.logger.warn({
|
|
59
65
|
content: message,
|
|
60
66
|
message: 'Master sent message',
|
|
@@ -62,6 +68,7 @@ const onMessage = (service) => (message) => {
|
|
|
62
68
|
});
|
|
63
69
|
}
|
|
64
70
|
};
|
|
71
|
+
exports.onMessage = onMessage;
|
|
65
72
|
const createAppHttpHandlers = ({ config: { routes, clients } }, serviceJSON, globalLimiter) => {
|
|
66
73
|
if (routes && clients) {
|
|
67
74
|
return Object.keys(routes).reduce((acc, routeId) => {
|
|
@@ -153,11 +160,16 @@ const startWorker = (serviceJSON) => {
|
|
|
153
160
|
var _a, _b;
|
|
154
161
|
(0, listeners_1.addProcessListeners)();
|
|
155
162
|
const tracer = TracerSingleton_1.TracerSingleton.getTracer();
|
|
163
|
+
// In multi-worker mode install prom-client's worker-side cluster responder so
|
|
164
|
+
// the master can collect this worker's registry for the aggregated /metrics.
|
|
165
|
+
if (serviceJSON.workers > 1) {
|
|
166
|
+
(0, clusterMetricsAggregator_1.ensureWorkerAggregatorRegistry)();
|
|
167
|
+
}
|
|
156
168
|
const app = new koa_1.default();
|
|
157
169
|
app.proxy = true;
|
|
158
170
|
app
|
|
159
171
|
.use(error_1.error)
|
|
160
|
-
.use((0, middlewares_1.prometheusLoggerMiddleware)())
|
|
172
|
+
.use((0, middlewares_1.prometheusLoggerMiddleware)(serviceJSON.workers))
|
|
161
173
|
.use((0, tracingMiddlewares_1.addTracingMiddleware)(tracer))
|
|
162
174
|
.use((0, requestMetricsMiddleware_1.addRequestMetricsMiddleware)())
|
|
163
175
|
.use((0, middlewares_1.addMetricsLoggerMiddleware)())
|
|
@@ -190,7 +202,7 @@ const startWorker = (serviceJSON) => {
|
|
|
190
202
|
const privateHandlersRouter = routerFromPrivateHttpHandlers(httpHandlers.pvt);
|
|
191
203
|
app.use(privateHandlersRouter.routes());
|
|
192
204
|
}
|
|
193
|
-
process.on('message', onMessage(serviceJSON));
|
|
205
|
+
process.on('message', (0, exports.onMessage)(serviceJSON));
|
|
194
206
|
return app;
|
|
195
207
|
};
|
|
196
208
|
exports.startWorker = startWorker;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { ServiceContext } from '../typings';
|
|
2
2
|
export declare function recorderMiddleware(ctx: ServiceContext, next: () => Promise<void>): Promise<void>;
|
|
3
3
|
export declare const addMetricsLoggerMiddleware: () => (ctx: ServiceContext, next: () => Promise<void>) => Promise<void>;
|
|
4
|
-
export declare const prometheusLoggerMiddleware: () => (ctx: ServiceContext, next: () => Promise<void>) => Promise<void>;
|
|
4
|
+
export declare const prometheusLoggerMiddleware: (workers?: number) => (ctx: ServiceContext, next: () => Promise<void>) => Promise<void>;
|
|
@@ -4,6 +4,7 @@ exports.prometheusLoggerMiddleware = exports.addMetricsLoggerMiddleware = export
|
|
|
4
4
|
const prom_client_1 = require("prom-client");
|
|
5
5
|
const constants_1 = require("../../../../constants");
|
|
6
6
|
const metricsLogger_1 = require("../../../logger/metricsLogger");
|
|
7
|
+
const clusterMetricsAggregator_1 = require("../../../metrics/clusterMetricsAggregator");
|
|
7
8
|
const EventLoopLagMeasurer_1 = require("../../../tracing/metrics/measurers/EventLoopLagMeasurer");
|
|
8
9
|
const recorder_1 = require("../utils/recorder");
|
|
9
10
|
async function recorderMiddleware(ctx, next) {
|
|
@@ -22,10 +23,14 @@ const addMetricsLoggerMiddleware = () => {
|
|
|
22
23
|
};
|
|
23
24
|
};
|
|
24
25
|
exports.addMetricsLoggerMiddleware = addMetricsLoggerMiddleware;
|
|
25
|
-
const prometheusLoggerMiddleware = () => {
|
|
26
|
+
const prometheusLoggerMiddleware = (workers = 1) => {
|
|
26
27
|
(0, prom_client_1.collectDefaultMetrics)();
|
|
27
28
|
const eventLoopLagMeasurer = new EventLoopLagMeasurer_1.EventLoopLagMeasurer();
|
|
28
29
|
eventLoopLagMeasurer.start();
|
|
30
|
+
// In multi-worker mode each worker holds only its own registry, so /metrics
|
|
31
|
+
// must serve the cluster-wide aggregate requested from the master over IPC.
|
|
32
|
+
// In single-worker mode (LINKED / workers:1) the local registry is complete.
|
|
33
|
+
const isMultiWorker = workers > 1;
|
|
29
34
|
return async (ctx, next) => {
|
|
30
35
|
if (ctx.request.path !== '/metrics') {
|
|
31
36
|
return next();
|
|
@@ -36,7 +41,7 @@ const prometheusLoggerMiddleware = () => {
|
|
|
36
41
|
}
|
|
37
42
|
await eventLoopLagMeasurer.updateInstrumentsAndReset();
|
|
38
43
|
ctx.set('Content-Type', prom_client_1.register.contentType);
|
|
39
|
-
ctx.body = await prom_client_1.register.metrics();
|
|
44
|
+
ctx.body = isMultiWorker ? await (0, clusterMetricsAggregator_1.requestAggregatedMetrics)() : await prom_client_1.register.metrics();
|
|
40
45
|
ctx.status = 200;
|
|
41
46
|
};
|
|
42
47
|
};
|
|
@@ -14,7 +14,10 @@ const isStatusTrackBroadcast = (message) => message === BROADCAST_STATUS_TRACK;
|
|
|
14
14
|
exports.isStatusTrackBroadcast = isStatusTrackBroadcast;
|
|
15
15
|
const statusTrackHandler = async (ctx) => {
|
|
16
16
|
var _a, _b, _c;
|
|
17
|
-
|
|
17
|
+
// Parity with the other builtin handlers: name the request so its samples don't
|
|
18
|
+
// land in the catch-all `handler="undefined"` bucket.
|
|
19
|
+
ctx.requestHandlerName = 'builtin:status-track';
|
|
20
|
+
(_b = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.currentSpan) === null || _b === void 0 ? void 0 : _b.setOperationName(ctx.requestHandlerName);
|
|
18
21
|
if (!constants_1.LINKED) {
|
|
19
22
|
(_c = process.send) === null || _c === void 0 ? void 0 : _c.call(process, BROADCAST_STATUS_TRACK);
|
|
20
23
|
}
|