@adalo/metrics 0.1.165 → 0.1.167

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.
@@ -1 +1 @@
1
- {"version":3,"file":"metricsQueueRedisClient.js","names":["RedisMetricsClient","require","IOREDIS","REDIS_V3","REDIS_V4","QueueRedisMetricsClient","constructor","redisClient","metricsConfig","getConfiguredQueueNames","process","env","METRICS_APP_REDIS_BQ","Error","allQueues","split","map","q","trim","filter","Boolean","length","Set","startupValidation","queueNames","console","info","error","message","queueCache","Map","queueJobsGauge","createGauge","name","help","labelNames","withDefaultLabels","_setCleanupHandlers","_send","args","Promise","reject","redisClientType","resolve","send_command","slice","err","result","sendCommand","call","_toNumber","v","n","parseInt","String","Number","isFinite","_getQueueType","queueName","forced","METRICS_QUEUE_TYPE","toLowerCase","bullPrefix","BULL_QUEUE_PREFIX","beePrefix","BEE_QUEUE_PREFIX","METRICS_BEE_QUEUE_PREFIX","bullWaitKey","beeWaitKey","bullExists","beeExists","all","_getBullHealth","prefix","base","waiting","active","succeeded","failed","delayed","_getBeeQueueHealth","collectSingleQueueMetrics","queueType","health","labels","getDefaultLabels","queue_name","set","status","warn","collectQueueMetrics","collectRedisMetrics","allSettled","gatewayPush","clearAllCounters","metricsLogValues","metricObjects","registry","getMetricsAsJSON","JSON","stringify","includes","startPush","intervalSec","_startPush","catch","on","cleanup","queue","close","module","exports"],"sources":["../../src/metrics/metricsQueueRedisClient.js"],"sourcesContent":["const { RedisMetricsClient } = require('./metricsRedisClient')\nconst { IOREDIS, REDIS_V3, REDIS_V4 } = require('../redisUtils')\n\n/**\n * QueueRedisMetricsClient extends RedisMetricsClient to collect\n * Redis and Bee Queue metrics periodically and push them to Prometheus Pushgateway.\n *\n * @extends RedisMetricsClient\n */\nclass QueueRedisMetricsClient extends RedisMetricsClient {\n /**\n * @param {Object} options\n * @param {any} options.redisClient - Redis client instance (required)\n * @param {boolean} [options.gracefulShutdownRedis] - Passed to RedisMetricsClient\n * @param {string} [options.appName] - Application name (from BaseMetricsClient)\n * @param {string} [options.dynoId] - Dyno/instance ID (from BaseMetricsClient)\n * @param {string} [options.processType] - Process type (from BaseMetricsClient)\n * @param {boolean} [options.enabled] - Enable metrics collection (from BaseMetricsClient)\n * @param {boolean} [options.logValues] - Log metrics values (from BaseMetricsClient)\n * @param {string} [options.pushgatewayUrl] - PushGateway URL (from BaseMetricsClient)\n * @param {string} [options.pushgatewaySecret] - PushGateway secret token (from BaseMetricsClient)\n * @param {number} [options.intervalSec] - Interval in seconds for pushing metrics (from BaseMetricsClient)\n * @param {boolean} [options.removeOldMetrics] - Remove old metrics by service (from BaseMetricsClient)\n * @param {function} [options.startupValidation] - Function to validate startup (from BaseMetricsClient)\n * @param {boolean} [options.disablePushgateway] - Disable pushing to Pushgateway (use HTTP scraping instead)\n */\n constructor({ redisClient, ...metricsConfig } = {}) {\n const getConfiguredQueueNames = () => {\n if (!process.env.METRICS_APP_REDIS_BQ) {\n throw new Error(\n 'No queues configured for monitoring. Set METRICS_APP_REDIS_BQ with comma-separated queue names'\n )\n }\n\n const allQueues = process.env.METRICS_APP_REDIS_BQ.split(',')\n .map(q => q.trim())\n .filter(Boolean)\n\n if (allQueues.length === 0) {\n throw new Error(\n 'METRICS_APP_REDIS_BQ is empty or contains only whitespace. ' +\n 'Example: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"'\n )\n }\n\n return [...new Set(allQueues)]\n }\n\n const startupValidation = () => {\n try {\n const queueNames = getConfiguredQueueNames()\n console.info(\n `[queue-metrics] Queue & Redis metrics collection starting for ${queueNames.length} queues`\n )\n return true\n } catch (error) {\n console.error(`[queue-metrics] ❌ Cannot start: ${error.message}`)\n console.error(\n `[queue-metrics] 💡 Example: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"`\n )\n console.error(\n `[queue-metrics] 💡 Optional: METRICS_QUEUE_INTERVAL_SEC=\"10\"`\n )\n console.error(`[queue-metrics] Skipping queue metrics collection`)\n return false\n }\n }\n\n super({\n ...metricsConfig,\n redisClient,\n startupValidation,\n })\n\n this.getConfiguredQueueNames = getConfiguredQueueNames\n this.startupValidation = startupValidation\n\n /** Cache for queue objects to avoid multiple connections */\n // NOTE:\n // Historically we used `bee-queue`'s `Queue#checkHealth()` here.\n // But bee-queue depends on `redis@3`, which is not compatible with Node 22\n // in some environments and can crash with errors like:\n // - \"this._ready.then is not a function\"\n // - \"TypeError: this.stream.once is not a function\"\n //\n // To avoid pulling in node-redis v3 at runtime, we read queue counters\n // directly from Redis using the *provided* redis client (ioredis or node-redis).\n //\n // Keep this map reserved for possible future caching (e.g. key schema detection),\n // but we no longer store Queue instances.\n this.queueCache = new Map()\n\n /** Gauge for queue jobs by status */\n this.queueJobsGauge = this.createGauge({\n name: 'app_queue_jobs_count',\n help: 'Number of app jobs in the queue by status',\n labelNames: this.withDefaultLabels(['queue_name', 'status']),\n })\n\n this._setCleanupHandlers()\n }\n\n /**\n * Execute a Redis command in a client-type safe way.\n *\n * @param {string[]} args Command args array, e.g. ['LLEN', 'key']\n * @returns {Promise<any>}\n */\n _send = args => {\n if (!this.redisClient) {\n return Promise.reject(new Error('Redis client not provided'))\n }\n\n // node-redis v3 (callback API)\n if (this.redisClientType === REDIS_V3) {\n return new Promise((resolve, reject) => {\n this.redisClient.send_command(args[0], args.slice(1), (err, result) => {\n if (err) reject(err)\n else resolve(result)\n })\n })\n }\n\n // node-redis v4 (Promise API)\n if (this.redisClientType === REDIS_V4) {\n return this.redisClient.sendCommand(args)\n }\n\n // ioredis (Promise API)\n if (this.redisClientType === IOREDIS) {\n // ioredis supports `.call(command, ...args)`\n return this.redisClient.call(args[0], ...args.slice(1))\n }\n\n return Promise.reject(new Error('Unsupported Redis client type'))\n }\n\n _toNumber = v => {\n const n = typeof v === 'number' ? v : parseInt(String(v || '0'), 10)\n return Number.isFinite(n) ? n : 0\n }\n\n _getQueueType = async queueName => {\n const forced = (process.env.METRICS_QUEUE_TYPE || '').trim().toLowerCase()\n if (forced === 'bull' || forced === 'bee') return forced\n\n const bullPrefix =\n (process.env.BULL_QUEUE_PREFIX || 'bull').trim() || 'bull'\n const beePrefix =\n (\n process.env.BEE_QUEUE_PREFIX ||\n process.env.METRICS_BEE_QUEUE_PREFIX ||\n 'bq'\n ).trim() || 'bq'\n\n // Detect by checking the canonical \"waiting\" key names.\n const bullWaitKey = `${bullPrefix}:${queueName}:wait`\n const beeWaitKey = `${beePrefix}:${queueName}:waiting`\n\n try {\n const [bullExists, beeExists] = await Promise.all([\n this._send(['EXISTS', bullWaitKey]),\n this._send(['EXISTS', beeWaitKey]),\n ])\n if (this._toNumber(bullExists) > 0) return 'bull'\n if (this._toNumber(beeExists) > 0) return 'bee'\n } catch {\n // If EXISTS is blocked/unavailable, fall back to trying bull first.\n }\n\n return 'bull'\n }\n\n _getBullHealth = async queueName => {\n const prefix = (process.env.BULL_QUEUE_PREFIX || 'bull').trim() || 'bull'\n const base = `${prefix}:${queueName}:`\n\n const [waiting, active, succeeded, failed, delayed] = await Promise.all([\n this._send(['LLEN', `${base}wait`]),\n this._send(['LLEN', `${base}active`]),\n this._send(['ZCARD', `${base}completed`]),\n this._send(['ZCARD', `${base}failed`]),\n this._send(['ZCARD', `${base}delayed`]),\n ])\n\n return {\n waiting: this._toNumber(waiting),\n active: this._toNumber(active),\n succeeded: this._toNumber(succeeded),\n failed: this._toNumber(failed),\n delayed: this._toNumber(delayed),\n }\n }\n\n _getBeeQueueHealth = async queueName => {\n const prefix =\n (\n process.env.BEE_QUEUE_PREFIX ||\n process.env.METRICS_BEE_QUEUE_PREFIX ||\n 'bq'\n ).trim() || 'bq'\n const base = `${prefix}:${queueName}:`\n\n const [waiting, active, succeeded, failed, delayed] = await Promise.all([\n this._send(['LLEN', `${base}waiting`]),\n this._send(['LLEN', `${base}active`]),\n this._send(['SCARD', `${base}succeeded`]),\n this._send(['SCARD', `${base}failed`]),\n this._send(['ZCARD', `${base}delayed`]),\n ])\n\n return {\n waiting: this._toNumber(waiting),\n active: this._toNumber(active),\n succeeded: this._toNumber(succeeded),\n failed: this._toNumber(failed),\n delayed: this._toNumber(delayed),\n }\n }\n\n /**\n * Collect metrics for a single queue and set gauges.\n *\n * Supports:\n * - Bull (default): keys like `bull:<queue>:wait`, `...:active`, `...:completed`, `...:failed`, `...:delayed`\n * - Bee-Queue: keys like `bq:<queue>:waiting`, `...:active`, `...:succeeded`, `...:failed`, `...:delayed`\n *\n * Auto-detects queue type unless `METRICS_QUEUE_TYPE` is set to `bull` or `bee`.\n *\n * @param {string} queueName - Name of the queue\n * @returns {Promise<void>}\n */\n collectSingleQueueMetrics = async queueName => {\n try {\n const queueType = await this._getQueueType(queueName)\n const health =\n queueType === 'bee'\n ? await this._getBeeQueueHealth(queueName)\n : await this._getBullHealth(queueName)\n\n const labels = {\n ...this.getDefaultLabels(),\n queue_name: queueName,\n }\n\n this.queueJobsGauge.set(\n { ...labels, status: 'waiting' },\n health.waiting || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'active' },\n health.active || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'succeeded' },\n health.succeeded || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'failed' },\n health.failed || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'delayed' },\n health.delayed || 0\n )\n } catch (error) {\n console.warn(\n `[queue-metrics] Failed to collect metrics for queue ${queueName}:`,\n error.message\n )\n }\n }\n\n /**\n * Collect metrics for all queues and Redis, then push to Pushgateway\n * @returns {Promise<void>}\n */\n collectQueueMetrics = async () => {\n try {\n const queueNames = this.getConfiguredQueueNames()\n\n await this.collectRedisMetrics()\n await Promise.allSettled(\n queueNames.map(queueName => this.collectSingleQueueMetrics(queueName))\n )\n\n await this.gatewayPush()\n this.clearAllCounters()\n\n if (this.metricsLogValues) {\n const metricObjects = await this.registry.getMetricsAsJSON()\n console.info(\n `[queue-metrics] Collected metrics for ${queueNames.length} queues:`,\n JSON.stringify(metricObjects, null, 2)\n )\n }\n } catch (error) {\n if (\n error.message?.includes('No queues configured') ||\n error.message?.includes('METRICS_APP_REDIS_BQ')\n ) {\n console.error(\n `[queue-metrics] ❌ Configuration error: ${error.message}`\n )\n console.error(\n `[queue-metrics] 💡 Example config: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"`\n )\n } else {\n console.error(\n `[queue-metrics] Failed to collect queue metrics: ${error.message}`\n )\n }\n throw error\n }\n }\n\n /**\n * Start periodic collection.\n * @param {number} [intervalSec=this.intervalSec] - Interval in seconds\n */\n startPush = (intervalSec = this.intervalSec) => {\n this._startPush(intervalSec, () => {\n this.collectQueueMetrics().catch(err => {\n console.error(\n `[queue-metrics] Failed to collect queue & Redis metrics:`,\n err\n )\n })\n })\n }\n\n _setCleanupHandlers = () => {\n process.on('SIGINT', this.cleanup)\n process.on('SIGTERM', this.cleanup)\n }\n\n /**\n * Cleanup queues and exit process.\n * Closes queues then runs Redis metrics cleanup (stop push, delete from VM, close Redis).\n * @returns {Promise<void>}\n */\n cleanup = async () => {\n for (const [queueName, queue] of this.queueCache) {\n try {\n await queue.close()\n } catch (err) {\n console.error(`[queue-metrics] Error closing queue ${queueName}:`, err)\n }\n }\n await super.cleanup()\n }\n}\n\nmodule.exports = { QueueRedisMetricsClient }\n"],"mappings":";;AAAA,MAAM;EAAEA;AAAmB,CAAC,GAAGC,OAAO,CAAC,sBAAsB,CAAC;AAC9D,MAAM;EAAEC,OAAO;EAAEC,QAAQ;EAAEC;AAAS,CAAC,GAAGH,OAAO,CAAC,eAAe,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,MAAMI,uBAAuB,SAASL,kBAAkB,CAAC;EACvD;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEM,WAAWA,CAAC;IAAEC,WAAW;IAAE,GAAGC;EAAc,CAAC,GAAG,CAAC,CAAC,EAAE;IAClD,MAAMC,uBAAuB,GAAGA,CAAA,KAAM;MACpC,IA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,CAACE,KAAK,CACX,0DAA0D,EAC1DmB,GACF,CAAC;MACH,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ,CAAC;EAEDT,mBAAmB,GAAGA,CAAA,KAAM;IAC1B3B,OAAO,CAACgG,EAAE,CAAC,QAAQ,EAAE,IAAI,CAACC,OAAO,CAAC;IAClCjG,OAAO,CAACgG,EAAE,CAAC,SAAS,EAAE,IAAI,CAACC,OAAO,CAAC;EACrC,CAAC;;EAED;AACF;AACA;AACA;AACA;EACEA,OAAO,GAAG,MAAAA,CAAA,KAAY;IACpB,KAAK,MAAM,CAACjD,SAAS,EAAEkD,KAAK,CAAC,IAAI,IAAI,CAAC/E,UAAU,EAAE;MAChD,IAAI;QACF,MAAM+E,KAAK,CAACC,KAAK,CAAC,CAAC;MACrB,CAAC,CAAC,OAAO/D,GAAG,EAAE;QACZrB,OAAO,CAACE,KAAK,CAAC,uCAAuC+B,SAAS,GAAG,EAAEZ,GAAG,CAAC;MACzE;IACF;IACA,MAAM,KAAK,CAAC6D,OAAO,CAAC,CAAC;EACvB,CAAC;AACH;AAEAG,MAAM,CAACC,OAAO,GAAG;EAAE1G;AAAwB,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"metricsQueueRedisClient.js","names":["RedisMetricsClient","require","IOREDIS","REDIS_V3","REDIS_V4","QueueRedisMetricsClient","constructor","redisClient","metricsConfig","getConfiguredQueueNames","process","env","METRICS_APP_REDIS_BQ","Error","allQueues","split","map","q","trim","filter","Boolean","length","Set","startupValidation","queueNames","console","info","error","message","queueCache","Map","queueJobsGauge","createGauge","name","help","labelNames","withDefaultLabels","_setCleanupHandlers","_send","args","Promise","reject","redisClientType","resolve","send_command","slice","err","result","sendCommand","call","_toNumber","v","n","parseInt","String","Number","isFinite","_getQueueType","queueName","forced","METRICS_QUEUE_TYPE","toLowerCase","bullPrefix","BULL_QUEUE_PREFIX","beePrefix","BEE_QUEUE_PREFIX","METRICS_BEE_QUEUE_PREFIX","bullWaitKey","beeWaitKey","bullExists","beeExists","all","_getBullHealth","prefix","base","waiting","active","succeeded","failed","delayed","_getBeeQueueHealth","collectSingleQueueMetrics","queueType","health","labels","getDefaultLabels","queue_name","set","status","warn","collectQueueMetrics","collectRedisMetrics","allSettled","gatewayPush","clearAllCounters","metricsLogValues","metricObjects","registry","getMetricsAsJSON","JSON","stringify","includes","startPush","intervalSec","_startPush","catch","on","cleanup","queue","close","exit","module","exports"],"sources":["../../src/metrics/metricsQueueRedisClient.js"],"sourcesContent":["const { RedisMetricsClient } = require('./metricsRedisClient')\nconst { IOREDIS, REDIS_V3, REDIS_V4 } = require('../redisUtils')\n\n/**\n * QueueRedisMetricsClient extends RedisMetricsClient to collect\n * Redis and Bee Queue metrics periodically and push them to Prometheus Pushgateway.\n *\n * @extends RedisMetricsClient\n */\nclass QueueRedisMetricsClient extends RedisMetricsClient {\n /**\n * @param {Object} options\n * @param {any} options.redisClient - Redis client instance (required)\n * @param {string} [options.appName] - Application name (from BaseMetricsClient)\n * @param {string} [options.dynoId] - Dyno/instance ID (from BaseMetricsClient)\n * @param {string} [options.processType] - Process type (from BaseMetricsClient)\n * @param {boolean} [options.enabled] - Enable metrics collection (from BaseMetricsClient)\n * @param {boolean} [options.logValues] - Log metrics values (from BaseMetricsClient)\n * @param {string} [options.pushgatewayUrl] - PushGateway URL (from BaseMetricsClient)\n * @param {string} [options.pushgatewaySecret] - PushGateway secret token (from BaseMetricsClient)\n * @param {number} [options.intervalSec] - Interval in seconds for pushing metrics (from BaseMetricsClient)\n * @param {boolean} [options.removeOldMetrics] - Remove old metrics by service (from BaseMetricsClient)\n * @param {function} [options.startupValidation] - Function to validate startup (from BaseMetricsClient)\n * @param {boolean} [options.disablePushgateway] - Disable pushing to Pushgateway (use HTTP scraping instead)\n */\n constructor({ redisClient, ...metricsConfig } = {}) {\n const getConfiguredQueueNames = () => {\n if (!process.env.METRICS_APP_REDIS_BQ) {\n throw new Error(\n 'No queues configured for monitoring. Set METRICS_APP_REDIS_BQ with comma-separated queue names'\n )\n }\n\n const allQueues = process.env.METRICS_APP_REDIS_BQ.split(',')\n .map(q => q.trim())\n .filter(Boolean)\n\n if (allQueues.length === 0) {\n throw new Error(\n 'METRICS_APP_REDIS_BQ is empty or contains only whitespace. ' +\n 'Example: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"'\n )\n }\n\n return [...new Set(allQueues)]\n }\n\n const startupValidation = () => {\n try {\n const queueNames = getConfiguredQueueNames()\n console.info(\n `[queue-metrics] Queue & Redis metrics collection starting for ${queueNames.length} queues`\n )\n return true\n } catch (error) {\n console.error(`[queue-metrics] ❌ Cannot start: ${error.message}`)\n console.error(\n `[queue-metrics] 💡 Example: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"`\n )\n console.error(\n `[queue-metrics] 💡 Optional: METRICS_QUEUE_INTERVAL_SEC=\"10\"`\n )\n console.error(`[queue-metrics] Skipping queue metrics collection`)\n return false\n }\n }\n\n super({\n ...metricsConfig,\n redisClient,\n startupValidation,\n })\n\n this.getConfiguredQueueNames = getConfiguredQueueNames\n this.startupValidation = startupValidation\n\n /** Cache for queue objects to avoid multiple connections */\n // NOTE:\n // Historically we used `bee-queue`'s `Queue#checkHealth()` here.\n // But bee-queue depends on `redis@3`, which is not compatible with Node 22\n // in some environments and can crash with errors like:\n // - \"this._ready.then is not a function\"\n // - \"TypeError: this.stream.once is not a function\"\n //\n // To avoid pulling in node-redis v3 at runtime, we read queue counters\n // directly from Redis using the *provided* redis client (ioredis or node-redis).\n //\n // Keep this map reserved for possible future caching (e.g. key schema detection),\n // but we no longer store Queue instances.\n this.queueCache = new Map()\n\n /** Gauge for queue jobs by status */\n this.queueJobsGauge = this.createGauge({\n name: 'app_queue_jobs_count',\n help: 'Number of app jobs in the queue by status',\n labelNames: this.withDefaultLabels(['queue_name', 'status']),\n })\n\n this._setCleanupHandlers()\n }\n\n /**\n * Execute a Redis command in a client-type safe way.\n *\n * @param {string[]} args Command args array, e.g. ['LLEN', 'key']\n * @returns {Promise<any>}\n */\n _send = args => {\n if (!this.redisClient) {\n return Promise.reject(new Error('Redis client not provided'))\n }\n\n // node-redis v3 (callback API)\n if (this.redisClientType === REDIS_V3) {\n return new Promise((resolve, reject) => {\n this.redisClient.send_command(args[0], args.slice(1), (err, result) => {\n if (err) reject(err)\n else resolve(result)\n })\n })\n }\n\n // node-redis v4 (Promise API)\n if (this.redisClientType === REDIS_V4) {\n return this.redisClient.sendCommand(args)\n }\n\n // ioredis (Promise API)\n if (this.redisClientType === IOREDIS) {\n // ioredis supports `.call(command, ...args)`\n return this.redisClient.call(args[0], ...args.slice(1))\n }\n\n return Promise.reject(new Error('Unsupported Redis client type'))\n }\n\n _toNumber = v => {\n const n = typeof v === 'number' ? v : parseInt(String(v || '0'), 10)\n return Number.isFinite(n) ? n : 0\n }\n\n _getQueueType = async queueName => {\n const forced = (process.env.METRICS_QUEUE_TYPE || '').trim().toLowerCase()\n if (forced === 'bull' || forced === 'bee') return forced\n\n const bullPrefix =\n (process.env.BULL_QUEUE_PREFIX || 'bull').trim() || 'bull'\n const beePrefix =\n (\n process.env.BEE_QUEUE_PREFIX ||\n process.env.METRICS_BEE_QUEUE_PREFIX ||\n 'bq'\n ).trim() || 'bq'\n\n // Detect by checking the canonical \"waiting\" key names.\n const bullWaitKey = `${bullPrefix}:${queueName}:wait`\n const beeWaitKey = `${beePrefix}:${queueName}:waiting`\n\n try {\n const [bullExists, beeExists] = await Promise.all([\n this._send(['EXISTS', bullWaitKey]),\n this._send(['EXISTS', beeWaitKey]),\n ])\n if (this._toNumber(bullExists) > 0) return 'bull'\n if (this._toNumber(beeExists) > 0) return 'bee'\n } catch {\n // If EXISTS is blocked/unavailable, fall back to trying bull first.\n }\n\n return 'bull'\n }\n\n _getBullHealth = async queueName => {\n const prefix = (process.env.BULL_QUEUE_PREFIX || 'bull').trim() || 'bull'\n const base = `${prefix}:${queueName}:`\n\n const [waiting, active, succeeded, failed, delayed] = await Promise.all([\n this._send(['LLEN', `${base}wait`]),\n this._send(['LLEN', `${base}active`]),\n this._send(['ZCARD', `${base}completed`]),\n this._send(['ZCARD', `${base}failed`]),\n this._send(['ZCARD', `${base}delayed`]),\n ])\n\n return {\n waiting: this._toNumber(waiting),\n active: this._toNumber(active),\n succeeded: this._toNumber(succeeded),\n failed: this._toNumber(failed),\n delayed: this._toNumber(delayed),\n }\n }\n\n _getBeeQueueHealth = async queueName => {\n const prefix =\n (\n process.env.BEE_QUEUE_PREFIX ||\n process.env.METRICS_BEE_QUEUE_PREFIX ||\n 'bq'\n ).trim() || 'bq'\n const base = `${prefix}:${queueName}:`\n\n const [waiting, active, succeeded, failed, delayed] = await Promise.all([\n this._send(['LLEN', `${base}waiting`]),\n this._send(['LLEN', `${base}active`]),\n this._send(['SCARD', `${base}succeeded`]),\n this._send(['SCARD', `${base}failed`]),\n this._send(['ZCARD', `${base}delayed`]),\n ])\n\n return {\n waiting: this._toNumber(waiting),\n active: this._toNumber(active),\n succeeded: this._toNumber(succeeded),\n failed: this._toNumber(failed),\n delayed: this._toNumber(delayed),\n }\n }\n\n /**\n * Collect metrics for a single queue and set gauges.\n *\n * Supports:\n * - Bull (default): keys like `bull:<queue>:wait`, `...:active`, `...:completed`, `...:failed`, `...:delayed`\n * - Bee-Queue: keys like `bq:<queue>:waiting`, `...:active`, `...:succeeded`, `...:failed`, `...:delayed`\n *\n * Auto-detects queue type unless `METRICS_QUEUE_TYPE` is set to `bull` or `bee`.\n *\n * @param {string} queueName - Name of the queue\n * @returns {Promise<void>}\n */\n collectSingleQueueMetrics = async queueName => {\n try {\n const queueType = await this._getQueueType(queueName)\n const health =\n queueType === 'bee'\n ? await this._getBeeQueueHealth(queueName)\n : await this._getBullHealth(queueName)\n\n const labels = {\n ...this.getDefaultLabels(),\n queue_name: queueName,\n }\n\n this.queueJobsGauge.set(\n { ...labels, status: 'waiting' },\n health.waiting || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'active' },\n health.active || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'succeeded' },\n health.succeeded || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'failed' },\n health.failed || 0\n )\n this.queueJobsGauge.set(\n { ...labels, status: 'delayed' },\n health.delayed || 0\n )\n } catch (error) {\n console.warn(\n `[queue-metrics] Failed to collect metrics for queue ${queueName}:`,\n error.message\n )\n }\n }\n\n /**\n * Collect metrics for all queues and Redis, then push to Pushgateway\n * @returns {Promise<void>}\n */\n collectQueueMetrics = async () => {\n try {\n const queueNames = this.getConfiguredQueueNames()\n\n await this.collectRedisMetrics()\n await Promise.allSettled(\n queueNames.map(queueName => this.collectSingleQueueMetrics(queueName))\n )\n\n await this.gatewayPush()\n this.clearAllCounters()\n\n if (this.metricsLogValues) {\n const metricObjects = await this.registry.getMetricsAsJSON()\n console.info(\n `[queue-metrics] Collected metrics for ${queueNames.length} queues:`,\n JSON.stringify(metricObjects, null, 2)\n )\n }\n } catch (error) {\n if (\n error.message?.includes('No queues configured') ||\n error.message?.includes('METRICS_APP_REDIS_BQ')\n ) {\n console.error(\n `[queue-metrics] ❌ Configuration error: ${error.message}`\n )\n console.error(\n `[queue-metrics] 💡 Example config: METRICS_APP_REDIS_BQ=\"adalo-compile,adalo-migrations\"`\n )\n } else {\n console.error(\n `[queue-metrics] Failed to collect queue metrics: ${error.message}`\n )\n }\n throw error\n }\n }\n\n /**\n * Start periodic collection.\n * @param {number} [intervalSec=this.intervalSec] - Interval in seconds\n */\n startPush = (intervalSec = this.intervalSec) => {\n this._startPush(intervalSec, () => {\n this.collectQueueMetrics().catch(err => {\n console.error(\n `[queue-metrics] Failed to collect queue & Redis metrics:`,\n err\n )\n })\n })\n }\n\n _setCleanupHandlers = () => {\n process.on('SIGINT', this.cleanup)\n process.on('SIGTERM', this.cleanup)\n }\n\n /**\n * Cleanup queues and exit process.\n * @returns {Promise<void>}\n */\n cleanup = async () => {\n for (const [queueName, queue] of this.queueCache) {\n try {\n await queue.close()\n } catch (err) {\n console.error(`[queue-metrics] Error closing queue ${queueName}:`, err)\n }\n }\n process.exit(0)\n }\n}\n\nmodule.exports = { QueueRedisMetricsClient }\n"],"mappings":";;AAAA,MAAM;EAAEA;AAAmB,CAAC,GAAGC,OAAO,CAAC,sBAAsB,CAAC;AAC9D,MAAM;EAAEC,OAAO;EAAEC,QAAQ;EAAEC;AAAS,CAAC,GAAGH,OAAO,CAAC,eAAe,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,MAAMI,uBAAuB,SAASL,kBAAkB,CAAC;EACvD;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEM,WAAWA,CAAC;IAAEC,WAAW;IAAE,GAAGC;EAAc,CAAC,GAAG,CAAC,CAAC,EAAE;IAClD,MAAMC,uBAAuB,GAAGA,CAAA,KAAM;MACpC,IAAI,CAACC,OAAO,CAACC,GAAG,CAACC,oBAAoB,EAAE;QACrC,MAAM,IAAIC,KAAK,CACb,gGACF,CAAC;MACH;MAEA,MAAMC,SAAS,GAAGJ,OAAO,CAACC,GAAG,CAACC,oBAAoB,CAACG,KAAK,CAAC,GAAG,CAAC,CAC1DC,GAAG,CAACC,CAAC,IAAIA,CAAC,CAACC,IAAI,CAAC,CAAC,CAAC,CAClBC,MAAM,CAACC,OAAO,CAAC;MAElB,IAAIN,SAAS,CAACO,MAAM,KAAK,CAAC,EAAE;QAC1B,MAAM,IAAIR,KAAK,CACb,6DAA6D,GAC3D,gEACJ,CAAC;MACH;MAEA,OAAO,CAAC,GAAG,IAAIS,GAAG,CAACR,SAAS,CAAC,CAAC;IAChC,CAAC;IAED,MAAMS,iBAAiB,GAAGA,CAAA,KAAM;MAC9B,IAAI;QACF,MAAMC,UAAU,GAAGf,uBAAuB,CAAC,CAAC;QAC5CgB,OAAO,CAACC,IAAI,CACV,iEAAiEF,UAAU,CAACH,MAAM,SACpF,CAAC;QACD,OAAO,IAAI;MACb,CAAC,CAAC,OAAOM,KAAK,EAAE;QACdF,OAAO,CAACE,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","ignoreList":[]}
@@ -7,8 +7,7 @@
7
7
  export class RedisMetricsClient extends BaseMetricsClient {
8
8
  /**
9
9
  * @param {Object} options
10
- * @param {any} options.redisClient - Redis client instance (required). Used for metrics and publish. Subscriber is created internally (duplicate() or REDIS_URL).
11
- * @param {boolean} [options.gracefulShutdownRedis] - Default true. When true, new instance publishes on start and old instances exit on message. Set false or METRICS_GRACEFUL_SHUTDOWN_REDIS=false to disable.
10
+ * @param {any} options.redisClient - Redis client instance (required)
12
11
  * @param {string} [options.appName] - Application name (from BaseMetricsClient)
13
12
  * @param {string} [options.dynoId] - Dyno/instance ID (from BaseMetricsClient)
14
13
  * @param {string} [options.processType] - Process type (from BaseMetricsClient)
@@ -23,7 +22,6 @@ export class RedisMetricsClient extends BaseMetricsClient {
23
22
  */
24
23
  constructor({ redisClient, ...metricsConfig }?: {
25
24
  redisClient: any;
26
- gracefulShutdownRedis?: boolean | undefined;
27
25
  appName?: string | undefined;
28
26
  dynoId?: string | undefined;
29
27
  processType?: string | undefined;
@@ -39,9 +37,9 @@ export class RedisMetricsClient extends BaseMetricsClient {
39
37
  /** Redis client used for metrics */
40
38
  redisClient: any;
41
39
  redisClientType: string;
42
- /** Dedicated Redis connection for subscribe (subscriber mode); closed in cleanup. */
43
- _subClient: any;
44
- /** Counter for Redis client connections */
40
+ /** Label names for Redis metrics: app + process_type only (no dyno_id). */
41
+ _redisLabelNames: string[];
42
+ /** Counter for Redis connection metrics */
45
43
  redisConnectionsGauge: import("prom-client").Gauge<string>;
46
44
  redisConnectionsMemoryGauge: import("prom-client").Gauge<string>;
47
45
  /** Gauge for Redis memory usage */
@@ -50,39 +48,6 @@ export class RedisMetricsClient extends BaseMetricsClient {
50
48
  redisStatsGauge: import("prom-client").Gauge<string>;
51
49
  _redisConnSeenKeys: Set<any>;
52
50
  _redisConnZeroedKeys: Set<any>;
53
- /**
54
- * Initialize graceful-shutdown state and subscribe when enabled. Called from constructor.
55
- * @param {boolean} [gracefulShutdownRedis] - Explicit false to disable; otherwise enabled unless METRICS_GRACEFUL_SHUTDOWN_REDIS=false.
56
- */
57
- _initGracefulShutdown(gracefulShutdownRedis?: boolean | undefined): void;
58
- _gracefulShutdownRedis: boolean | undefined;
59
- _gracefulShutdownStream: string | null | undefined;
60
- _gracefulShutdownAckChannel: string | null | undefined;
61
- _gracefulShutdownLogPrefix: string | undefined;
62
- /**
63
- * Create a dedicated Redis client for subscribe (pub/sub). Uses duplicate() when available, else createClient from REDIS_URL. Branches by redisClientType (IOREDIS, REDIS_V3, REDIS_V4).
64
- * @returns {any|null} Subscriber client or null if not possible.
65
- */
66
- _createSubscriberClient(): any | null;
67
- /**
68
- * Set up Redis subscribe for graceful shutdown. Uses _createSubscriberClient() so subscriber matches client type (ioredis vs node-redis v3/v4).
69
- */
70
- /**
71
- * Set up Redis stream read for graceful shutdown. Uses _createSubscriberClient() and XREAD BLOCK; stream is trimmed (MAXLEN and MINID) so messages are not kept in Redis forever.
72
- */
73
- _setupGracefulShutdownSubscribe(): void;
74
- _streamReadLoop(streamKey: any): void;
75
- _xreadBlock(streamKey: any, blockMs: any): Promise<any>;
76
- _parseXreadReply(reply: any, streamKey: any): any[][];
77
- /**
78
- * Old instance: stop push, clear metrics from VM, then publish ack so new can start; then exit.
79
- */
80
- _cleanupAndPublishAck(): Promise<void>;
81
- _publishAck(): any;
82
- /**
83
- * Publish "new instance started" to stream so old instances exit. Stream is trimmed (MAXLEN ~ 10 and MINID older than 1 min) so messages are not kept in Redis forever.
84
- */
85
- _publishNewInstanceStarted(): void;
86
51
  getRedisConnections: () => Promise<any>;
87
52
  getRedisInfo: (section: any) => Promise<any>;
88
53
  parseRedisConnections: (clientsStr: any) => any;
@@ -97,9 +62,10 @@ export class RedisMetricsClient extends BaseMetricsClient {
97
62
  */
98
63
  pushRedisMetrics: () => Promise<void>;
99
64
  /**
100
- * Start periodic collection. When graceful shutdown is on: new publishes "new started" so old exits and clears; new does not push until after one interval (skipFirstPush), giving old time to stop.
65
+ * Start periodic collection.
66
+ * @param {number} [intervalSec=this.intervalSec] - Interval in seconds
101
67
  */
102
- startPush: (intervalSec?: number) => void;
68
+ startPush: (intervalSec?: number | undefined) => void;
103
69
  }
104
70
  import { BaseMetricsClient } from "./baseMetricsClient";
105
71
  //# sourceMappingURL=metricsRedisClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metricsRedisClient.d.ts","sourceRoot":"","sources":["../../src/metrics/metricsRedisClient.js"],"names":[],"mappings":"AAcA;;;;;GAKG;AACH;IACE;;;;;;;;;;;;;;;OAeG;IACH;QAdwB,WAAW,EAAxB,GAAG;QACe,qBAAqB;QACtB,OAAO;QACP,MAAM;QACN,WAAW;QACV,OAAO;QACP,SAAS;QACV,cAAc;QACd,iBAAiB;QACjB,WAAW;QACV,gBAAgB;QACf,iBAAiB;QAClB,kBAAkB;OAgE9C;IA9CC,oCAAoC;IACpC,iBAA8B;IAC9B,wBAAsD;IAEtD,qFAAqF;IACrF,gBAAsB;IAItB,2CAA2C;IAC3C,2DAIE;IAEF,iEAIE;IAEF,mCAAmC;IACnC,sDAIE;IAEF,sCAAsC;IACtC,qDAIE;IAQF,6BAAmC;IACnC,+BAAqC;IAKvC;;;OAGG;IACH,yEAeC;IAXC,4CAAgE;IAChE,mDAEQ;IACR,uDAEQ;IACR,+CAAgH;IAMlH;;;OAGG;IACH,2BAFa,GAAG,GAAC,IAAI,CAuBpB;IAED;;OAEG;IACH;;OAEG;IACH,wCAaC;IAED,sCAmBC;IAED,wDAqBC;IAED,sDAKC;IAED;;OAEG;IACH,uCAoCC;IAED,mBAmBC;IAED;;OAEG;IACH,mCAkBC;IAED,wCAgCC;IAED,6CAuBC;IAED,gDAkBC;IAED;;;OAGG;IACH,2BAFa,QAAQ,IAAI,CAAC,CA6KzB;IAED;;;OAGG;IACH,wBAFa,QAAQ,IAAI,CAAC,CAazB;IAED;;OAEG;IACH,0CASC;CAmDF"}
1
+ {"version":3,"file":"metricsRedisClient.d.ts","sourceRoot":"","sources":["../../src/metrics/metricsRedisClient.js"],"names":[],"mappings":"AAWA;;;;;GAKG;AACH;IACE;;;;;;;;;;;;;;OAcG;IACH;QAbwB,WAAW,EAAxB,GAAG;QACc,OAAO;QACP,MAAM;QACN,WAAW;QACV,OAAO;QACP,SAAS;QACV,cAAc;QACd,iBAAiB;QACjB,WAAW;QACV,gBAAgB;QACf,iBAAiB;QAClB,kBAAkB;OA8D9C;IA5CC,oCAAoC;IACpC,iBAA8B;IAC9B,wBAAsD;IAEtD,2EAA2E;IAC3E,2BAA+C;IAE/C,2CAA2C;IAC3C,2DAIE;IAEF,iEAIE;IAEF,mCAAmC;IACnC,sDAIE;IAEF,sCAAsC;IACtC,qDAIE;IAQF,6BAAmC;IACnC,+BAAqC;IAKvC,wCAgCC;IAED,6CAuBC;IAED,gDAkBC;IAED;;;OAGG;IACH,2BAFa,QAAQ,IAAI,CAAC,CA6KzB;IAED;;;OAGG;IACH,wBAFa,QAAQ,IAAI,CAAC,CAqBzB;IAED;;;OAGG;IACH,sDAMC;CA4BF"}
@@ -12,9 +12,6 @@ const {
12
12
  const redisConnectionStableFields = ['name', 'flags', 'cmd'];
13
13
  const redisConnectionFields = ['name', 'flags', 'tot-mem', 'cmd'];
14
14
 
15
- /** Stream entries older than this (ms) are trimmed so messages are not kept in Redis. Fixed 60s. */
16
- const GRACEFUL_SHUTDOWN_STREAM_MAXAGE_MS = 60000;
17
-
18
15
  /**
19
16
  * RedisMetricsClient extends BaseMetricsClient to collect
20
17
  * Redis metrics periodically and push them to Prometheus Pushgateway.
@@ -24,8 +21,7 @@ const GRACEFUL_SHUTDOWN_STREAM_MAXAGE_MS = 60000;
24
21
  class RedisMetricsClient extends BaseMetricsClient {
25
22
  /**
26
23
  * @param {Object} options
27
- * @param {any} options.redisClient - Redis client instance (required). Used for metrics and publish. Subscriber is created internally (duplicate() or REDIS_URL).
28
- * @param {boolean} [options.gracefulShutdownRedis] - Default true. When true, new instance publishes on start and old instances exit on message. Set false or METRICS_GRACEFUL_SHUTDOWN_REDIS=false to disable.
24
+ * @param {any} options.redisClient - Redis client instance (required)
29
25
  * @param {string} [options.appName] - Application name (from BaseMetricsClient)
30
26
  * @param {string} [options.dynoId] - Dyno/instance ID (from BaseMetricsClient)
31
27
  * @param {string} [options.processType] - Process type (from BaseMetricsClient)
@@ -56,34 +52,33 @@ class RedisMetricsClient extends BaseMetricsClient {
56
52
  this.redisClient = redisClient;
57
53
  this.redisClientType = getRedisClientType(redisClient);
58
54
 
59
- /** Dedicated Redis connection for subscribe (subscriber mode); closed in cleanup. */
60
- this._subClient = null;
61
- this._initGracefulShutdown(metricsConfig.gracefulShutdownRedis);
55
+ /** Label names for Redis metrics: app + process_type only (no dyno_id). */
56
+ this._redisLabelNames = ['app', 'process_type'];
62
57
 
63
- /** Counter for Redis client connections */
58
+ /** Counter for Redis connection metrics */
64
59
  this.redisConnectionsGauge = this.createGauge({
65
60
  name: 'app_redis_connections_count',
66
61
  help: 'Redis client connections',
67
- labelNames: this.withDefaultLabels(redisConnectionStableFields)
62
+ labelNames: [...this._redisLabelNames, ...redisConnectionStableFields]
68
63
  });
69
64
  this.redisConnectionsMemoryGauge = this.createGauge({
70
65
  name: 'app_redis_connections_memory_usage_count',
71
66
  help: 'Redis client connections',
72
- labelNames: this.withDefaultLabels(redisConnectionStableFields)
67
+ labelNames: [...this._redisLabelNames, ...redisConnectionStableFields]
73
68
  });
74
69
 
75
70
  /** Gauge for Redis memory usage */
76
71
  this.redisMemoryGauge = this.createGauge({
77
72
  name: 'app_redis_memory_bytes',
78
73
  help: 'Redis memory usage in bytes',
79
- labelNames: this.withDefaultLabels(['memory_type'])
74
+ labelNames: [...this._redisLabelNames, 'memory_type']
80
75
  });
81
76
 
82
77
  /** Gauge for Redis operation stats */
83
78
  this.redisStatsGauge = this.createGauge({
84
79
  name: 'app_redis_stats_total',
85
80
  help: 'Redis operation statistics',
86
- labelNames: this.withDefaultLabels(['operation'])
81
+ labelNames: [...this._redisLabelNames, 'operation']
87
82
  });
88
83
 
89
84
  // Track emitted connection label combinations so we can:
@@ -96,194 +91,6 @@ class RedisMetricsClient extends BaseMetricsClient {
96
91
  this._redisConnZeroedKeys = new Set();
97
92
  this._setCleanupHandlers();
98
93
  }
99
-
100
- /**
101
- * Initialize graceful-shutdown state and subscribe when enabled. Called from constructor.
102
- * @param {boolean} [gracefulShutdownRedis] - Explicit false to disable; otherwise enabled unless METRICS_GRACEFUL_SHUTDOWN_REDIS=false.
103
- */
104
- _initGracefulShutdown(gracefulShutdownRedis) {
105
- const disabledByParam = gracefulShutdownRedis === false;
106
- const disabledByEnv = process.env.METRICS_GRACEFUL_SHUTDOWN_REDIS === 'false';
107
- this._gracefulShutdownRedis = !disabledByParam && !disabledByEnv;
108
- this._gracefulShutdownStream = this._gracefulShutdownRedis ? `metrics:graceful-shutdown:${this.appName}:${this.processType}` : null;
109
- this._gracefulShutdownAckChannel = this._gracefulShutdownRedis ? `metrics:graceful-shutdown-ack:${this.appName}:${this.processType}` : null;
110
- this._gracefulShutdownLogPrefix = `[graceful-shutdown] [${this.processType}] [${this.appName}] [${this.dynoId}]`;
111
- if (this._gracefulShutdownRedis && this._gracefulShutdownStream) {
112
- this._setupGracefulShutdownSubscribe();
113
- }
114
- }
115
-
116
- /**
117
- * Create a dedicated Redis client for subscribe (pub/sub). Uses duplicate() when available, else createClient from REDIS_URL. Branches by redisClientType (IOREDIS, REDIS_V3, REDIS_V4).
118
- * @returns {any|null} Subscriber client or null if not possible.
119
- */
120
- _createSubscriberClient() {
121
- if (this.redisClientType === IOREDIS && this.redisClient && typeof this.redisClient.duplicate === 'function') {
122
- return this.redisClient.duplicate();
123
- }
124
- if ((this.redisClientType === REDIS_V3 || this.redisClientType === REDIS_V4) && this.redisClient && typeof this.redisClient.duplicate === 'function') {
125
- return this.redisClient.duplicate();
126
- }
127
- if ((this.redisClientType === REDIS_V3 || this.redisClientType === REDIS_V4) && process.env.REDIS_URL) {
128
- try {
129
- const redis = require('redis');
130
- if (typeof redis.createClient !== 'function') return null;
131
- try {
132
- return redis.createClient({
133
- url: process.env.REDIS_URL
134
- });
135
- } catch {
136
- return redis.createClient(process.env.REDIS_URL);
137
- }
138
- } catch {
139
- return null;
140
- }
141
- }
142
- return null;
143
- }
144
-
145
- /**
146
- * Set up Redis subscribe for graceful shutdown. Uses _createSubscriberClient() so subscriber matches client type (ioredis vs node-redis v3/v4).
147
- */
148
- /**
149
- * Set up Redis stream read for graceful shutdown. Uses _createSubscriberClient() and XREAD BLOCK; stream is trimmed (MAXLEN and MINID) so messages are not kept in Redis forever.
150
- */
151
- _setupGracefulShutdownSubscribe() {
152
- const streamKey = this._gracefulShutdownStream;
153
- if (!streamKey) return;
154
- const subClient = this._createSubscriberClient();
155
- if (subClient && typeof subClient.on === 'function') {
156
- subClient.on('error', () => {});
157
- }
158
- if (!subClient) return;
159
- this._subClient = subClient;
160
- this._streamReadLoop(streamKey);
161
- }
162
- _streamReadLoop(streamKey) {
163
- const self = this;
164
- const blockMs = 5000;
165
- const runRead = () => {
166
- if (!self._subClient) return;
167
- self._xreadBlock(streamKey, blockMs).then(entries => {
168
- if (!entries || entries.length === 0) {
169
- setImmediate(runRead);
170
- return;
171
- }
172
- self._cleanupAndPublishAck();
173
- }).catch(() => {
174
- setImmediate(runRead);
175
- });
176
- };
177
- runRead();
178
- }
179
- _xreadBlock(streamKey, blockMs) {
180
- const client = this._subClient || this.redisClient;
181
- if (!client) return Promise.resolve([]);
182
- if (this.redisClientType === REDIS_V3) {
183
- return new Promise((resolve, reject) => {
184
- client.send_command('XREAD', ['BLOCK', String(blockMs), 'STREAMS', streamKey, '$'], (err, result) => {
185
- if (err) return reject(err);
186
- resolve(this._parseXreadReply(result, streamKey));
187
- });
188
- });
189
- }
190
- if (this.redisClientType === REDIS_V4) {
191
- const p = client.sendCommand(['XREAD', 'BLOCK', String(blockMs), 'STREAMS', streamKey, '$']);
192
- return Promise.resolve(p).then(result => this._parseXreadReply(result, streamKey)).catch(() => []);
193
- }
194
- if (this.redisClientType === IOREDIS) {
195
- const p = client.call('XREAD', 'BLOCK', blockMs, 'STREAMS', streamKey, '$');
196
- return Promise.resolve(p).then(result => this._parseXreadReply(result, streamKey)).catch(() => []);
197
- }
198
- return Promise.resolve([]);
199
- }
200
- _parseXreadReply(reply, streamKey) {
201
- if (!reply || !Array.isArray(reply)) return [];
202
- const streamReply = reply.find(r => r && r[0] === streamKey);
203
- if (!streamReply || !Array.isArray(streamReply[1])) return [];
204
- return streamReply[1].map(entry => Array.isArray(entry) ? [entry[0], entry[1] || []] : [entry, []]);
205
- }
206
-
207
- /**
208
- * Old instance: stop push, clear metrics from VM, then publish ack so new can start; then exit.
209
- */
210
- async _cleanupAndPublishAck() {
211
- this.stopPush();
212
- if (this.enabled) {
213
- await this.gatewayDelete();
214
- }
215
- await this._publishAck();
216
- if (this._subClient) {
217
- try {
218
- if (this.redisClientType === REDIS_V3) {
219
- await new Promise((resolve, reject) => {
220
- if (typeof this._subClient.quit === 'function') {
221
- this._subClient.quit(err => err ? reject(err) : resolve());
222
- } else resolve();
223
- });
224
- } else if (this.redisClientType === REDIS_V4) {
225
- if (this._subClient.quit) await this._subClient.quit();
226
- } else if (this.redisClientType === IOREDIS) {
227
- if (this._subClient.disconnect) await this._subClient.disconnect();
228
- }
229
- } catch {
230
- // ignore
231
- }
232
- this._subClient = null;
233
- }
234
- try {
235
- if (this.redisClient) {
236
- if (this.redisClientType === REDIS_V3 || this.redisClientType === REDIS_V4) {
237
- await this.redisClient.quit();
238
- } else if (this.redisClientType === IOREDIS) {
239
- await this.redisClient.disconnect();
240
- }
241
- }
242
- } catch {
243
- // ignore
244
- }
245
- process.exit(0);
246
- }
247
- _publishAck() {
248
- const ackChannel = this._gracefulShutdownAckChannel;
249
- if (!ackChannel || !this.redisClient) return Promise.resolve();
250
- console.warn(`${this._gracefulShutdownLogPrefix} OLD: clearing metrics and exiting.`);
251
- const msg = this.dynoId || 'stopped';
252
- if (this.redisClientType === REDIS_V3) {
253
- return new Promise(resolve => {
254
- this.redisClient.send_command('PUBLISH', [ackChannel, msg], () => resolve());
255
- });
256
- }
257
- if (this.redisClientType === REDIS_V4) {
258
- return this.redisClient.sendCommand(['PUBLISH', ackChannel, msg]).catch(() => {});
259
- }
260
- if (this.redisClientType === IOREDIS) {
261
- return this.redisClient.publish(ackChannel, msg).catch(() => {});
262
- }
263
- return Promise.resolve();
264
- }
265
-
266
- /**
267
- * Publish "new instance started" to stream so old instances exit. Stream is trimmed (MAXLEN ~ 10 and MINID older than 1 min) so messages are not kept in Redis forever.
268
- */
269
- _publishNewInstanceStarted() {
270
- const streamKey = this._gracefulShutdownStream;
271
- if (!streamKey || !this.redisClient) return;
272
- const value = this.dynoId || '1';
273
- const noop = () => {};
274
- const maxAgeMs = GRACEFUL_SHUTDOWN_STREAM_MAXAGE_MS;
275
- const minId = `${Date.now() - maxAgeMs}-0`;
276
- if (this.redisClientType === REDIS_V3) {
277
- this.redisClient.send_command('XADD', [streamKey, 'MAXLEN', '~', '10', '*', 'dyno_id', value], noop);
278
- this.redisClient.send_command('XTRIM', [streamKey, 'MINID', minId], noop);
279
- } else if (this.redisClientType === REDIS_V4) {
280
- this.redisClient.sendCommand(['XADD', streamKey, 'MAXLEN', '~', '10', '*', 'dyno_id', value]).catch(noop);
281
- this.redisClient.sendCommand(['XTRIM', streamKey, 'MINID', minId]).catch(noop);
282
- } else if (this.redisClientType === IOREDIS) {
283
- this.redisClient.call('XADD', streamKey, 'MAXLEN', '~', 10, '*', 'dyno_id', value).catch(noop);
284
- this.redisClient.call('XTRIM', streamKey, 'MINID', minId).catch(noop);
285
- }
286
- }
287
94
  getRedisConnections = async () => {
288
95
  if (!this.redisClient) throw new Error('Redis client not provided');
289
96
 
@@ -361,7 +168,10 @@ class RedisMetricsClient extends BaseMetricsClient {
361
168
  collectRedisMetrics = async () => {
362
169
  try {
363
170
  const [memoryInfoStr, statsInfoStr, connectionsInfoStr] = await Promise.all([this.getRedisInfo('memory'), this.getRedisInfo('stats'), this.getRedisConnections()]);
364
- const labels = this.getDefaultLabels();
171
+ const labels = {
172
+ app: this.appName,
173
+ process_type: this.processType
174
+ };
365
175
  const connections = this.parseRedisConnections(connectionsInfoStr);
366
176
  if (this.logValues) {
367
177
  // "IN" data: raw client list from Redis
@@ -497,7 +307,7 @@ class RedisMetricsClient extends BaseMetricsClient {
497
307
  }, parseInt(stats.instantaneous_ops_per_sec, 10) || 0);
498
308
  }
499
309
  } catch (error) {
500
- console.error(`[queue-metrics] Failed to collect Redis metrics:`, error.message);
310
+ console.warn(`[queue-metrics] Failed to collect Redis metrics:`, error.message);
501
311
  }
502
312
  };
503
313
 
@@ -510,6 +320,10 @@ class RedisMetricsClient extends BaseMetricsClient {
510
320
  await this.collectRedisMetrics();
511
321
  await this.gatewayPush();
512
322
  this.clearAllCounters();
323
+ if (this.metricsLogValues) {
324
+ const metricObjects = await this.registry.getMetricsAsJSON();
325
+ console.info(`[queue-metrics] Collected metrics for Redis`, JSON.stringify(metricObjects, null, 2));
326
+ }
513
327
  } catch (error) {
514
328
  console.error(`[queue-metrics] Failed to collect Redis metrics: ${error.message}`);
515
329
  throw error;
@@ -517,7 +331,8 @@ class RedisMetricsClient extends BaseMetricsClient {
517
331
  };
518
332
 
519
333
  /**
520
- * Start periodic collection. When graceful shutdown is on: new publishes "new started" so old exits and clears; new does not push until after one interval (skipFirstPush), giving old time to stop.
334
+ * Start periodic collection.
335
+ * @param {number} [intervalSec=this.intervalSec] - Interval in seconds
521
336
  */
522
337
  startPush = (intervalSec = this.intervalSec) => {
523
338
  this._startPush(intervalSec, () => {
@@ -525,39 +340,13 @@ class RedisMetricsClient extends BaseMetricsClient {
525
340
  console.error(`[queue-metrics] Failed to push Redis metrics:`, err);
526
341
  });
527
342
  });
528
- if (this._gracefulShutdownRedis) {
529
- this._publishNewInstanceStarted();
530
- }
531
343
  };
532
344
 
533
345
  /**
534
346
  * Cleanup Redis client and exit process.
535
- * Stops push, deletes this instance's metrics from VM (if removeOldMetrics), closes subscriber and main Redis, then exits.
536
347
  * @returns {Promise<void>}
537
348
  */
538
349
  cleanup = async () => {
539
- this.stopPush();
540
- if (this.enabled) {
541
- await this.gatewayDelete();
542
- }
543
- if (this._subClient) {
544
- try {
545
- if (this.redisClientType === REDIS_V3) {
546
- await new Promise((resolve, reject) => {
547
- if (typeof this._subClient.quit === 'function') {
548
- this._subClient.quit(err => err ? reject(err) : resolve());
549
- } else resolve();
550
- });
551
- } else if (this.redisClientType === REDIS_V4) {
552
- if (this._subClient.quit) await this._subClient.quit();
553
- } else if (this.redisClientType === IOREDIS) {
554
- if (this._subClient.disconnect) await this._subClient.disconnect();
555
- }
556
- } catch (err) {
557
- console.error('[queue-metrics] Error closing subscriber client:', err);
558
- }
559
- this._subClient = null;
560
- }
561
350
  try {
562
351
  if (!this.redisClient) return;
563
352
  if (this.redisClientType === REDIS_V3 || this.redisClientType === REDIS_V4) {
@@ -568,7 +357,7 @@ class RedisMetricsClient extends BaseMetricsClient {
568
357
  } catch (err) {
569
358
  console.error('[queue-metrics] Error closing Redis client:', err);
570
359
  }
571
- await super.cleanup();
360
+ process.exit(0);
572
361
  };
573
362
  _setCleanupHandlers = () => {
574
363
  process.on('SIGINT', this.cleanup);