@vtex/api 7.4.2-beta.1 → 7.5.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 CHANGED
@@ -5,7 +5,29 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
6
6
  and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [7.5.0]
9
+
10
+ ### Added
11
+
12
+ - Kubernetes cluster identity and role (`VTEX_CLUSTER_ID` → `cluster_id`,
13
+ `VTEX_CLUSTER_ROLE` → `cluster_role`) as shared diagnostics resource
14
+ attributes, applied centrally to diagnostics metrics and logs. Values are
15
+ trimmed and omitted independently when empty, enabling cross-cluster
16
+ dashboards and incident isolation without consuming per-call custom
17
+ attribute limits.
18
+
19
+ ### Fixed
20
+
21
+ - `runtime_http_*` metrics no longer emit samples without a `handler` label. Requests
22
+ that never reach a named handler (unmatched paths, replica-level rate limit
23
+ rejections, errors before the route pipeline) were counted with
24
+ `handler: undefined`; Node's cluster IPC serializes worker registries as JSON, which
25
+ drops `undefined` values, so the aggregated `/metrics` exposed a second, unnamed
26
+ series that Prometheus reads as `handler=""`. Those requests are now labelled
27
+ `handler="undefined"` — the same value prom-client rendered locally before cluster
28
+ aggregation — keeping dashboards and alerts that filter on it working.
29
+ - `/_status` requests are now reported as `handler="builtin:status-track"`, matching
30
+ the other builtin handlers, instead of falling into the unnamed bucket.
9
31
 
10
32
  ## [7.4.0] - 2026-06-22
11
33
  ### Changed
@@ -45,6 +45,8 @@ export declare const AttributeKeys: {
45
45
  VTEX_IO_WORKSPACE_TYPE: "vtex_io.workspace.type";
46
46
  VTEX_IO_APP_ID: "vtex_io.app.id";
47
47
  VTEX_IO_APP_AUTHOR_TYPE: "vtex_io.app.author_type";
48
+ VTEX_IO_CLUSTER_ID: "vtex_io.cluster.id";
49
+ VTEX_IO_CLUSTER_ROLE: "vtex_io.cluster.role";
48
50
  };
49
51
  /** @deprecated Use HeaderKeys.CACHE_CONTROL instead */
50
52
  export declare const CACHE_CONTROL_HEADER: string;
@@ -114,6 +116,8 @@ export declare const HTTP_SERVER_PORT = 5050;
114
116
  export declare const MAX_WORKERS = 4;
115
117
  export declare const LINKED: boolean;
116
118
  export declare const REGION: string;
119
+ export declare const CLUSTER_ID: string;
120
+ export declare const CLUSTER_ROLE: string;
117
121
  export declare const PUBLIC_ENDPOINT: string;
