@adalo/metrics 0.0.0-staging.19 → 0.0.0-staging.21
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/README.md +1 -1
- package/lib/metrics/httpMetricsRedisCollector.d.ts.map +1 -1
- package/lib/metrics/httpMetricsRedisCollector.js +1 -23
- package/lib/metrics/httpMetricsRedisCollector.js.map +1 -1
- package/lib/metrics/httpMetricsRedisStore.d.ts +3 -0
- package/lib/metrics/httpMetricsRedisStore.d.ts.map +1 -1
- package/lib/metrics/httpMetricsRedisStore.js +3 -25
- package/lib/metrics/httpMetricsRedisStore.js.map +1 -1
- package/package.json +1 -1
- package/src/metrics/httpMetricsRedisCollector.js +1 -26
- package/src/metrics/httpMetricsRedisStore.js +3 -60
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ new MetricsClient({
|
|
|
31
31
|
|
|
32
32
|
### HTTP metrics: `MetricsClient` vs Redis
|
|
33
33
|
|
|
34
|
-
**`MetricsClient`** only registers **in-process** `app_requests_*` counters when `METRICS_HTTP_ENABLED` / `httpMetricsEnabled` is on. For **Redis-backed** HTTP aggregation (multi-web / cluster), use **`HttpMetricsRedisRecorder`** (writers) and **`HttpMetricsRedisCollector`** (drain + push) with an injected **`redisClient`** — same idea as `RedisMetricsClient`, not mixed into `MetricsClient`.
|
|
34
|
+
**`MetricsClient`** only registers **in-process** `app_requests_*` counters when `METRICS_HTTP_ENABLED` / `httpMetricsEnabled` is on. For **Redis-backed** HTTP aggregation (multi-web / cluster), use **`HttpMetricsRedisRecorder`** (writers) and **`HttpMetricsRedisCollector`** (drain + push) with an injected **`redisClient`** — same idea as `RedisMetricsClient`, not mixed into `MetricsClient`. See **`docs/http-metrics-redis.md`** for key segments and what is stored in Redis.
|
|
35
35
|
|
|
36
36
|
`DatabaseMetricsClient` / `QueueRedisMetricsClient` / `RedisMetricsClient` call **`process.exit(0)` with no logs** if `BUILD_DYNO_PROCESS_TYPE` (or `processType`) does not match `database-metrics` / `queue-metrics` / (`redis-metrics` or `queue-metrics`) respectively.
|
|
37
37
|
## Example Usage
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpMetricsRedisCollector.d.ts","sourceRoot":"","sources":["../../src/metrics/httpMetricsRedisCollector.js"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"httpMetricsRedisCollector.d.ts","sourceRoot":"","sources":["../../src/metrics/httpMetricsRedisCollector.js"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AACH;IACE;;;;;;;;;;;;;;;;OAgBG;IACH;qBAfW,OAAO,OAAO,EAAE,WAAW;;;;;;;;;;;;;;mBAoErC;IAhCC,8BAKE;CAgDL"}
|
|
@@ -1,22 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
const cluster = require('cluster');
|
|
4
3
|
const {
|
|
5
4
|
BaseMetricsClient
|
|
6
5
|
} = require('./baseMetricsClient');
|
|
7
6
|
const {
|
|
8
7
|
HttpMetricsRedisStore
|
|
9
8
|
} = require('./httpMetricsRedisStore');
|
|
10
|
-
function clusterWorkerTag() {
|
|
11
|
-
try {
|
|
12
|
-
if (cluster.isWorker && cluster.worker) {
|
|
13
|
-
return ` cluster_worker_id=${cluster.worker.id}`;
|
|
14
|
-
}
|
|
15
|
-
} catch (_) {
|
|
16
|
-
/* ignore */
|
|
17
|
-
}
|
|
18
|
-
return '';
|
|
19
|
-
}
|
|
20
9
|
|
|
21
10
|
/**
|
|
22
11
|
* Drain worker: reads HTTP aggregates from Redis (written by {@link HttpMetricsRedisRecorder}),
|
|
@@ -85,21 +74,10 @@ class HttpMetricsRedisCollector extends BaseMetricsClient {
|
|
|
85
74
|
* @returns {Promise<void>}
|
|
86
75
|
*/
|
|
87
76
|
pushMetrics = async () => {
|
|
88
|
-
const {
|
|
89
|
-
pid
|
|
90
|
-
} = process;
|
|
91
|
-
const clusterTag = clusterWorkerTag();
|
|
92
|
-
// --- TEMP_HTTP_METRICS_DIAG: remove when done debugging ---
|
|
93
|
-
console.warn(`[TEMP_HTTP_METRICS_DIAG] http_metrics_publish_start pid=${pid}${clusterTag} dyno_id=${this.dynoId} process_type=${this.processType} app=${this.appName}`);
|
|
94
|
-
// --- end TEMP_HTTP_METRICS_DIAG ---
|
|
95
77
|
if (this._store && this.countersFunctions?.app_requests_total && this.countersFunctions?.app_requests_total_duration) {
|
|
96
78
|
await this._store.flushToCounters((labels, value) => this.countersFunctions.app_requests_total(labels, value), (labels, value) => this.countersFunctions.app_requests_total_duration(labels, value));
|
|
97
79
|
}
|
|
98
|
-
|
|
99
|
-
// --- TEMP_HTTP_METRICS_DIAG: remove when done debugging ---
|
|
100
|
-
console.warn(`[TEMP_HTTP_METRICS_DIAG] http_metrics_publish_finished pid=${pid}${clusterTag} dyno_id=${this.dynoId} (registry POST to VM-agent / import completed for this tick)`);
|
|
101
|
-
// --- end TEMP_HTTP_METRICS_DIAG ---
|
|
102
|
-
return out;
|
|
80
|
+
return this._pushMetrics();
|
|
103
81
|
};
|
|
104
82
|
}
|
|
105
83
|
module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpMetricsRedisCollector.js","names":["
|
|
1
|
+
{"version":3,"file":"httpMetricsRedisCollector.js","names":["BaseMetricsClient","require","HttpMetricsRedisStore","HttpMetricsRedisCollector","constructor","config","redisClient","Error","blockNodeDefaultMetrics","keyProcessType","redisProcessTypeForKeys","process","env","METRICS_HTTP_REDIS_KEY_PROCESS_TYPE","defaultLabelsWithoutDynoId","app","appName","process_type","_store","processType","ttlSec","createCounter","name","help","labelNames","withDefaultLabelsWithoutDynoId","useLabelsWithoutDynoId","pushMetrics","countersFunctions","app_requests_total","app_requests_total_duration","flushToCounters","labels","value","_pushMetrics","module","exports"],"sources":["../../src/metrics/httpMetricsRedisCollector.js"],"sourcesContent":["const { BaseMetricsClient } = require('./baseMetricsClient')\nconst { HttpMetricsRedisStore } = require('./httpMetricsRedisStore')\n\n/**\n * Drain worker: reads HTTP aggregates from Redis (written by {@link HttpMetricsRedisRecorder}),\n * applies them to `app_requests_*` counters, then pushes the registry to the VM-agent (same as {@link BaseMetricsClient}).\n * Always passes `blockNodeDefaultMetrics: true` to the base client (HTTP-only registry; no default Node heap/event-loop metrics).\n * Redis key segment must match writers (`appName` + `processType` / {@link HttpMetricsRedisStore}).\n *\n * @extends BaseMetricsClient\n */\nclass HttpMetricsRedisCollector extends BaseMetricsClient {\n /**\n * @param {Object} [config]\n * @param {import('redis').RedisClient} config.redisClient **Required.** Injected client (same pattern as {@link RedisMetricsClient}).\n * @param {string} [config.appName] Application name (defaults per {@link BaseMetricsClient})\n * @param {string} [config.dynoId] Dyno/instance ID\n * @param {string} [config.processType] Label `process_type` on push (default from env / base)\n * @param {boolean} [config.enabled] Enable collection and push\n * @param {boolean} [config.logValues] Log metric JSON to console\n * @param {string} [config.pushgatewayUrl] VM-agent import URL\n * @param {string} [config.pushgatewaySecret] Basic auth secret (Base64)\n * @param {number} [config.intervalSec] Push interval (seconds)\n * @param {boolean} [config.removeOldMetrics] Clear old series on shutdown where supported\n * @param {function} [config.startupValidation] Run before first push\n * @param {boolean} [config.disablePushgateway] Skip POST to VM-agent\n * @param {string} [config.redisProcessTypeForKeys] Segment in Redis keys for HTTP hashes (default `web`; env `METRICS_HTTP_REDIS_KEY_PROCESS_TYPE` overrides)\n * @param {number} [config.ttlSec] Passed to {@link HttpMetricsRedisStore} (should match writers)\n */\n constructor(config = {}) {\n const { redisClient } = config\n if (redisClient == null) {\n throw new Error('HttpMetricsRedisCollector: redisClient is required')\n }\n\n super({\n ...config,\n blockNodeDefaultMetrics: true,\n })\n\n const keyProcessType =\n config.redisProcessTypeForKeys ||\n process.env.METRICS_HTTP_REDIS_KEY_PROCESS_TYPE ||\n 'web'\n\n this.defaultLabelsWithoutDynoId = {\n app: this.appName,\n process_type: keyProcessType,\n }\n\n this._store = new HttpMetricsRedisStore({\n redisClient,\n appName: this.appName,\n processType: keyProcessType,\n ttlSec: config.ttlSec,\n })\n\n this.createCounter({\n name: 'app_requests_total',\n help: 'Total number of HTTP requests',\n labelNames: this.withDefaultLabelsWithoutDynoId([\n 'method',\n 'route',\n 'appId',\n 'databaseId',\n 'status_code',\n ]),\n useLabelsWithoutDynoId: true,\n })\n\n this.createCounter({\n name: 'app_requests_total_duration',\n help: 'Total duration of HTTP requests in milliseconds',\n labelNames: this.withDefaultLabelsWithoutDynoId([\n 'method',\n 'route',\n 'appId',\n 'databaseId',\n 'status_code',\n ]),\n useLabelsWithoutDynoId: true,\n })\n }\n\n /**\n * Drains Redis into counters, then runs gauge updates and VM-agent push ({@link BaseMetricsClient#_pushMetrics}).\n * @returns {Promise<void>}\n */\n pushMetrics = async () => {\n if (\n this._store &&\n this.countersFunctions?.app_requests_total &&\n this.countersFunctions?.app_requests_total_duration\n ) {\n await this._store.flushToCounters(\n (labels, value) =>\n this.countersFunctions.app_requests_total(labels, value),\n (labels, value) =>\n this.countersFunctions.app_requests_total_duration(labels, value)\n )\n }\n return this._pushMetrics()\n }\n}\n\nmodule.exports = { HttpMetricsRedisCollector }\n"],"mappings":";;AAAA,MAAM;EAAEA;AAAkB,CAAC,GAAGC,OAAO,CAAC,qBAAqB,CAAC;AAC5D,MAAM;EAAEC;AAAsB,CAAC,GAAGD,OAAO,CAAC,yBAAyB,CAAC;;AAEpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAME,yBAAyB,SAASH,iBAAiB,CAAC;EACxD;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEI,WAAWA,CAACC,MAAM,GAAG,CAAC,CAAC,EAAE;IACvB,MAAM;MAAEC;IAAY,CAAC,GAAGD,MAAM;IAC9B,IAAIC,WAAW,IAAI,IAAI,EAAE;MACvB,MAAM,IAAIC,KAAK,CAAC,oDAAoD,CAAC;IACvE;IAEA,KAAK,CAAC;MACJ,GAAGF,MAAM;MACTG,uBAAuB,EAAE;IAC3B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EC,KAAK,KACZ,IAAI,CAACL,iBAAiB,CAACE,2BAA2B,CAACE,MAAM,EAAEC,KAAK,CACpE,CAAC;IACH;IACA,OAAO,IAAI,CAACC,YAAY,CAAC,CAAC;EAC5B,CAAC;AACH;AAEAC,MAAM,CAACC,OAAO,GAAG;EAAEjC;AAA0B,CAAC","ignoreList":[]}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Redis HTTP aggregate store. Uses an **injected** client (same pattern as {@link RedisMetricsClient}).
|
|
3
3
|
* Expects `redis` v3-style API: `multi().hincrby().expire().exec(cb)`, `eval`, `set`, `del`.
|
|
4
|
+
*
|
|
5
|
+
* **Stored metrics:** two hashes per app/segment — `:count` (HINCRBY per route group) and `:dur`
|
|
6
|
+
* (sum of duration ms per same field). Hash field = `method\\x1eroute\\x1estatus\\x1eappId\\x1edatabaseId`.
|
|
4
7
|
*/
|
|
5
8
|
export class HttpMetricsRedisStore {
|
|
6
9
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpMetricsRedisStore.d.ts","sourceRoot":"","sources":["../../src/metrics/httpMetricsRedisStore.js"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"httpMetricsRedisStore.d.ts","sourceRoot":"","sources":["../../src/metrics/httpMetricsRedisStore.js"],"names":[],"mappings":"AAwDA;;;;;;GAMG;AACH;IACE;;;;;;OAMG;IACH;QAL6C,WAAW,EAA7C,OAAO,OAAO,EAAE,WAAW;QACd,OAAO,EAApB,MAAM;QACO,WAAW,EAAxB,MAAM;QACQ,MAAM;OAiB9B;IAXC,qCAA0B;IAC1B,eAGwC;IAIxC,iBAAiD;IACjD,eAA6C;IAC7C,gBAAqD;IAGvD;;;OAGG;IACH,sBAEC;IAED;;;;;;;OAOG;IACH,eAPW,MAAM,SACN,MAAM,cACN,MAAM,SACN,MAAM,cACN,MAAM,cACN,MAAM,QAqBhB;IAED;;;;OAIG;IACH,qCAJoB,MAAM,SAAS,MAAM,KAAK,IAAI,0BAC9B,MAAM,SAAS,MAAM,KAAK,IAAI,GACrC,QAAQ,OAAO,CAAC,CA6E5B;CACF;AA7KD;;;;;;;GAOG;AACH,sCAPW,MAAM,SACN,MAAM,cACN,MAAM,SACN,MAAM,cACN,MAAM,GACJ,MAAM,CAIlB;AA3CD;;;GAGG;AACH,wBAFU,MAAM,CAEQ;AAiBxB;;GAEG;AACH,wCAFa,OAAO,CASnB;AAzBD;;;GAGG;AACH,iDAFU,MAAM,CAE8B"}
|
|
@@ -54,18 +54,12 @@ function hgetallPairsToObject(pairs) {
|
|
|
54
54
|
return o;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** --- TEMP_HTTP_METRICS_DIAG: delete this helper and all calls when done debugging --- */
|
|
58
|
-
function tempHttpDiagLog(message) {
|
|
59
|
-
console.warn(`[TEMP_HTTP_METRICS_DIAG] ${message}`);
|
|
60
|
-
}
|
|
61
|
-
function truncateForDiag(s, maxLen = 220) {
|
|
62
|
-
const t = String(s);
|
|
63
|
-
return t.length > maxLen ? `${t.slice(0, maxLen - 3)}...` : t;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
57
|
/**
|
|
67
58
|
* Redis HTTP aggregate store. Uses an **injected** client (same pattern as {@link RedisMetricsClient}).
|
|
68
59
|
* Expects `redis` v3-style API: `multi().hincrby().expire().exec(cb)`, `eval`, `set`, `del`.
|
|
60
|
+
*
|
|
61
|
+
* **Stored metrics:** two hashes per app/segment — `:count` (HINCRBY per route group) and `:dur`
|
|
62
|
+
* (sum of duration ms per same field). Hash field = `method\\x1eroute\\x1estatus\\x1eappId\\x1edatabaseId`.
|
|
69
63
|
*/
|
|
70
64
|
class HttpMetricsRedisStore {
|
|
71
65
|
/**
|
|
@@ -113,7 +107,6 @@ class HttpMetricsRedisStore {
|
|
|
113
107
|
const client = this._ensureClient();
|
|
114
108
|
const field = buildFieldKey(method, route, statusCode, appId, databaseId);
|
|
115
109
|
const dur = Math.max(0, Math.round(Number(durationMs) || 0));
|
|
116
|
-
tempHttpDiagLog(`http_redis_write_prepare pid=${process.pid} countKey=${this.countKey} durKey=${this.durKey} hincr_field=${truncateForDiag(field)} durationMs=${dur}`);
|
|
117
110
|
client.multi().hincrby(this.countKey, field, 1).hincrby(this.durKey, field, dur).expire(this.countKey, this.ttlSec).expire(this.durKey, this.ttlSec).exec(err => {
|
|
118
111
|
if (err) {
|
|
119
112
|
console.error('[HttpMetricsRedisStore] record failed:', err.message);
|
|
@@ -140,7 +133,6 @@ class HttpMetricsRedisStore {
|
|
|
140
133
|
return new Promise(resolve => {
|
|
141
134
|
client.set(this.lockKey, '1', 'EX', 25, 'NX', (setErr, ok) => {
|
|
142
135
|
if (setErr || ok !== 'OK') {
|
|
143
|
-
tempHttpDiagLog(`http_redis_drain_skip pid=${process.pid} countKey=${this.countKey} reason=${setErr ? setErr.message : 'lock_not_held'}`);
|
|
144
136
|
resolve(false);
|
|
145
137
|
return;
|
|
146
138
|
}
|
|
@@ -150,22 +142,17 @@ class HttpMetricsRedisStore {
|
|
|
150
142
|
};
|
|
151
143
|
if (evalErr) {
|
|
152
144
|
console.error('[HttpMetricsRedisStore] drain failed:', evalErr.message);
|
|
153
|
-
tempHttpDiagLog(`http_redis_drain_got_error pid=${process.pid} message=${evalErr.message}`);
|
|
154
145
|
finish();
|
|
155
146
|
return;
|
|
156
147
|
}
|
|
157
148
|
try {
|
|
158
149
|
if (!raw || !Array.isArray(raw) || raw.length < 2) {
|
|
159
|
-
tempHttpDiagLog(`http_redis_drain_collected pid=${process.pid} countKey=${this.countKey} hash_fields=0 sum_request_counts=0 (empty — keys deleted or no data)`);
|
|
160
150
|
finish();
|
|
161
151
|
return;
|
|
162
152
|
}
|
|
163
153
|
const counts = hgetallPairsToObject(raw[0]);
|
|
164
154
|
const durs = hgetallPairsToObject(raw[1]);
|
|
165
155
|
const fieldKeys = Object.keys(counts);
|
|
166
|
-
let totalUnits = 0;
|
|
167
|
-
let appliedGroups = 0;
|
|
168
|
-
const samples = [];
|
|
169
156
|
for (const field of fieldKeys) {
|
|
170
157
|
const count = parseInt(counts[field], 10);
|
|
171
158
|
if (!count || count < 1) {
|
|
@@ -176,12 +163,7 @@ class HttpMetricsRedisStore {
|
|
|
176
163
|
if (parts.length !== 5) {
|
|
177
164
|
continue;
|
|
178
165
|
}
|
|
179
|
-
totalUnits += count;
|
|
180
|
-
appliedGroups += 1;
|
|
181
166
|
const [m, route, statusStr, aid, did] = parts;
|
|
182
|
-
if (samples.length < 4) {
|
|
183
|
-
samples.push(`${m} ${route} ${statusStr} x${count}`);
|
|
184
|
-
}
|
|
185
167
|
const labels = {
|
|
186
168
|
method: m,
|
|
187
169
|
route,
|
|
@@ -194,12 +176,8 @@ class HttpMetricsRedisStore {
|
|
|
194
176
|
applyDuration(labels, dur);
|
|
195
177
|
}
|
|
196
178
|
}
|
|
197
|
-
const emptyHint = fieldKeys.length === 0 ? 'no_hash_entries' : totalUnits === 0 ? 'entries_present_but_zero_counts' : 'ok';
|
|
198
|
-
const noTrafficHint = fieldKeys.length === 0 ? ' | if web had traffic: check web uses HttpMetricsRedisRecorder (METRICS_HTTP_ENABLED, not METRICS_HTTP_USE_BUILTIN_COUNTERS), same REDIS, BUILD_APP_NAME, key segment `web`' : '';
|
|
199
|
-
tempHttpDiagLog(`http_redis_drain_collected pid=${process.pid} countKey=${this.countKey} durKey=${this.durKey} hash_fields_read=${fieldKeys.length} label_groups_applied=${appliedGroups} sum_request_counts=${totalUnits} state=${emptyHint} sample=${samples.join(' | ') || '—'}${noTrafficHint}`);
|
|
200
179
|
} catch (e) {
|
|
201
180
|
console.error('[HttpMetricsRedisStore] flush apply failed:', e.message);
|
|
202
|
-
tempHttpDiagLog(`http_redis_drain_apply_failed pid=${process.pid} ${e.message}`);
|
|
203
181
|
}
|
|
204
182
|
finish();
|
|
205
183
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpMetricsRedisStore.js","names":["FIELD_SEP","DEFAULT_HTTP_METRICS_REDIS_TTL_SEC","DRAIN_LUA","isRedisPeerInstalled","require","resolve","buildFieldKey","method","route","statusCode","appId","databaseId","String","join","hgetallPairsToObject","pairs","o","length","i","tempHttpDiagLog","message","console","warn","truncateForDiag","s","maxLen","t","slice","HttpMetricsRedisStore","constructor","redisClient","appName","processType","ttlSec","Error","_client","keySeg","encodeURIComponent","countKey","durKey","lockKey","_ensureClient","record","durationMs","client","field","dur","Math","max","round","Number","process","pid","multi","hincrby","expire","exec","err","error","e","flushToCounters","applyCount","applyDuration","Promise","set","setErr","ok","eval","evalErr","raw","finish","del","Array","isArray","counts","durs","fieldKeys","Object","keys","totalUnits","appliedGroups","samples","count","parseInt","parts","split","m","statusStr","aid","did","push","labels","status_code","emptyHint","noTrafficHint","module","exports"],"sources":["../../src/metrics/httpMetricsRedisStore.js"],"sourcesContent":["/**\n * Record separator for hash fields (avoids collisions when route contains \"|\").\n * @type {string}\n */\nconst FIELD_SEP = '\\x1e'\n\n/**\n * Default Redis key TTL in seconds (sliding: refreshed on each `record` write).\n * @type {number}\n */\nconst DEFAULT_HTTP_METRICS_REDIS_TTL_SEC = 120\n\nconst DRAIN_LUA = `\nlocal function drain(key)\n local v = redis.call('HGETALL', key)\n redis.call('DEL', key)\n return v\nend\nreturn {drain(KEYS[1]), drain(KEYS[2])}\n`\n\n/**\n * @returns {boolean} Whether the `redis` npm package is resolvable (optional peer).\n */\nfunction isRedisPeerInstalled() {\n try {\n require.resolve('redis')\n return true\n } catch {\n return false\n }\n}\n\n/**\n * @param {string} method\n * @param {string} route\n * @param {number} statusCode\n * @param {string} appId\n * @param {string} databaseId\n * @returns {string}\n */\nfunction buildFieldKey(method, route, statusCode, appId, databaseId) {\n return [method, route, String(statusCode), appId, databaseId].join(FIELD_SEP)\n}\n\nfunction hgetallPairsToObject(pairs) {\n const o = {}\n if (!pairs || !pairs.length) {\n return o\n }\n for (let i = 0; i < pairs.length; i += 2) {\n o[pairs[i]] = pairs[i + 1]\n }\n return o\n}\n\n/** --- TEMP_HTTP_METRICS_DIAG: delete this helper and all calls when done debugging --- */\nfunction tempHttpDiagLog(message) {\n console.warn(`[TEMP_HTTP_METRICS_DIAG] ${message}`)\n}\n\nfunction truncateForDiag(s, maxLen = 220) {\n const t = String(s)\n return t.length > maxLen ? `${t.slice(0, maxLen - 3)}...` : t\n}\n\n/**\n * Redis HTTP aggregate store. Uses an **injected** client (same pattern as {@link RedisMetricsClient}).\n * Expects `redis` v3-style API: `multi().hincrby().expire().exec(cb)`, `eval`, `set`, `del`.\n */\nclass HttpMetricsRedisStore {\n /**\n * @param {Object} opts\n * @param {import('redis').RedisClient} opts.redisClient\n * @param {string} opts.appName BUILD_APP_NAME (key segment)\n * @param {string} opts.processType logical process for key (e.g. web)\n * @param {number} [opts.ttlSec] Expire keys after this many seconds (default 120)\n */\n constructor({ redisClient, appName, processType, ttlSec }) {\n if (redisClient == null) {\n throw new Error('HttpMetricsRedisStore: redisClient is required')\n }\n this._client = redisClient\n this.ttlSec =\n typeof ttlSec === 'number' && ttlSec > 0\n ? ttlSec\n : DEFAULT_HTTP_METRICS_REDIS_TTL_SEC\n const keySeg = `${encodeURIComponent(appName)}:${encodeURIComponent(\n processType\n )}`\n this.countKey = `metrics:http:v2:${keySeg}:count`\n this.durKey = `metrics:http:v2:${keySeg}:dur`\n this.lockKey = `metrics:http:v2:${keySeg}:drain_lock`\n }\n\n /**\n * @returns {import('redis').RedisClient}\n * @private\n */\n _ensureClient() {\n return this._client\n }\n\n /**\n * @param {string} method\n * @param {string} route\n * @param {number} statusCode\n * @param {string} appId\n * @param {string} databaseId\n * @param {number} durationMs\n */\n record(method, route, statusCode, appId, databaseId, durationMs) {\n try {\n const client = this._ensureClient()\n const field = buildFieldKey(method, route, statusCode, appId, databaseId)\n const dur = Math.max(0, Math.round(Number(durationMs) || 0))\n tempHttpDiagLog(\n `http_redis_write_prepare pid=${process.pid} countKey=${\n this.countKey\n } durKey=${this.durKey} hincr_field=${truncateForDiag(\n field\n )} durationMs=${dur}`\n )\n client\n .multi()\n .hincrby(this.countKey, field, 1)\n .hincrby(this.durKey, field, dur)\n .expire(this.countKey, this.ttlSec)\n .expire(this.durKey, this.ttlSec)\n .exec(err => {\n if (err) {\n console.error('[HttpMetricsRedisStore] record failed:', err.message)\n }\n })\n } catch (e) {\n console.error('[HttpMetricsRedisStore] record:', e.message)\n }\n }\n\n /**\n * @param {(labels: Object, value: number) => void} applyCount\n * @param {(labels: Object, value: number) => void} applyDuration\n * @returns {Promise<boolean>}\n */\n flushToCounters(applyCount, applyDuration) {\n let client\n try {\n client = this._ensureClient()\n } catch (e) {\n console.error('[HttpMetricsRedisStore] flush:', e.message)\n return Promise.resolve(false)\n }\n return new Promise(resolve => {\n client.set(this.lockKey, '1', 'EX', 25, 'NX', (setErr, ok) => {\n if (setErr || ok !== 'OK') {\n tempHttpDiagLog(\n `http_redis_drain_skip pid=${process.pid} countKey=${\n this.countKey\n } reason=${setErr ? setErr.message : 'lock_not_held'}`\n )\n resolve(false)\n return\n }\n client.eval(\n DRAIN_LUA,\n 2,\n this.countKey,\n this.durKey,\n (evalErr, raw) => {\n const finish = () => {\n client.del(this.lockKey, () => resolve(true))\n }\n\n if (evalErr) {\n console.error(\n '[HttpMetricsRedisStore] drain failed:',\n evalErr.message\n )\n tempHttpDiagLog(\n `http_redis_drain_got_error pid=${process.pid} message=${evalErr.message}`\n )\n finish()\n return\n }\n\n try {\n if (!raw || !Array.isArray(raw) || raw.length < 2) {\n tempHttpDiagLog(\n `http_redis_drain_collected pid=${process.pid} countKey=${\n this.countKey\n } hash_fields=0 sum_request_counts=0 (empty — keys deleted or no data)`\n )\n finish()\n return\n }\n const counts = hgetallPairsToObject(raw[0])\n const durs = hgetallPairsToObject(raw[1])\n const fieldKeys = Object.keys(counts)\n let totalUnits = 0\n let appliedGroups = 0\n const samples = []\n for (const field of fieldKeys) {\n const count = parseInt(counts[field], 10)\n if (!count || count < 1) {\n continue\n }\n const dur = parseInt(durs[field] || '0', 10) || 0\n const parts = field.split(FIELD_SEP)\n if (parts.length !== 5) {\n continue\n }\n totalUnits += count\n appliedGroups += 1\n const [m, route, statusStr, aid, did] = parts\n if (samples.length < 4) {\n samples.push(`${m} ${route} ${statusStr} x${count}`)\n }\n const labels = {\n method: m,\n route,\n status_code: statusStr,\n appId: aid,\n databaseId: did,\n }\n applyCount(labels, count)\n if (dur > 0) {\n applyDuration(labels, dur)\n }\n }\n const emptyHint =\n fieldKeys.length === 0\n ? 'no_hash_entries'\n : totalUnits === 0\n ? 'entries_present_but_zero_counts'\n : 'ok'\n const noTrafficHint =\n fieldKeys.length === 0\n ? ' | if web had traffic: check web uses HttpMetricsRedisRecorder (METRICS_HTTP_ENABLED, not METRICS_HTTP_USE_BUILTIN_COUNTERS), same REDIS, BUILD_APP_NAME, key segment `web`'\n : ''\n tempHttpDiagLog(\n `http_redis_drain_collected pid=${process.pid} countKey=${\n this.countKey\n } durKey=${this.durKey} hash_fields_read=${\n fieldKeys.length\n } label_groups_applied=${appliedGroups} sum_request_counts=${totalUnits} state=${emptyHint} sample=${samples.join(\n ' | '\n ) || '—'}${noTrafficHint}`\n )\n } catch (e) {\n console.error(\n '[HttpMetricsRedisStore] flush apply failed:',\n e.message\n )\n tempHttpDiagLog(\n `http_redis_drain_apply_failed pid=${process.pid} ${e.message}`\n )\n }\n finish()\n }\n )\n })\n })\n }\n}\n\nmodule.exports = {\n HttpMetricsRedisStore,\n buildFieldKey,\n FIELD_SEP,\n isRedisPeerInstalled,\n DEFAULT_HTTP_METRICS_REDIS_TTL_SEC,\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA,MAAMA,SAAS,GAAG,MAAM;;AAExB;AACA;AACA;AACA;AACA,MAAMC,kCAAkC,GAAG,GAAG;AAE9C,MAAMC,SAAS,GAAG;AAClB;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA,SAASC,oBAAoBA,CAAA,EAAG;EAC9B,IAAI;IACFC,OAAO,CAACC,OAAO,CA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OAAO,CAACC,GAAG,aAC3C,IAAI,CAACd,QAAQ,WACJ,IAAI,CAACC,MAAM,qBACpBqC,SAAS,CAAC3D,MAAM,yBACO+D,aAAa,uBAAuBD,UAAU,UAAUc,SAAS,WAAWZ,OAAO,CAACpE,IAAI,CAC/G,KACF,CAAC,IAAI,GAAG,GAAGiF,aAAa,EAC1B,CAAC;UACH,CAAC,CAAC,OAAOnC,CAAC,EAAE;YACVtC,OAAO,CAACqC,KAAK,CACX,6CAA6C,EAC7CC,CAAC,CAACvC,OACJ,CAAC;YACDD,eAAe,CACb,qCAAqCgC,OAAO,CAACC,GAAG,IAAIO,CAAC,CAACvC,OAAO,EAC/D,CAAC;UACH;UACAkD,MAAM,CAAC,CAAC;QACV,CACF,CAAC;MACH,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;AACF;AAEAyB,MAAM,CAACC,OAAO,GAAG;EACfpE,qBAAqB;EACrBtB,aAAa;EACbN,SAAS;EACTG,oBAAoB;EACpBF;AACF,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"httpMetricsRedisStore.js","names":["FIELD_SEP","DEFAULT_HTTP_METRICS_REDIS_TTL_SEC","DRAIN_LUA","isRedisPeerInstalled","require","resolve","buildFieldKey","method","route","statusCode","appId","databaseId","String","join","hgetallPairsToObject","pairs","o","length","i","HttpMetricsRedisStore","constructor","redisClient","appName","processType","ttlSec","Error","_client","keySeg","encodeURIComponent","countKey","durKey","lockKey","_ensureClient","record","durationMs","client","field","dur","Math","max","round","Number","multi","hincrby","expire","exec","err","console","error","message","e","flushToCounters","applyCount","applyDuration","Promise","set","setErr","ok","eval","evalErr","raw","finish","del","Array","isArray","counts","durs","fieldKeys","Object","keys","count","parseInt","parts","split","m","statusStr","aid","did","labels","status_code","module","exports"],"sources":["../../src/metrics/httpMetricsRedisStore.js"],"sourcesContent":["/**\n * Record separator for hash fields (avoids collisions when route contains \"|\").\n * @type {string}\n */\nconst FIELD_SEP = '\\x1e'\n\n/**\n * Default Redis key TTL in seconds (sliding: refreshed on each `record` write).\n * @type {number}\n */\nconst DEFAULT_HTTP_METRICS_REDIS_TTL_SEC = 120\n\nconst DRAIN_LUA = `\nlocal function drain(key)\n local v = redis.call('HGETALL', key)\n redis.call('DEL', key)\n return v\nend\nreturn {drain(KEYS[1]), drain(KEYS[2])}\n`\n\n/**\n * @returns {boolean} Whether the `redis` npm package is resolvable (optional peer).\n */\nfunction isRedisPeerInstalled() {\n try {\n require.resolve('redis')\n return true\n } catch {\n return false\n }\n}\n\n/**\n * @param {string} method\n * @param {string} route\n * @param {number} statusCode\n * @param {string} appId\n * @param {string} databaseId\n * @returns {string}\n */\nfunction buildFieldKey(method, route, statusCode, appId, databaseId) {\n return [method, route, String(statusCode), appId, databaseId].join(FIELD_SEP)\n}\n\nfunction hgetallPairsToObject(pairs) {\n const o = {}\n if (!pairs || !pairs.length) {\n return o\n }\n for (let i = 0; i < pairs.length; i += 2) {\n o[pairs[i]] = pairs[i + 1]\n }\n return o\n}\n\n/**\n * Redis HTTP aggregate store. Uses an **injected** client (same pattern as {@link RedisMetricsClient}).\n * Expects `redis` v3-style API: `multi().hincrby().expire().exec(cb)`, `eval`, `set`, `del`.\n *\n * **Stored metrics:** two hashes per app/segment — `:count` (HINCRBY per route group) and `:dur`\n * (sum of duration ms per same field). Hash field = `method\\\\x1eroute\\\\x1estatus\\\\x1eappId\\\\x1edatabaseId`.\n */\nclass HttpMetricsRedisStore {\n /**\n * @param {Object} opts\n * @param {import('redis').RedisClient} opts.redisClient\n * @param {string} opts.appName BUILD_APP_NAME (key segment)\n * @param {string} opts.processType logical process for key (e.g. web)\n * @param {number} [opts.ttlSec] Expire keys after this many seconds (default 120)\n */\n constructor({ redisClient, appName, processType, ttlSec }) {\n if (redisClient == null) {\n throw new Error('HttpMetricsRedisStore: redisClient is required')\n }\n this._client = redisClient\n this.ttlSec =\n typeof ttlSec === 'number' && ttlSec > 0\n ? ttlSec\n : DEFAULT_HTTP_METRICS_REDIS_TTL_SEC\n const keySeg = `${encodeURIComponent(appName)}:${encodeURIComponent(\n processType\n )}`\n this.countKey = `metrics:http:v2:${keySeg}:count`\n this.durKey = `metrics:http:v2:${keySeg}:dur`\n this.lockKey = `metrics:http:v2:${keySeg}:drain_lock`\n }\n\n /**\n * @returns {import('redis').RedisClient}\n * @private\n */\n _ensureClient() {\n return this._client\n }\n\n /**\n * @param {string} method\n * @param {string} route\n * @param {number} statusCode\n * @param {string} appId\n * @param {string} databaseId\n * @param {number} durationMs\n */\n record(method, route, statusCode, appId, databaseId, durationMs) {\n try {\n const client = this._ensureClient()\n const field = buildFieldKey(method, route, statusCode, appId, databaseId)\n const dur = Math.max(0, Math.round(Number(durationMs) || 0))\n client\n .multi()\n .hincrby(this.countKey, field, 1)\n .hincrby(this.durKey, field, dur)\n .expire(this.countKey, this.ttlSec)\n .expire(this.durKey, this.ttlSec)\n .exec(err => {\n if (err) {\n console.error('[HttpMetricsRedisStore] record failed:', err.message)\n }\n })\n } catch (e) {\n console.error('[HttpMetricsRedisStore] record:', e.message)\n }\n }\n\n /**\n * @param {(labels: Object, value: number) => void} applyCount\n * @param {(labels: Object, value: number) => void} applyDuration\n * @returns {Promise<boolean>}\n */\n flushToCounters(applyCount, applyDuration) {\n let client\n try {\n client = this._ensureClient()\n } catch (e) {\n console.error('[HttpMetricsRedisStore] flush:', e.message)\n return Promise.resolve(false)\n }\n return new Promise(resolve => {\n client.set(this.lockKey, '1', 'EX', 25, 'NX', (setErr, ok) => {\n if (setErr || ok !== 'OK') {\n resolve(false)\n return\n }\n client.eval(\n DRAIN_LUA,\n 2,\n this.countKey,\n this.durKey,\n (evalErr, raw) => {\n const finish = () => {\n client.del(this.lockKey, () => resolve(true))\n }\n\n if (evalErr) {\n console.error(\n '[HttpMetricsRedisStore] drain failed:',\n evalErr.message\n )\n finish()\n return\n }\n\n try {\n if (!raw || !Array.isArray(raw) || raw.length < 2) {\n finish()\n return\n }\n const counts = hgetallPairsToObject(raw[0])\n const durs = hgetallPairsToObject(raw[1])\n const fieldKeys = Object.keys(counts)\n for (const field of fieldKeys) {\n const count = parseInt(counts[field], 10)\n if (!count || count < 1) {\n continue\n }\n const dur = parseInt(durs[field] || '0', 10) || 0\n const parts = field.split(FIELD_SEP)\n if (parts.length !== 5) {\n continue\n }\n const [m, route, statusStr, aid, did] = parts\n const labels = {\n method: m,\n route,\n status_code: statusStr,\n appId: aid,\n databaseId: did,\n }\n applyCount(labels, count)\n if (dur > 0) {\n applyDuration(labels, dur)\n }\n }\n } catch (e) {\n console.error(\n '[HttpMetricsRedisStore] flush apply failed:',\n e.message\n )\n }\n finish()\n }\n )\n })\n })\n }\n}\n\nmodule.exports = {\n HttpMetricsRedisStore,\n buildFieldKey,\n FIELD_SEP,\n isRedisPeerInstalled,\n DEFAULT_HTTP_METRICS_REDIS_TTL_SEC,\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA,MAAMA,SAAS,GAAG,MAAM;;AAExB;AACA;AACA;AACA;AACA,MAAMC,kCAAkC,GAAG,GAAG;AAE9C,MAAMC,SAAS,GAAG;AAClB;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA,SAASC,oBAAoBA,CAAA,EAAG;EAC9B,IAAI;IACFC,OAAO,CAACC,OAAO,CAAC,OAAO,CAAC;IACxB,OAAO,IAAI;EACb,CAAC,CAAC,MAAM;IACN,OAAO,KAAK;EACd;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,aAAaA,CAACC,MAAM,EAAEC,KAAK,EAAEC,UAAU,EAAEC,KAAK,EAAEC,UAAU,EAAE;EACnE,OAAO,CAACJ,MAAM,EAAEC,KAAK,EAAEI,MAAM,CAACH,UAAU,CAAC,EAAEC,KAAK,EAAEC,UAAU,CAAC,CAACE,IAAI,CAACb,SAAS,CAAC;AAC/E;AAEA,SAASc,oBAAoBA,CAACC,KAAK,EAAE;EACnC,MAAMC,CAAC,GAAG,CAAC,CAAC;EACZ,IAAI,C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AAMjC,GAAG,GAAGkC,QAAQ,CAACL,IAAI,CAAC9B,KAAK,CAAC,IAAI,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC;cACjD,MAAMoC,KAAK,GAAGpC,KAAK,CAACqC,KAAK,CAACzE,SAAS,CAAC;cACpC,IAAIwE,KAAK,CAACvD,MAAM,KAAK,CAAC,EAAE;gBACtB;cACF;cACA,MAAM,CAACyD,CAAC,EAAElE,KAAK,EAAEmE,SAAS,EAAEC,GAAG,EAAEC,GAAG,CAAC,GAAGL,KAAK;cAC7C,MAAMM,MAAM,GAAG;gBACbvE,MAAM,EAAEmE,CAAC;gBACTlE,KAAK;gBACLuE,WAAW,EAAEJ,SAAS;gBACtBjE,KAAK,EAAEkE,GAAG;gBACVjE,UAAU,EAAEkE;cACd,CAAC;cACDzB,UAAU,CAAC0B,MAAM,EAAER,KAAK,CAAC;cACzB,IAAIjC,GAAG,GAAG,CAAC,EAAE;gBACXgB,aAAa,CAACyB,MAAM,EAAEzC,GAAG,CAAC;cAC5B;YACF;UACF,CAAC,CAAC,OAAOa,CAAC,EAAE;YACVH,OAAO,CAACC,KAAK,CACX,6CAA6C,EAC7CE,CAAC,CAACD,OACJ,CAAC;UACH;UACAY,MAAM,CAAC,CAAC;QACV,CACF,CAAC;MACH,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ;AACF;AAEAmB,MAAM,CAACC,OAAO,GAAG;EACf9D,qBAAqB;EACrBb,aAAa;EACbN,SAAS;EACTG,oBAAoB;EACpBF;AACF,CAAC","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,18 +1,6 @@
|
|
|
1
|
-
const cluster = require('cluster')
|
|
2
1
|
const { BaseMetricsClient } = require('./baseMetricsClient')
|
|
3
2
|
const { HttpMetricsRedisStore } = require('./httpMetricsRedisStore')
|
|
4
3
|
|
|
5
|
-
function clusterWorkerTag() {
|
|
6
|
-
try {
|
|
7
|
-
if (cluster.isWorker && cluster.worker) {
|
|
8
|
-
return ` cluster_worker_id=${cluster.worker.id}`
|
|
9
|
-
}
|
|
10
|
-
} catch (_) {
|
|
11
|
-
/* ignore */
|
|
12
|
-
}
|
|
13
|
-
return ''
|
|
14
|
-
}
|
|
15
|
-
|
|
16
4
|
/**
|
|
17
5
|
* Drain worker: reads HTTP aggregates from Redis (written by {@link HttpMetricsRedisRecorder}),
|
|
18
6
|
* applies them to `app_requests_*` counters, then pushes the registry to the VM-agent (same as {@link BaseMetricsClient}).
|
|
@@ -99,13 +87,6 @@ class HttpMetricsRedisCollector extends BaseMetricsClient {
|
|
|
99
87
|
* @returns {Promise<void>}
|
|
100
88
|
*/
|
|
101
89
|
pushMetrics = async () => {
|
|
102
|
-
const { pid } = process
|
|
103
|
-
const clusterTag = clusterWorkerTag()
|
|
104
|
-
// --- TEMP_HTTP_METRICS_DIAG: remove when done debugging ---
|
|
105
|
-
console.warn(
|
|
106
|
-
`[TEMP_HTTP_METRICS_DIAG] http_metrics_publish_start pid=${pid}${clusterTag} dyno_id=${this.dynoId} process_type=${this.processType} app=${this.appName}`
|
|
107
|
-
)
|
|
108
|
-
// --- end TEMP_HTTP_METRICS_DIAG ---
|
|
109
90
|
if (
|
|
110
91
|
this._store &&
|
|
111
92
|
this.countersFunctions?.app_requests_total &&
|
|
@@ -118,13 +99,7 @@ class HttpMetricsRedisCollector extends BaseMetricsClient {
|
|
|
118
99
|
this.countersFunctions.app_requests_total_duration(labels, value)
|
|
119
100
|
)
|
|
120
101
|
}
|
|
121
|
-
|
|
122
|
-
// --- TEMP_HTTP_METRICS_DIAG: remove when done debugging ---
|
|
123
|
-
console.warn(
|
|
124
|
-
`[TEMP_HTTP_METRICS_DIAG] http_metrics_publish_finished pid=${pid}${clusterTag} dyno_id=${this.dynoId} (registry POST to VM-agent / import completed for this tick)`
|
|
125
|
-
)
|
|
126
|
-
// --- end TEMP_HTTP_METRICS_DIAG ---
|
|
127
|
-
return out
|
|
102
|
+
return this._pushMetrics()
|
|
128
103
|
}
|
|
129
104
|
}
|
|
130
105
|
|
|
@@ -54,19 +54,12 @@ function hgetallPairsToObject(pairs) {
|
|
|
54
54
|
return o
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** --- TEMP_HTTP_METRICS_DIAG: delete this helper and all calls when done debugging --- */
|
|
58
|
-
function tempHttpDiagLog(message) {
|
|
59
|
-
console.warn(`[TEMP_HTTP_METRICS_DIAG] ${message}`)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
function truncateForDiag(s, maxLen = 220) {
|
|
63
|
-
const t = String(s)
|
|
64
|
-
return t.length > maxLen ? `${t.slice(0, maxLen - 3)}...` : t
|
|
65
|
-
}
|
|
66
|
-
|
|
67
57
|
/**
|
|
68
58
|
* Redis HTTP aggregate store. Uses an **injected** client (same pattern as {@link RedisMetricsClient}).
|
|
69
59
|
* Expects `redis` v3-style API: `multi().hincrby().expire().exec(cb)`, `eval`, `set`, `del`.
|
|
60
|
+
*
|
|
61
|
+
* **Stored metrics:** two hashes per app/segment — `:count` (HINCRBY per route group) and `:dur`
|
|
62
|
+
* (sum of duration ms per same field). Hash field = `method\\x1eroute\\x1estatus\\x1eappId\\x1edatabaseId`.
|
|
70
63
|
*/
|
|
71
64
|
class HttpMetricsRedisStore {
|
|
72
65
|
/**
|
|
@@ -114,13 +107,6 @@ class HttpMetricsRedisStore {
|
|
|
114
107
|
const client = this._ensureClient()
|
|
115
108
|
const field = buildFieldKey(method, route, statusCode, appId, databaseId)
|
|
116
109
|
const dur = Math.max(0, Math.round(Number(durationMs) || 0))
|
|
117
|
-
tempHttpDiagLog(
|
|
118
|
-
`http_redis_write_prepare pid=${process.pid} countKey=${
|
|
119
|
-
this.countKey
|
|
120
|
-
} durKey=${this.durKey} hincr_field=${truncateForDiag(
|
|
121
|
-
field
|
|
122
|
-
)} durationMs=${dur}`
|
|
123
|
-
)
|
|
124
110
|
client
|
|
125
111
|
.multi()
|
|
126
112
|
.hincrby(this.countKey, field, 1)
|
|
@@ -153,11 +139,6 @@ class HttpMetricsRedisStore {
|
|
|
153
139
|
return new Promise(resolve => {
|
|
154
140
|
client.set(this.lockKey, '1', 'EX', 25, 'NX', (setErr, ok) => {
|
|
155
141
|
if (setErr || ok !== 'OK') {
|
|
156
|
-
tempHttpDiagLog(
|
|
157
|
-
`http_redis_drain_skip pid=${process.pid} countKey=${
|
|
158
|
-
this.countKey
|
|
159
|
-
} reason=${setErr ? setErr.message : 'lock_not_held'}`
|
|
160
|
-
)
|
|
161
142
|
resolve(false)
|
|
162
143
|
return
|
|
163
144
|
}
|
|
@@ -176,29 +157,18 @@ class HttpMetricsRedisStore {
|
|
|
176
157
|
'[HttpMetricsRedisStore] drain failed:',
|
|
177
158
|
evalErr.message
|
|
178
159
|
)
|
|
179
|
-
tempHttpDiagLog(
|
|
180
|
-
`http_redis_drain_got_error pid=${process.pid} message=${evalErr.message}`
|
|
181
|
-
)
|
|
182
160
|
finish()
|
|
183
161
|
return
|
|
184
162
|
}
|
|
185
163
|
|
|
186
164
|
try {
|
|
187
165
|
if (!raw || !Array.isArray(raw) || raw.length < 2) {
|
|
188
|
-
tempHttpDiagLog(
|
|
189
|
-
`http_redis_drain_collected pid=${process.pid} countKey=${
|
|
190
|
-
this.countKey
|
|
191
|
-
} hash_fields=0 sum_request_counts=0 (empty — keys deleted or no data)`
|
|
192
|
-
)
|
|
193
166
|
finish()
|
|
194
167
|
return
|
|
195
168
|
}
|
|
196
169
|
const counts = hgetallPairsToObject(raw[0])
|
|
197
170
|
const durs = hgetallPairsToObject(raw[1])
|
|
198
171
|
const fieldKeys = Object.keys(counts)
|
|
199
|
-
let totalUnits = 0
|
|
200
|
-
let appliedGroups = 0
|
|
201
|
-
const samples = []
|
|
202
172
|
for (const field of fieldKeys) {
|
|
203
173
|
const count = parseInt(counts[field], 10)
|
|
204
174
|
if (!count || count < 1) {
|
|
@@ -209,12 +179,7 @@ class HttpMetricsRedisStore {
|
|
|
209
179
|
if (parts.length !== 5) {
|
|
210
180
|
continue
|
|
211
181
|
}
|
|
212
|
-
totalUnits += count
|
|
213
|
-
appliedGroups += 1
|
|
214
182
|
const [m, route, statusStr, aid, did] = parts
|
|
215
|
-
if (samples.length < 4) {
|
|
216
|
-
samples.push(`${m} ${route} ${statusStr} x${count}`)
|
|
217
|
-
}
|
|
218
183
|
const labels = {
|
|
219
184
|
method: m,
|
|
220
185
|
route,
|
|
@@ -227,33 +192,11 @@ class HttpMetricsRedisStore {
|
|
|
227
192
|
applyDuration(labels, dur)
|
|
228
193
|
}
|
|
229
194
|
}
|
|
230
|
-
const emptyHint =
|
|
231
|
-
fieldKeys.length === 0
|
|
232
|
-
? 'no_hash_entries'
|
|
233
|
-
: totalUnits === 0
|
|
234
|
-
? 'entries_present_but_zero_counts'
|
|
235
|
-
: 'ok'
|
|
236
|
-
const noTrafficHint =
|
|
237
|
-
fieldKeys.length === 0
|
|
238
|
-
? ' | if web had traffic: check web uses HttpMetricsRedisRecorder (METRICS_HTTP_ENABLED, not METRICS_HTTP_USE_BUILTIN_COUNTERS), same REDIS, BUILD_APP_NAME, key segment `web`'
|
|
239
|
-
: ''
|
|
240
|
-
tempHttpDiagLog(
|
|
241
|
-
`http_redis_drain_collected pid=${process.pid} countKey=${
|
|
242
|
-
this.countKey
|
|
243
|
-
} durKey=${this.durKey} hash_fields_read=${
|
|
244
|
-
fieldKeys.length
|
|
245
|
-
} label_groups_applied=${appliedGroups} sum_request_counts=${totalUnits} state=${emptyHint} sample=${samples.join(
|
|
246
|
-
' | '
|
|
247
|
-
) || '—'}${noTrafficHint}`
|
|
248
|
-
)
|
|
249
195
|
} catch (e) {
|
|
250
196
|
console.error(
|
|
251
197
|
'[HttpMetricsRedisStore] flush apply failed:',
|
|
252
198
|
e.message
|
|
253
199
|
)
|
|
254
|
-
tempHttpDiagLog(
|
|
255
|
-
`http_redis_drain_apply_failed pid=${process.pid} ${e.message}`
|
|
256
|
-
)
|
|
257
200
|
}
|
|
258
201
|
finish()
|
|
259
202
|
}
|