@redkern/node-red-prometheus 0.0.0-stage → 0.1.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.
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // PRM-CARD-1, PRM-CARD-2, PRM-CARD-4: per-metric series limit (existing series keep updating) and optional
4
+ // label allowlists. PRM-CARD-3 (dropped counter, yellow status) lives in registry.js and nodes/prometheus.js.
5
+
6
+ const DEFAULT_MAX_SERIES = 1000;
7
+ const OTHER = 'other';
8
+
9
+ function seriesKey(labelNames, labels) {
10
+ // Unit separator cannot appear in a valid label name and is escaped in values by JSON.
11
+ return JSON.stringify(labelNames.map((name) => labels[name]));
12
+ }
13
+
14
+ /**
15
+ * @param {{ labelNames: string[], maxSeries?: number, allowlist?: Record<string, string[]>, onDrop?: () => void }} options
16
+ */
17
+ function createCardinalityGuard({ labelNames, maxSeries = DEFAULT_MAX_SERIES, allowlist = {}, onDrop = () => {} }) {
18
+ const known = new Set();
19
+ let limit = normalizeLimit(maxSeries);
20
+ let allowed = normalizeAllowlist(allowlist);
21
+ let dropped = 0;
22
+
23
+ return {
24
+ /**
25
+ * Returns the labels to write, or null when the series must be dropped.
26
+ * @param {Record<string, string>} labels
27
+ */
28
+ admit(labels) {
29
+ const effective = {};
30
+ for (const name of labelNames) {
31
+ const value = labels[name];
32
+ const values = allowed.get(name);
33
+ effective[name] = values && !values.has(value) ? OTHER : value;
34
+ }
35
+ const key = seriesKey(labelNames, effective);
36
+ if (known.has(key)) return effective;
37
+ if (known.size >= limit) {
38
+ dropped += 1;
39
+ onDrop();
40
+ return null;
41
+ }
42
+ known.add(key);
43
+ return effective;
44
+ },
45
+ /** Applies new limits from a redeployed config node without resetting existing series (PRM-REG-3). */
46
+ update({ maxSeries: nextMax = DEFAULT_MAX_SERIES, allowlist: nextAllowlist = {} } = {}) {
47
+ limit = normalizeLimit(nextMax);
48
+ allowed = normalizeAllowlist(nextAllowlist);
49
+ },
50
+ get size() { return known.size; },
51
+ get dropped() { return dropped; },
52
+ get limit() { return limit; }
53
+ };
54
+ }
55
+
56
+ function normalizeLimit(value) {
57
+ const number = Number(value);
58
+ if (!Number.isSafeInteger(number) || number < 1) return DEFAULT_MAX_SERIES;
59
+ return number;
60
+ }
61
+
62
+ function normalizeAllowlist(allowlist) {
63
+ const map = new Map();
64
+ for (const [name, values] of Object.entries(allowlist || {})) {
65
+ if (!Array.isArray(values) || values.length === 0) continue;
66
+ map.set(name, new Set(values.map(String)));
67
+ }
68
+ return map;
69
+ }
70
+
71
+ module.exports = { createCardinalityGuard, DEFAULT_MAX_SERIES, OTHER };
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ const os = require('node:os');
4
+
5
+ // PRM-DEF-1, PRM-DEF-2, PRM-DEF-3: process/runtime metrics collected into a registry separate from user metrics, so an
6
+ // exporter can switch them off, change the prefix or the host label without touching user series.
7
+ //
8
+ // prom-client's default metrics install PerformanceObservers that are never disconnected, so one
9
+ // registry is created per (prefix, hostLabel) and reused for the life of the process.
10
+
11
+ const cache = new Map();
12
+
13
+ function hostName() {
14
+ return process.env.HOSTNAME || os.hostname();
15
+ }
16
+
17
+ /**
18
+ * @param {{ promClient: typeof import('prom-client'), prefix: string, hostLabel: boolean, deployCount: () => number }} options
19
+ */
20
+ function defaultMetricsRegistry({ promClient, prefix, hostLabel, deployCount }) {
21
+ const key = JSON.stringify([prefix, hostLabel]);
22
+ const cached = cache.get(key);
23
+ if (cached) {
24
+ cached.deployCount = deployCount;
25
+ return cached.registry;
26
+ }
27
+ const registry = new promClient.Registry();
28
+ const entry = { registry, deployCount };
29
+ const labels = hostLabel ? { host: hostName() } : undefined;
30
+ promClient.collectDefaultMetrics({ register: registry, prefix, ...(labels ? { labels } : {}) });
31
+ new promClient.Counter({
32
+ name: `${prefix}flows_deploy_total`,
33
+ help: 'Node-RED flow starts (startup and every deploy) since the process started.',
34
+ labelNames: hostLabel ? ['host'] : [],
35
+ registers: [registry],
36
+ collect() {
37
+ this.reset();
38
+ const count = entry.deployCount();
39
+ if (hostLabel) this.inc({ host: hostName() }, count);
40
+ else if (count > 0) this.inc(count);
41
+ }
42
+ });
43
+ cache.set(key, entry);
44
+ return registry;
45
+ }
46
+
47
+ function clearCache() {
48
+ cache.clear();
49
+ }
50
+
51
+ module.exports = { defaultMetricsRegistry, hostName, clearCache };
package/lib/palette.js ADDED
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ const kit = require('@redkern/node-red-kit');
4
+ const promClient = require('prom-client');
5
+ const { createMetricRegistry } = require('./registry.js');
6
+ const { createReceiver } = require('./receiver.js');
7
+ const { defaultMetricsRegistry } = require('./default-metrics.js');
8
+ const { createWarnOnce } = require('./warn-once.js');
9
+
10
+ // One palette context per Node-RED runtime, kept in the module closure (PRM-REG-1, PRM-EXP-3).
11
+
12
+ const DEFAULT_PORT = 9550;
13
+ const SETTINGS_TYPE = 'redkern-prom-exporter';
14
+ const CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
15
+ // Admin routes reject the 0.0.4 media type in kit 1.1.0 (KIT-HTTP facade); Prometheus parses plain
16
+ // text/plain as the 0.0.4 text format, so the httpAdmin mode answers with it (docs/spec.md, Deviations).
17
+ const ADMIN_CONTENT_TYPE = 'text/plain; charset=utf-8';
18
+
19
+ const palettes = new WeakMap();
20
+
21
+ function getPalette(RED) {
22
+ let palette = palettes.get(RED);
23
+ if (palette) return palette;
24
+ palette = createPalette(RED);
25
+ palettes.set(RED, palette);
26
+ return palette;
27
+ }
28
+
29
+ function createPalette(RED) {
30
+ let deployCount = 0;
31
+ let exporter;
32
+ let activeNodes = 0;
33
+
34
+ // PRM-EXP-1, PRM-EXP-4: the dedicated port is the kit internal server (createInternalServer). Its
35
+ // /metrics route has its own token class "metrics" (KIT-HTTP-6). Kit requires a declared route token at
36
+ // init, so the listener is declared only when REDKERN_PROM_METRICS_TOKEN (or the matching setting) is
37
+ // present; without it the palette still works and the admin API mode stays available.
38
+ const tokenConfigured = hasMetricsToken(RED);
39
+ const rk = kit.init(RED, {
40
+ domain: 'prom',
41
+ settingsType: SETTINGS_TYPE,
42
+ secrets: { metrics: { required: false } },
43
+ // Declared so the kit listener may answer with the 0.0.4 media type; this palette never acquires a
44
+ // source lease, it is the receiver (PRM-REG-6).
45
+ metrics: { contentType: CONTENT_TYPE, metrics: render },
46
+ ...(tokenConfigured ? {
47
+ internalServer: {
48
+ port: DEFAULT_PORT,
49
+ routes: [{
50
+ method: 'GET',
51
+ path: '/metrics',
52
+ auth: { token: 'metrics' },
53
+ handler: async (_request, response) => response.text(await render(), CONTENT_TYPE)
54
+ }]
55
+ }
56
+ } : {})
57
+ });
58
+ const log = rk.plugin({ id: 'palette' }).log;
59
+ const warn = (key, message) => log.warn(message, { key });
60
+ const warnOnce = createWarnOnce((message, meta) => log.warn(message, meta), 1024);
61
+
62
+ const metrics = createMetricRegistry({ promClient, warn });
63
+ const receiver = createReceiver({ RED, warn, warnOnce });
64
+
65
+ const onFlowsStarted = () => {
66
+ deployCount += 1;
67
+ // PRM-REG-3: metrics whose config nodes disappeared in this deploy are removed only now, so a
68
+ // config node that was stopped and started again keeps its series.
69
+ metrics.sweep();
70
+ };
71
+
72
+ function acquire() {
73
+ if (!rk.enabled) return () => {};
74
+ activeNodes += 1;
75
+ if (activeNodes === 1) {
76
+ if (RED.events && typeof RED.events.on === 'function') RED.events.on('flows:started', onFlowsStarted);
77
+ receiver.start();
78
+ }
79
+
80
+ let active = true;
81
+ return () => {
82
+ if (!active) return;
83
+ active = false;
84
+ activeNodes -= 1;
85
+ if (activeNodes === 0) {
86
+ if (RED.events && typeof RED.events.removeListener === 'function') RED.events.removeListener('flows:started', onFlowsStarted);
87
+ receiver.stop();
88
+ }
89
+ };
90
+ }
91
+
92
+ async function render() {
93
+ const texts = [];
94
+ const options = exporter?.options;
95
+ if (options?.defaultMetrics) {
96
+ const registry = defaultMetricsRegistry({
97
+ promClient,
98
+ prefix: options.prefix,
99
+ hostLabel: options.hostLabel,
100
+ deployCount: () => deployCount
101
+ });
102
+ texts.push(await registry.metrics());
103
+ }
104
+ texts.push(await metrics.metrics());
105
+ if (options?.includeGlobalRegistry) texts.push(await promClient.register.metrics());
106
+ return receiver.render(texts);
107
+ }
108
+
109
+ // Registered on first use, once per palette (PRM-EXP-3), so instances without an admin-mode exporter do not
110
+ // log the kit's missing-adminAuth warning.
111
+ let adminRoute;
112
+ const getAdminRoute = () => adminRoute || (adminRoute = rk.createRouteRegistry({
113
+ method: 'GET',
114
+ path: '/metrics',
115
+ permission: rk.names.permRead,
116
+ // Without an admin-mode exporter in the registry, kit answers 503 NO_ACTIVE_ENTRIES before this runs.
117
+ handler: async (_request, response) => {
118
+ response.text(await render(), ADMIN_CONTENT_TYPE);
119
+ }
120
+ }));
121
+
122
+ return {
123
+ RED,
124
+ rk,
125
+ log,
126
+ warn,
127
+ warnOnce,
128
+ metrics,
129
+ receiver,
130
+ tokenConfigured,
131
+ acquire,
132
+ get adminRoute() { return getAdminRoute(); },
133
+ render,
134
+ contentType: CONTENT_TYPE,
135
+ /** PRM-EXP-5: one exporter per Node-RED instance. */
136
+ claimExporter(id, options) {
137
+ if (exporter && exporter.id !== id) return false;
138
+ exporter = { id, options };
139
+ return true;
140
+ },
141
+ releaseExporter(id) {
142
+ if (exporter?.id === id) exporter = undefined;
143
+ }
144
+ };
145
+ }
146
+
147
+ function hasMetricsToken(RED) {
148
+ const env = kit.readEnv('REDKERN_PROM_METRICS_TOKEN');
149
+ if (typeof env === 'string' && env.trim() !== '') return true;
150
+ const settings = kit.readSettings(RED, SETTINGS_TYPE, { metricsToken: { type: 'str' } });
151
+ return typeof settings.metricsToken === 'string' && settings.metricsToken.trim() !== '';
152
+ }
153
+
154
+ module.exports = { getPalette, DEFAULT_PORT, SETTINGS_TYPE, CONTENT_TYPE, ADMIN_CONTENT_TYPE };
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ const { MIMEType } = require('node:util');
4
+
5
+ // PRM-REG-6: receiver for the kit metrics-source protocol (KIT-MET-1..4).
6
+
7
+ const REGISTER = 'redkern:metrics:register';
8
+ const UNREGISTER = 'redkern:metrics:unregister';
9
+ const DISCOVER = 'redkern:metrics:discover';
10
+ const SOURCE_TIMEOUT_MS = 5000;
11
+ const FAMILY_SUFFIXES = ['_bucket', '_sum', '_count', '_total', '_created', '_info'];
12
+
13
+ function isPrometheusText004(contentType) {
14
+ if (typeof contentType !== 'string') return false;
15
+ try {
16
+ const type = new MIMEType(contentType);
17
+ return type.essence.toLowerCase() === 'text/plain' && type.params.get('version') === '0.0.4';
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Splits Prometheus text 0.0.4 into metric families, keeping HELP/TYPE lines with their samples.
25
+ * @param {string} text
26
+ * @returns {Array<{ name: string, lines: string[] }>}
27
+ */
28
+ function splitFamilies(text) {
29
+ const families = [];
30
+ let current;
31
+ const open = (name) => {
32
+ current = { name, lines: [] };
33
+ families.push(current);
34
+ };
35
+ for (const line of String(text).split('\n')) {
36
+ if (line.trim() === '') continue;
37
+ const meta = line.match(/^#\s+(HELP|TYPE)\s+([a-zA-Z_:][a-zA-Z0-9_:]*)/);
38
+ if (meta) {
39
+ if (!current || current.name !== meta[2]) open(meta[2]);
40
+ current.lines.push(line);
41
+ continue;
42
+ }
43
+ if (line.startsWith('#')) {
44
+ if (current) current.lines.push(line);
45
+ continue;
46
+ }
47
+ const sample = line.match(/^([a-zA-Z_:][a-zA-Z0-9_:]*)/);
48
+ if (!sample) continue;
49
+ const name = sample[1];
50
+ if (!current || !belongsTo(name, current.name)) open(name);
51
+ current.lines.push(line);
52
+ }
53
+ return families;
54
+ }
55
+
56
+ function belongsTo(sampleName, familyName) {
57
+ if (sampleName === familyName) return true;
58
+ return FAMILY_SUFFIXES.some((suffix) => sampleName === `${familyName}${suffix}`);
59
+ }
60
+
61
+ /**
62
+ * @param {{ RED: any, warn: (key: string, message: string) => void, warnOnce: (key: string, message: string) => void }} options
63
+ */
64
+ function createReceiver({ RED, warn, warnOnce }) {
65
+ const sources = new Map();
66
+ let started = false;
67
+
68
+ function onRegister(descriptor) {
69
+ if (!descriptor || typeof descriptor !== 'object') return;
70
+ if (descriptor.version !== 1) {
71
+ warn('SOURCE_VERSION', `Ignored metrics source with unknown version ${String(descriptor.version)}`);
72
+ return;
73
+ }
74
+ if (typeof descriptor.sourceId !== 'string' || typeof descriptor.metrics !== 'function') {
75
+ warn('SOURCE_INVALID', 'Ignored malformed metrics source');
76
+ return;
77
+ }
78
+ if (!isPrometheusText004(descriptor.contentType)) {
79
+ warnOnce(`SOURCE_CONTENT_TYPE:${descriptor.sourceId}`, `Ignored metrics source "${String(descriptor.domain)}": content type must be Prometheus text 0.0.4`);
80
+ return;
81
+ }
82
+ // Re-announcements after discover keep the original order (PRM-REG-6: sources win in declaration order).
83
+ sources.set(descriptor.sourceId, { domain: String(descriptor.domain), metrics: descriptor.metrics });
84
+ }
85
+
86
+ function onUnregister(event) {
87
+ if (event && typeof event.sourceId === 'string') sources.delete(event.sourceId);
88
+ }
89
+
90
+ return {
91
+ start() {
92
+ if (started) return;
93
+ started = true;
94
+ RED.events.on(REGISTER, onRegister);
95
+ RED.events.on(UNREGISTER, onUnregister);
96
+ RED.events.emit(DISCOVER, { version: 1 });
97
+ },
98
+ stop() {
99
+ if (!started) return;
100
+ started = false;
101
+ RED.events.removeListener(REGISTER, onRegister);
102
+ RED.events.removeListener(UNREGISTER, onUnregister);
103
+ sources.clear();
104
+ },
105
+ get size() { return sources.size; },
106
+ domains() { return [...sources.values()].map((source) => source.domain); },
107
+ /**
108
+ * Appends every source's text after the palette's own output, skipping metric families that are
109
+ * already present. Text is concatenated, not merged with Registry.merge, so palettes may use
110
+ * different prom-client versions.
111
+ * @param {string[]} ownTexts texts that always win, in order
112
+ */
113
+ async render(ownTexts) {
114
+ const seen = new Set();
115
+ const parts = [];
116
+ const append = (text, origin) => {
117
+ const kept = [];
118
+ for (const family of splitFamilies(text)) {
119
+ if (seen.has(family.name)) {
120
+ warnOnce(`DUPLICATE:${origin}:${family.name}`, `Metric "${family.name}" from ${origin} duplicates an earlier source and was skipped`);
121
+ continue;
122
+ }
123
+ seen.add(family.name);
124
+ kept.push(...family.lines);
125
+ }
126
+ if (kept.length) parts.push(`${kept.join('\n')}\n`);
127
+ };
128
+ // Fast path for this palette's own prom-client output: every family has a TYPE line, so the names are
129
+ // read without splitting the text, which is the largest part of a scrape. Split only on a collision.
130
+ for (const text of ownTexts) {
131
+ const names = [...text.matchAll(/^# TYPE ([a-zA-Z_:][a-zA-Z0-9_:]*) /gm)].map((match) => match[1]);
132
+ if (names.some((name) => seen.has(name))) {
133
+ append(text, 'prometheus palette');
134
+ continue;
135
+ }
136
+ for (const name of names) seen.add(name);
137
+ if (text.length) parts.push(text.endsWith('\n') ? text : `${text}\n`);
138
+ }
139
+ for (const [sourceId, source] of sources) {
140
+ let text;
141
+ try {
142
+ text = await withTimeout(Promise.resolve().then(() => source.metrics()), SOURCE_TIMEOUT_MS);
143
+ } catch (error) {
144
+ warnOnce(`SOURCE_FAILED:${sourceId}`, `Metrics source "${source.domain}" failed: ${error?.message || 'unknown error'}`);
145
+ continue;
146
+ }
147
+ if (typeof text !== 'string') {
148
+ warnOnce(`SOURCE_NOT_TEXT:${sourceId}`, `Metrics source "${source.domain}" returned a non-text value`);
149
+ continue;
150
+ }
151
+ append(text, `source "${source.domain}"`);
152
+ }
153
+ return parts.join('');
154
+ }
155
+ };
156
+ }
157
+
158
+ function withTimeout(promise, ms) {
159
+ let timer;
160
+ return Promise.race([
161
+ promise,
162
+ new Promise((_, reject) => {
163
+ timer = setTimeout(() => reject(Object.assign(new Error('metrics source timed out'), { code: 'SOURCE_TIMEOUT' })), ms);
164
+ timer.unref?.();
165
+ })
166
+ ]).finally(() => clearTimeout(timer));
167
+ }
168
+
169
+ module.exports = { createReceiver, splitFamilies, isPrometheusText004, REGISTER, UNREGISTER, DISCOVER };
@@ -0,0 +1,241 @@
1
+ 'use strict';
2
+
3
+ const { createCardinalityGuard } = require('./cardinality.js');
4
+
5
+ // PRM-REG-1, PRM-REG-3, PRM-REG-4, PRM-REG-5: a palette-private prom-client Registry with
6
+ // ensure-semantics, owner reference counting and deferred removal across deploys.
7
+
8
+ const METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
9
+ const LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
10
+ const RESERVED_LABELS = new Set(['le', 'quantile']);
11
+ const TYPES = Object.freeze(['counter', 'gauge', 'histogram', 'summary']);
12
+ const OPERATIONS = Object.freeze({
13
+ counter: Object.freeze(['inc']),
14
+ gauge: Object.freeze(['inc', 'dec', 'set']),
15
+ histogram: Object.freeze(['observe']),
16
+ summary: Object.freeze(['observe'])
17
+ });
18
+ const INTERNAL_PREFIX = 'redkern_prom_';
19
+
20
+ /**
21
+ * Validates and normalizes a metric definition coming from a config node.
22
+ * @returns {{ ok: true, value: any } | { ok: false, errors: Array<{ field: string, code: string, message: string }> }}
23
+ */
24
+ function normalizeDefinition(input) {
25
+ const errors = [];
26
+ const type = String(input.type || '');
27
+ const name = String(input.name || '').trim();
28
+ const labelNames = Array.isArray(input.labelNames) ? input.labelNames.map((label) => String(label).trim()).filter(Boolean) : [];
29
+ if (!TYPES.includes(type)) errors.push(issue('metricType', 'INVALID_TYPE', `Unsupported metric type "${type}"`));
30
+ if (!METRIC_NAME.test(name)) errors.push(issue('metricName', 'INVALID_NAME', `Metric "${name}" has an invalid Prometheus name`));
31
+ else if (name.startsWith(INTERNAL_PREFIX)) errors.push(issue('metricName', 'RESERVED_NAME', `Metric names starting with ${INTERNAL_PREFIX} are reserved`));
32
+ for (const label of labelNames) {
33
+ if (!LABEL_NAME.test(label) || label.startsWith('__')) errors.push(issue('labelNames', 'INVALID_LABEL', `Label "${label}" has an invalid Prometheus name`));
34
+ else if (RESERVED_LABELS.has(label)) errors.push(issue('labelNames', 'RESERVED_LABEL', `Label "${label}" is reserved by Prometheus`));
35
+ }
36
+ const duplicate = labelNames.find((label, index) => labelNames.indexOf(label) !== index);
37
+ if (duplicate) errors.push(issue('labelNames', 'DUPLICATE_LABEL', `Label "${duplicate}" is declared more than once`));
38
+
39
+ const value = {
40
+ type,
41
+ name,
42
+ help: String(input.help || '').trim() || name,
43
+ labelNames,
44
+ maxSeries: input.maxSeries,
45
+ allowlist: input.allowlist || {}
46
+ };
47
+ if (type === 'histogram') {
48
+ const buckets = numberList(input.buckets);
49
+ if (buckets === null) errors.push(issue('buckets', 'INVALID_BUCKETS', 'Buckets must be finite numbers'));
50
+ else if (buckets.length) {
51
+ if (buckets.some((bucket, index) => index > 0 && bucket <= buckets[index - 1])) {
52
+ errors.push(issue('buckets', 'INVALID_BUCKETS', 'Buckets must be strictly increasing'));
53
+ }
54
+ value.buckets = buckets;
55
+ }
56
+ }
57
+ if (type === 'summary') {
58
+ const percentiles = numberList(input.percentiles);
59
+ if (percentiles === null || (percentiles && percentiles.some((p) => p <= 0 || p >= 1))) {
60
+ errors.push(issue('percentiles', 'INVALID_PERCENTILES', 'Percentiles must be numbers between 0 and 1'));
61
+ } else if (percentiles.length) value.percentiles = percentiles;
62
+ const hasMaxAge = input.maxAgeSeconds !== undefined && input.maxAgeSeconds !== null && String(input.maxAgeSeconds).trim() !== '' && Number(input.maxAgeSeconds) !== 0;
63
+ const maxAge = Number(input.maxAgeSeconds);
64
+ const ageBuckets = Number(input.ageBuckets);
65
+ if (hasMaxAge) {
66
+ if (!Number.isSafeInteger(maxAge) || maxAge < 1) errors.push(issue('maxAgeSeconds', 'INVALID_MAX_AGE', 'maxAgeSeconds must be a positive integer'));
67
+ else value.maxAgeSeconds = maxAge;
68
+ if (!Number.isSafeInteger(ageBuckets) || ageBuckets < 1) errors.push(issue('ageBuckets', 'INVALID_AGE_BUCKETS', 'ageBuckets must be a positive integer when maxAgeSeconds is set'));
69
+ else value.ageBuckets = ageBuckets;
70
+ }
71
+ }
72
+ for (const label of Object.keys(value.allowlist)) {
73
+ if (!labelNames.includes(label)) errors.push(issue('allowlist', 'UNKNOWN_LABEL', `Allowlist label "${label}" is not declared on the metric`));
74
+ }
75
+ return errors.length ? { ok: false, errors } : { ok: true, value };
76
+ }
77
+
78
+ function contractOf(definition) {
79
+ return JSON.stringify([
80
+ definition.type,
81
+ definition.labelNames,
82
+ definition.buckets || null,
83
+ definition.percentiles || null,
84
+ definition.maxAgeSeconds || null,
85
+ definition.ageBuckets || null
86
+ ]);
87
+ }
88
+
89
+ /**
90
+ * @param {{ promClient: typeof import('prom-client'), warn: (key: string, message: string) => void }} options
91
+ */
92
+ function createMetricRegistry({ promClient, warn }) {
93
+ const registry = new promClient.Registry();
94
+ const entries = new Map();
95
+ const dropped = new promClient.Counter({
96
+ name: `${INTERNAL_PREFIX}dropped_series_total`,
97
+ help: 'New label combinations rejected because a metric reached maxSeriesPerMetric.',
98
+ labelNames: ['metric'],
99
+ registers: [registry]
100
+ });
101
+
102
+ function construct(definition) {
103
+ const options = {
104
+ name: definition.name,
105
+ help: definition.help,
106
+ labelNames: definition.labelNames,
107
+ registers: [registry]
108
+ };
109
+ if (definition.type === 'counter') return new promClient.Counter(options);
110
+ if (definition.type === 'gauge') return new promClient.Gauge(options);
111
+ if (definition.type === 'histogram') {
112
+ return new promClient.Histogram(definition.buckets ? { ...options, buckets: definition.buckets } : options);
113
+ }
114
+ const summary = { ...options };
115
+ if (definition.percentiles) summary.percentiles = definition.percentiles;
116
+ if (definition.maxAgeSeconds) {
117
+ summary.maxAgeSeconds = definition.maxAgeSeconds;
118
+ summary.ageBuckets = definition.ageBuckets;
119
+ }
120
+ return new promClient.Summary(summary);
121
+ }
122
+
123
+ function createEntry(definition) {
124
+ const entry = {
125
+ definition,
126
+ contract: contractOf(definition),
127
+ metric: construct(definition),
128
+ owners: new Set(),
129
+ guard: createCardinalityGuard({
130
+ labelNames: definition.labelNames,
131
+ maxSeries: definition.maxSeries,
132
+ allowlist: definition.allowlist,
133
+ onDrop: () => {
134
+ dropped.inc({ metric: definition.name });
135
+ if (entry.onDrop) for (const listener of entry.onDrop) listener();
136
+ }
137
+ }),
138
+ onDrop: new Set()
139
+ };
140
+ entries.set(definition.name, entry);
141
+ return entry;
142
+ }
143
+
144
+ function removeEntry(name) {
145
+ entries.delete(name);
146
+ registry.removeSingleMetric(name);
147
+ }
148
+
149
+ return {
150
+ registry,
151
+ /**
152
+ * @returns {{ ok: true, handle: any } | { ok: false, code: string, message: string }}
153
+ */
154
+ ensure(ownerId, definition) {
155
+ let entry = entries.get(definition.name);
156
+ const contract = contractOf(definition);
157
+ if (entry && entry.contract !== contract) {
158
+ if (entry.owners.size > 0 && !(entry.owners.size === 1 && entry.owners.has(ownerId))) {
159
+ return {
160
+ ok: false,
161
+ code: 'CONTRACT_CONFLICT',
162
+ message: `Metric "${definition.name}" is already defined with a different type, labels or buckets`
163
+ };
164
+ }
165
+ warn(`RECREATE:${definition.name}`, `Metric "${definition.name}" changed type, labels or buckets; it was recreated and its series were reset`);
166
+ removeEntry(definition.name);
167
+ entry = undefined;
168
+ }
169
+ if (!entry) entry = createEntry(definition);
170
+ else if (entry.owners.size === 0) entry.guard.update({ maxSeries: definition.maxSeries, allowlist: definition.allowlist });
171
+ else if (Number(entry.guard.limit) !== Number(definition.maxSeries ?? entry.guard.limit)) {
172
+ warn(`LIMIT:${definition.name}`, `Metric "${definition.name}" is shared by config nodes with different maxSeriesPerMetric; the first deployed value is kept`);
173
+ }
174
+ entry.owners.add(ownerId);
175
+ return { ok: true, handle: makeHandle(entry) };
176
+ },
177
+ /** Marks the owner as gone. The metric stays until sweep() so a redeploy keeps its series (PRM-REG-3). */
178
+ release(ownerId, name) {
179
+ const entry = entries.get(name);
180
+ if (!entry) return false;
181
+ return entry.owners.delete(ownerId);
182
+ },
183
+ /** Removes metrics that no deployed config node owns any more. Called after flows start. */
184
+ sweep() {
185
+ const removed = [];
186
+ for (const [name, entry] of entries) {
187
+ if (entry.owners.size === 0) {
188
+ removeEntry(name);
189
+ removed.push(name);
190
+ }
191
+ }
192
+ return removed;
193
+ },
194
+ has(name) { return entries.has(name); },
195
+ async metrics() { return registry.metrics(); }
196
+ };
197
+ }
198
+
199
+ function makeHandle(entry) {
200
+ const { definition, metric, guard } = entry;
201
+ return {
202
+ name: definition.name,
203
+ type: definition.type,
204
+ labelNames: definition.labelNames,
205
+ supports(operation) {
206
+ return OPERATIONS[definition.type].includes(operation);
207
+ },
208
+ /**
209
+ * @returns {'ok' | 'dropped' | 'unsupported' | 'invalid'}
210
+ */
211
+ write(operation, labels, value) {
212
+ if (!OPERATIONS[definition.type].includes(operation)) return 'unsupported';
213
+ if (!Number.isFinite(value)) return 'invalid';
214
+ if (definition.type === 'counter' && value < 0) return 'invalid';
215
+ const effective = guard.admit(labels);
216
+ if (!effective) return 'dropped';
217
+ if (definition.labelNames.length === 0) metric[operation](value);
218
+ else metric[operation](effective, value);
219
+ return 'ok';
220
+ },
221
+ onDrop(listener) {
222
+ entry.onDrop.add(listener);
223
+ return () => entry.onDrop.delete(listener);
224
+ },
225
+ get series() { return guard.size; }
226
+ };
227
+ }
228
+
229
+ function numberList(value) {
230
+ if (value === undefined || value === null || value === '') return [];
231
+ const raw = Array.isArray(value) ? value : String(value).split(',');
232
+ const items = raw.map((item) => String(item).trim()).filter((item) => item.length > 0);
233
+ const numbers = items.map(Number);
234
+ return numbers.every(Number.isFinite) ? numbers : null;
235
+ }
236
+
237
+ function issue(field, code, message) {
238
+ return { field, code, message };
239
+ }
240
+
241
+ module.exports = { createMetricRegistry, normalizeDefinition, contractOf, numberList, TYPES, OPERATIONS, INTERNAL_PREFIX };