118
122
  export declare const APP: {
119
123
  ID: string;
package/lib/constants.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOG_CLIENT_INIT_TIMEOUT_MS = exports.cancellableMethods = exports.INSPECT_DEBUGGER_PORT = exports.PRODUCTION = exports.WORKSPACE = exports.ACCOUNT = exports.NODE_ENV = exports.APP = exports.PUBLIC_ENDPOINT = exports.REGION = exports.LINKED = exports.MAX_WORKERS = exports.HTTP_SERVER_PORT = exports.MAX_AGE = exports.UP_SIGNAL = exports.BODY_HASH = exports.PROVIDER_HEADER = exports.TRACE_ID_HEADER = exports.COLOSSUS_PARAMS_HEADER = exports.COLOSSUS_ROUTE_ID_HEADER = exports.COLOSSUS_ROUTE_DECLARER_HEADER = exports.EVENT_HANDLER_ID_HEADER = exports.EVENT_SUBJECT_HEADER = exports.EVENT_SENDER_HEADER = exports.EVENT_KEY_HEADER = exports.WORKSPACE_HEADER = exports.WORKSPACE_IS_PRODUCTION_HEADER = exports.PLATFORM_HEADER = exports.OPERATION_ID_HEADER = exports.ROUTER_CACHE_HEADER = exports.REQUEST_ID_HEADER = exports.CREDENTIAL_HEADER = exports.ACCOUNT_HEADER = exports.ETAG_HEADER = exports.META_HEADER_BUCKET = exports.META_HEADER = exports.BINDING_HEADER = exports.TENANT_HEADER = exports.FORWARDED_HOST_HEADER = exports.LOCALE_HEADER = exports.PRODUCT_HEADER = exports.SESSION_HEADER = exports.SEGMENT_HEADER = exports.CACHE_CONTROL_HEADER = exports.AttributeKeys = exports.HeaderKeys = exports.PID = exports.IS_IO = exports.DEFAULT_WORKSPACE = exports.NODE_VTEX_API_VERSION = void 0;
4
- exports.DIAGNOSTICS_TELEMETRY_ENABLED = exports.DK_APP_ID = exports.OTEL_EXPORTER_OTLP_ENDPOINT = exports.METRIC_CLIENT_INIT_TIMEOUT_MS = void 0;
3
+ exports.INSPECT_DEBUGGER_PORT = exports.PRODUCTION = exports.WORKSPACE = exports.ACCOUNT = exports.NODE_ENV = exports.APP = exports.PUBLIC_ENDPOINT = exports.CLUSTER_ROLE = exports.CLUSTER_ID = exports.REGION = exports.LINKED = exports.MAX_WORKERS = exports.HTTP_SERVER_PORT = exports.MAX_AGE = exports.UP_SIGNAL = exports.BODY_HASH = exports.PROVIDER_HEADER = exports.TRACE_ID_HEADER = exports.COLOSSUS_PARAMS_HEADER = exports.COLOSSUS_ROUTE_ID_HEADER = exports.COLOSSUS_ROUTE_DECLARER_HEADER = exports.EVENT_HANDLER_ID_HEADER = exports.EVENT_SUBJECT_HEADER = exports.EVENT_SENDER_HEADER = exports.EVENT_KEY_HEADER = exports.WORKSPACE_HEADER = exports.WORKSPACE_IS_PRODUCTION_HEADER = exports.PLATFORM_HEADER = exports.OPERATION_ID_HEADER = exports.ROUTER_CACHE_HEADER = exports.REQUEST_ID_HEADER = exports.CREDENTIAL_HEADER = exports.ACCOUNT_HEADER = exports.ETAG_HEADER = exports.META_HEADER_BUCKET = exports.META_HEADER = exports.BINDING_HEADER = exports.TENANT_HEADER = exports.FORWARDED_HOST_HEADER = exports.LOCALE_HEADER = exports.PRODUCT_HEADER = exports.SESSION_HEADER = exports.SEGMENT_HEADER = exports.CACHE_CONTROL_HEADER = exports.AttributeKeys = exports.HeaderKeys = exports.PID = exports.IS_IO = exports.DEFAULT_WORKSPACE = exports.NODE_VTEX_API_VERSION = void 0;
4
+ exports.DIAGNOSTICS_TELEMETRY_ENABLED = exports.DK_APP_ID = exports.OTEL_EXPORTER_OTLP_ENDPOINT = exports.METRIC_CLIENT_INIT_TIMEOUT_MS = exports.LOG_CLIENT_INIT_TIMEOUT_MS = exports.cancellableMethods = void 0;
5
5
  const app_1 = require("./utils/app");
6
6
  const diagnostics_semconv_1 = require("@vtex/diagnostics-semconv");
7
7
  // tslint:disable-next-line
@@ -55,6 +55,8 @@ exports.AttributeKeys = {
55
55
  VTEX_IO_WORKSPACE_TYPE: diagnostics_semconv_1.ATTR_VTEX_IO_WORKSPACE_TYPE,
56
56
  VTEX_IO_APP_ID: diagnostics_semconv_1.ATTR_VTEX_IO_APP_ID,
57
57
  VTEX_IO_APP_AUTHOR_TYPE: diagnostics_semconv_1.ATTR_VTEX_IO_APP_AUTHOR_TYPE,
58
+ VTEX_IO_CLUSTER_ID: diagnostics_semconv_1.ATTR_VTEX_IO_CLUSTER_ID,
59
+ VTEX_IO_CLUSTER_ROLE: diagnostics_semconv_1.ATTR_VTEX_IO_CLUSTER_ROLE,
58
60
  };
59
61
  /** @deprecated Use HeaderKeys.CACHE_CONTROL instead */
60
62
  exports.CACHE_CONTROL_HEADER = exports.HeaderKeys.CACHE_CONTROL;
@@ -123,6 +125,8 @@ exports.HTTP_SERVER_PORT = 5050;
123
125
  exports.MAX_WORKERS = 4;
124
126
  exports.LINKED = !!process.env.VTEX_APP_LINK;
125
127
  exports.REGION = process.env.VTEX_REGION;
128
+ exports.CLUSTER_ID = process.env.VTEX_CLUSTER_ID;
129
+ exports.CLUSTER_ROLE = process.env.VTEX_CLUSTER_ROLE;
126
130
  exports.PUBLIC_ENDPOINT = process.env.VTEX_PUBLIC_ENDPOINT || 'myvtex.com';
127
131
  exports.APP = {
128
132
  ID: process.env.VTEX_APP_ID,
@@ -1,2 +1,4 @@
1
+ import { Worker } from 'cluster';
1
2
  import { ServiceJSON } from './worker/runtime/typings';
3
+ export declare const onMessage: (worker: Worker, message: any) => void;
2
4
  export declare const startMaster: (service: ServiceJSON) => void;
@@ -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,180 @@
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
+ const __resetForTests = () => {
174
+ masterAggregatorRegistry = undefined;
175
+ workerAggregatorRegistry = undefined;
176
+ pendingRequests.forEach((p) => clearTimeout(p.timer));
177
+ pendingRequests.clear();
178
+ requestCounter = 0;
179
+ };
180
+ exports.__resetForTests = __resetForTests;
@@ -4,6 +4,7 @@ exports.addOtelRequestMetricsMiddleware = void 0;
4
4
  const stream_1 = require("stream");
5
5
  const utils_1 = require("../../utils");
6
6
  const metrics_1 = require("./metrics");
7
+ const requestHandlerLabel_1 = require("./requestHandlerLabel");
7
8
  const INSTRUMENTS_INITIALIZATION_TIMEOUT = 500;
8
9
  const addOtelRequestMetricsMiddleware = () => {
9
10
  let instruments;
@@ -31,7 +32,9 @@ const addOtelRequestMetricsMiddleware = () => {
31
32
  instruments.concurrentRequests.add(1);
32
33
  ctx.req.once('aborted', () => {
33
34
  if (instruments) {
34
- instruments.abortedRequests.add(1, { [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: ctx.requestHandlerName });
35
+ instruments.abortedRequests.add(1, {
36
+ [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
37
+ });
35
38
  }
36
39
  });
37
40
  let responseClosed = false;
@@ -43,14 +46,14 @@ const addOtelRequestMetricsMiddleware = () => {
43
46
  const responseLength = ctx.response.length;
44
47
  if (responseLength && instruments) {
45
48
  instruments.responseSizes.record(responseLength, {
46
- [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: ctx.requestHandlerName,
49
+ [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
47
50
  [metrics_1.RequestsMetricLabels.STATUS_CODE]: ctx.response.status,
48
51
  [metrics_1.RequestsMetricLabels.ACCOUNT_NAME]: ((_a = ctx.vtex) === null || _a === void 0 ? void 0 : _a.account) || 'unknown',
49
52
  });
50
53
  }
51
54
  if (instruments) {
52
55
  instruments.totalRequests.add(1, {
53
- [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: ctx.requestHandlerName,
56
+ [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
54
57
  [metrics_1.RequestsMetricLabels.STATUS_CODE]: ctx.response.status,
55
58
  [metrics_1.RequestsMetricLabels.ACCOUNT_NAME]: ((_b = ctx.vtex) === null || _b === void 0 ? void 0 : _b.account) || 'unknown',
56
59
  });
@@ -59,7 +62,7 @@ const addOtelRequestMetricsMiddleware = () => {
59
62
  var _a;
60
63
  if (instruments) {
61
64
  instruments.requestTimings.record((0, utils_1.hrToMillisFloat)(process.hrtime(start)), {
62
- [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: ctx.requestHandlerName,
65
+ [metrics_1.RequestsMetricLabels.REQUEST_HANDLER]: (0, requestHandlerLabel_1.requestHandlerLabel)(ctx.requestHandlerName),
63
66
  [metrics_1.RequestsMetricLabels.STATUS_CODE]: ctx.response.status,
64
67
  [metrics_1.RequestsMetricLabels.ACCOUNT_NAME]: ((_a = ctx.vtex) === null || _a === void 0 ? void 0 : _a.account) || 'unknown',
65
68
  });
@@ -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
  };
@@ -5,6 +5,7 @@ const instrumentation_koa_1 = require("@opentelemetry/instrumentation-koa");
5
5
  const diagnostics_nodejs_1 = require("@vtex/diagnostics-nodejs");
6
6
  const constants_1 = require("../../constants");
7
7
  const hostMetrics_1 = require("../metrics/instruments/hostMetrics");
8
+ const resourceAttributes_1 = require("./resourceAttributes");
8
9
  const APPLICATION_ID = constants_1.APP.ID || 'vtex-io-app';
9
10
  class TelemetryClientSingleton {
10
11
  static getInstance() {
@@ -58,6 +59,7 @@ class TelemetryClientSingleton {
58
59
  'version': constants_1.APP.VERSION || '',
59
60
  [constants_1.AttributeKeys.VTEX_IO_WORKSPACE_NAME]: constants_1.WORKSPACE,
60
61
  [constants_1.AttributeKeys.VTEX_IO_WORKSPACE_TYPE]: constants_1.PRODUCTION ? 'production' : 'development',
62
+ ...(0, resourceAttributes_1.getClusterResourceAttributes)(constants_1.CLUSTER_ID, constants_1.CLUSTER_ROLE),
61
63
  },
62
64
  // Use built-in no-op functionality when telemetry is disabled
63
65
  noop: !constants_1.DIAGNOSTICS_TELEMETRY_ENABLED,
@@ -0,0 +1 @@
1
+ export declare const getClusterResourceAttributes: (clusterId?: string, clusterRole?: string) => Record<string, string>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getClusterResourceAttributes = void 0;
4
+ const constants_1 = require("../../constants");
5
+ const normalizeAttribute = (value) => {
6
+ const normalized = value === null || value === void 0 ? void 0 : value.trim();
7
+ return normalized || undefined;
8
+ };
9
+ const getClusterResourceAttributes = (clusterId, clusterRole) => {
10
+ const attributes = {};
11
+ const normalizedClusterId = normalizeAttribute(clusterId);
12
+ const normalizedClusterRole = normalizeAttribute(clusterRole);
13
+ if (normalizedClusterId) {
14
+ attributes[constants_1.AttributeKeys.VTEX_IO_CLUSTER_ID] = normalizedClusterId;
15
+ }
16
+ if (normalizedClusterRole) {
17
+ attributes[constants_1.AttributeKeys.VTEX_IO_CLUSTER_ROLE] = normalizedClusterRole;
18
+ }
19
+ return attributes;
20
+ };
21
+ exports.getClusterResourceAttributes = getClusterResourceAttributes;
@@ -1,3 +1,4 @@
1
1
  import Koa from 'koa';
2
2
  import { ServiceJSON } from './runtime/typings';
3
+ export declare const onMessage: (service: ServiceJSON) => (message: any) => void;
3
4
  export declare const startWorker: (serviceJSON: ServiceJSON) => Koa<Koa.DefaultState, Koa.DefaultContext>;
@@ -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 diagnostics_nodejs_1 = require("@vtex/diagnostics-nodejs");
8
8
  const http_1 = require("http");
9
9
  const koa_1 = __importDefault(require("koa"));
@@ -14,6 +14,7 @@ const constants_1 = require("../../constants");
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 otelRequestMetricsMiddleware_1 = require("../metrics/otelRequestMetricsMiddleware");
18
19
  const requestMetricsMiddleware_1 = require("../metrics/requestMetricsMiddleware");
19
20
  const TracerSingleton_1 = require("../tracing/TracerSingleton");
@@ -55,7 +56,12 @@ const onMessage = (service) => (message) => {
55
56
  else if ((0, statusTrack_1.isStatusTrack)(message)) {
56
57
  (0, statusTrack_1.trackStatus)();
57
58
  }
58
- else {
59
+ else if ((0, clusterMetricsAggregator_1.isAggMetricsResponse)(message)) {
60
+ (0, clusterMetricsAggregator_1.handleMasterMetricsResponse)(message);
61
+ }
62
+ else if (!(0, clusterMetricsAggregator_1.isPromClientMessage)(message)) {
63
+ // prom-client's own cluster messages are handled by its worker listener;
64
+ // anything else that reaches here is genuinely unexpected.
59
65
  listeners_1.logger.warn({
60
66
  content: message,
61
67
  message: 'Master sent message',
@@ -63,6 +69,7 @@ const onMessage = (service) => (message) => {
63
69
  });
64
70
  }
65
71
  };
72
+ exports.onMessage = onMessage;
66
73
  const createAppHttpHandlers = ({ config: { routes, clients } }, serviceJSON, globalLimiter) => {
67
74
  if (routes && clients) {
68
75
  return Object.keys(routes).reduce((acc, routeId) => {
@@ -154,12 +161,17 @@ const startWorker = (serviceJSON) => {
154
161
  var _a, _b;
155
162
  (0, listeners_1.addProcessListeners)();
156
163
  const tracer = TracerSingleton_1.TracerSingleton.getTracer();
164
+ // In multi-worker mode install prom-client's worker-side cluster responder so
165
+ // the master can collect this worker's registry for the aggregated /metrics.
166
+ if (serviceJSON.workers > 1) {
167
+ (0, clusterMetricsAggregator_1.ensureWorkerAggregatorRegistry)();
168
+ }
157
169
  const app = new koa_1.default();
158
170
  app.proxy = true;
159
171
  app
160
172
  .use(error_1.error)
161
173
  .use(diagnostics_nodejs_1.Instrumentation.Middlewares.ContextMiddlewares.Koa.ContextPropagationMiddleware())
162
- .use((0, middlewares_1.prometheusLoggerMiddleware)())
174
+ .use((0, middlewares_1.prometheusLoggerMiddleware)(serviceJSON.workers))
163
175
  .use((0, tracingMiddlewares_1.addTracingMiddleware)(tracer))
164
176
  .use((0, requestMetricsMiddleware_1.addRequestMetricsMiddleware)())
165
177
  .use((0, otelRequestMetricsMiddleware_1.addOtelRequestMetricsMiddleware)())
@@ -182,9 +194,8 @@ const startWorker = (serviceJSON) => {
182
194
  appGraphQLHandlers,
183
195
  runtimeHttpHandlers,
184
196
  ]
185
- .filter(x => x != null)
186
- // TODO: Fix ramda typings. Apparently there was an update that broke things
187
- .reduce(ramda_1.mergeDeepRight);
197
+ .filter((x) => x != null)
198
+ .reduce((acc, handler) => (0, ramda_1.mergeDeepRight)(acc, handler), {});
188
199
  if (httpHandlers === null || httpHandlers === void 0 ? void 0 : httpHandlers.pub) {
189
200
  const publicHandlersRouter = (0, router_2.routerFromPublicHttpHandlers)(httpHandlers.pub);
190
201
  app.use(publicHandlersRouter);
@@ -193,7 +204,7 @@ const startWorker = (serviceJSON) => {
193
204
  const privateHandlersRouter = routerFromPrivateHttpHandlers(httpHandlers.pvt);
194
205
  app.use(privateHandlersRouter.routes());
195
206
  }
196
- process.on('message', onMessage(serviceJSON));
207
+ process.on('message', (0, exports.onMessage)(serviceJSON));
197
208
  return app;
198
209
  };
199
210
  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
  };
@@ -15,7 +15,10 @@ const isStatusTrackBroadcast = (message) => message === BROADCAST_STATUS_TRACK;
15
15
  exports.isStatusTrackBroadcast = isStatusTrackBroadcast;
16
16
  const statusTrackHandler = async (ctx) => {
17
17
  var _a, _b, _c;
18
- (_b = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.currentSpan) === null || _b === void 0 ? void 0 : _b.setOperationName('builtin:status-track');
18
+ // Parity with the other builtin handlers: name the request so its samples don't
19
+ // land in the catch-all `handler="undefined"` bucket.
20
+ ctx.requestHandlerName = 'builtin:status-track';
21
+ (_b = (_a = ctx.tracing) === null || _a === void 0 ? void 0 : _a.currentSpan) === null || _b === void 0 ? void 0 : _b.setOperationName(ctx.requestHandlerName);
19
22
  if (!constants_1.LINKED) {
20
23
  (_c = process.send) === null || _c === void 0 ? void 0 : _c.call(process, BROADCAST_STATUS_TRACK);
21
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vtex/api",
3
- "version": "7.4.2-beta.1",
3
+ "version": "7.5.0",
4
4
  "description": "VTEX I/O API client",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
@@ -54,7 +54,7 @@
54
54
  "@types/koa": "^2.11.0",
55
55
  "@types/koa-compose": "^3.2.3",
56
56
  "@vtex/diagnostics-nodejs": "0.1.8-io",
57
- "@vtex/diagnostics-semconv": "^1.1.2",
57
+ "@vtex/diagnostics-semconv": "5.5.2",
58
58
  "@vtex/node-error-report": "^0.0.3",
59
59
  "@wry/equality": "^0.1.9",
60
60
  "agentkeepalive": "^4.0.2",