@adalo/metrics 0.0.0-staging.1

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.
Files changed (85) hide show
  1. package/.env.example +14 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc +61 -0
  4. package/.github/pull_request_template.md +14 -0
  5. package/.github/workflows/code-style.yml +29 -0
  6. package/.github/workflows/deploy-staging.yml +34 -0
  7. package/.github/workflows/deploy.yml +29 -0
  8. package/.github/workflows/tests.yml +17 -0
  9. package/.idea/codeStyles/Project.xml +101 -0
  10. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  11. package/.idea/git_toolbox_prj.xml +15 -0
  12. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  13. package/.idea/jsLibraryMappings.xml +6 -0
  14. package/.idea/prettier.xml +6 -0
  15. package/.idea/vcs.xml +6 -0
  16. package/.prettierrc +10 -0
  17. package/README-health.md +234 -0
  18. package/README.md +120 -0
  19. package/__tests__/metricsRedisClient.test.js +138 -0
  20. package/babel.config.js +20 -0
  21. package/lib/health/databaseChecker.d.ts +43 -0
  22. package/lib/health/databaseChecker.d.ts.map +1 -0
  23. package/lib/health/databaseChecker.js +189 -0
  24. package/lib/health/databaseChecker.js.map +1 -0
  25. package/lib/health/healthCheckCache.d.ts +59 -0
  26. package/lib/health/healthCheckCache.d.ts.map +1 -0
  27. package/lib/health/healthCheckCache.js +187 -0
  28. package/lib/health/healthCheckCache.js.map +1 -0
  29. package/lib/health/healthCheckClient.d.ts +124 -0
  30. package/lib/health/healthCheckClient.d.ts.map +1 -0
  31. package/lib/health/healthCheckClient.js +324 -0
  32. package/lib/health/healthCheckClient.js.map +1 -0
  33. package/lib/health/healthCheckUtils.d.ts +52 -0
  34. package/lib/health/healthCheckUtils.d.ts.map +1 -0
  35. package/lib/health/healthCheckUtils.js +129 -0
  36. package/lib/health/healthCheckUtils.js.map +1 -0
  37. package/lib/health/healthCheckWorker.d.ts +2 -0
  38. package/lib/health/healthCheckWorker.d.ts.map +1 -0
  39. package/lib/health/healthCheckWorker.js +70 -0
  40. package/lib/health/healthCheckWorker.js.map +1 -0
  41. package/lib/index.d.ts +10 -0
  42. package/lib/index.d.ts.map +1 -0
  43. package/lib/index.js +105 -0
  44. package/lib/index.js.map +1 -0
  45. package/lib/metrics/baseMetricsClient.d.ts +174 -0
  46. package/lib/metrics/baseMetricsClient.d.ts.map +1 -0
  47. package/lib/metrics/baseMetricsClient.js +428 -0
  48. package/lib/metrics/baseMetricsClient.js.map +1 -0
  49. package/lib/metrics/metricsClient.d.ts +95 -0
  50. package/lib/metrics/metricsClient.d.ts.map +1 -0
  51. package/lib/metrics/metricsClient.js +239 -0
  52. package/lib/metrics/metricsClient.js.map +1 -0
  53. package/lib/metrics/metricsDatabaseClient.d.ts +74 -0
  54. package/lib/metrics/metricsDatabaseClient.d.ts.map +1 -0
  55. package/lib/metrics/metricsDatabaseClient.js +218 -0
  56. package/lib/metrics/metricsDatabaseClient.js.map +1 -0
  57. package/lib/metrics/metricsQueueRedisClient.d.ts +57 -0
  58. package/lib/metrics/metricsQueueRedisClient.d.ts.map +1 -0
  59. package/lib/metrics/metricsQueueRedisClient.js +277 -0
  60. package/lib/metrics/metricsQueueRedisClient.js.map +1 -0
  61. package/lib/metrics/metricsRedisClient.d.ts +71 -0
  62. package/lib/metrics/metricsRedisClient.d.ts.map +1 -0
  63. package/lib/metrics/metricsRedisClient.js +370 -0
  64. package/lib/metrics/metricsRedisClient.js.map +1 -0
  65. package/lib/redisUtils.d.ts +53 -0
  66. package/lib/redisUtils.d.ts.map +1 -0
  67. package/lib/redisUtils.js +140 -0
  68. package/lib/redisUtils.js.map +1 -0
  69. package/package.json +66 -0
  70. package/scripts/README.md +43 -0
  71. package/scripts/clearMetrics.js +6 -0
  72. package/src/health/databaseChecker.js +183 -0
  73. package/src/health/healthCheckCache.js +216 -0
  74. package/src/health/healthCheckClient.js +347 -0
  75. package/src/health/healthCheckUtils.js +125 -0
  76. package/src/health/healthCheckWorker.js +71 -0
  77. package/src/index.ts +9 -0
  78. package/src/metrics/baseMetricsClient.js +494 -0
  79. package/src/metrics/metricsClient.js +284 -0
  80. package/src/metrics/metricsDatabaseClient.js +236 -0
  81. package/src/metrics/metricsQueueRedisClient.js +352 -0
  82. package/src/metrics/metricsRedisClient.js +417 -0
  83. package/src/redisUtils.js +155 -0
  84. package/tsconfig.json +19 -0
  85. package/tsconfig.types.json +11 -0
@@ -0,0 +1,417 @@
1
+ const { BaseMetricsClient } = require('./baseMetricsClient')
2
+ const {
3
+ getRedisClientType,
4
+ REDIS_V4,
5
+ IOREDIS,
6
+ REDIS_V3,
7
+ } = require('../redisUtils')
8
+
9
+ const redisConnectionStableFields = ['name', 'flags', 'cmd']
10
+ const redisConnectionFields = ['name', 'flags', 'tot-mem', 'cmd']
11
+
12
+ /**
13
+ * RedisMetricsClient extends BaseMetricsClient to collect
14
+ * Redis metrics periodically and push them to Prometheus Pushgateway.
15
+ *
16
+ * @extends BaseMetricsClient
17
+ */
18
+ class RedisMetricsClient extends BaseMetricsClient {
19
+ /**
20
+ * @param {Object} options
21
+ * @param {any} options.redisClient - Redis client instance (required)
22
+ * @param {string} [options.appName] - Application name (from BaseMetricsClient)
23
+ * @param {string} [options.dynoId] - Dyno/instance ID (from BaseMetricsClient)
24
+ * @param {string} [options.processType] - Process type (from BaseMetricsClient)
25
+ * @param {boolean} [options.enabled] - Enable metrics collection (from BaseMetricsClient)
26
+ * @param {boolean} [options.logValues] - Log metrics values (from BaseMetricsClient)
27
+ * @param {string} [options.pushgatewayUrl] - PushGateway URL (from BaseMetricsClient)
28
+ * @param {string} [options.pushgatewaySecret] - PushGateway secret token (from BaseMetricsClient)
29
+ * @param {number} [options.intervalSec] - Interval in seconds for pushing metrics (from BaseMetricsClient)
30
+ * @param {boolean} [options.removeOldMetrics] - Remove old metrics by service (from BaseMetricsClient)
31
+ * @param {function} [options.startupValidation] - Function to validate startup (from BaseMetricsClient)
32
+ * @param {boolean} [options.disablePushgateway] - Disable pushing to Pushgateway (use HTTP scraping instead)
33
+ */
34
+ constructor({ redisClient, ...metricsConfig } = {}) {
35
+ if (redisClient == null) {
36
+ throw new Error('RedisMetricsClient requires redisClient')
37
+ }
38
+
39
+ const intervalSec =
40
+ metricsConfig.intervalSec ||
41
+ parseInt(process.env.METRICS_QUEUE_INTERVAL_SEC || '', 10) ||
42
+ 5
43
+
44
+ super({
45
+ ...metricsConfig,
46
+ processType: metricsConfig.processType || 'queue-metrics',
47
+ intervalSec,
48
+ })
49
+
50
+ /** Redis client used for metrics */
51
+ this.redisClient = redisClient
52
+ this.redisClientType = getRedisClientType(redisClient)
53
+
54
+ /** Label names for Redis metrics: app + process_type only (no dyno_id). */
55
+ this._redisLabelNames = ['app', 'process_type']
56
+
57
+ /** Counter for Redis connection metrics */
58
+ this.redisConnectionsGauge = this.createGauge({
59
+ name: 'app_redis_connections_count',
60
+ help: 'Redis client connections',
61
+ labelNames: [...this._redisLabelNames, ...redisConnectionStableFields],
62
+ })
63
+
64
+ this.redisConnectionsMemoryGauge = this.createGauge({
65
+ name: 'app_redis_connections_memory_usage_count',
66
+ help: 'Redis client connections',
67
+ labelNames: [...this._redisLabelNames, ...redisConnectionStableFields],
68
+ })
69
+
70
+ /** Gauge for Redis memory usage */
71
+ this.redisMemoryGauge = this.createGauge({
72
+ name: 'app_redis_memory_bytes',
73
+ help: 'Redis memory usage in bytes',
74
+ labelNames: [...this._redisLabelNames, 'memory_type'],
75
+ })
76
+
77
+ /** Gauge for Redis operation stats */
78
+ this.redisStatsGauge = this.createGauge({
79
+ name: 'app_redis_stats_total',
80
+ help: 'Redis operation statistics',
81
+ labelNames: [...this._redisLabelNames, 'operation'],
82
+ })
83
+
84
+ // Track emitted connection label combinations so we can:
85
+ // - emit a one-shot 0 for series that disappear (overwrite last non-zero sample)
86
+ // - then stop emitting them on subsequent scrapes
87
+ //
88
+ // This is mainly needed because we label connections by `cmd`,
89
+ // and Redis `CLIENT LIST` `cmd` is volatile.
90
+ this._redisConnSeenKeys = new Set()
91
+ this._redisConnZeroedKeys = new Set()
92
+
93
+ this._setCleanupHandlers()
94
+ }
95
+
96
+ getRedisConnections = async () => {
97
+ if (!this.redisClient) throw new Error('Redis client not provided')
98
+
99
+ // node-redis v3 (uses callback)
100
+ if (this.redisClientType === REDIS_V3) {
101
+ return new Promise((resolve, reject) => {
102
+ this.redisClient.send_command('CLIENT', ['LIST'], (err, result) => {
103
+ if (err) {
104
+ reject(new Error(`Failed to get CLIENT LIST: ${err.message}`))
105
+ } else resolve(result)
106
+ })
107
+ })
108
+ }
109
+
110
+ // node-redis v4
111
+ if (this.redisClientType === REDIS_V4) {
112
+ try {
113
+ return this.redisClient.sendCommand(['CLIENT', 'LIST'])
114
+ } catch (err) {
115
+ throw new Error(`Failed to get CLIENT LIST: ${err.message}`)
116
+ }
117
+ }
118
+
119
+ if (this.redisClientType === IOREDIS) {
120
+ try {
121
+ return this.redisClient.client('LIST')
122
+ } catch (err) {
123
+ throw new Error(`Failed to get CLIENT LIST: ${err.message}`)
124
+ }
125
+ }
126
+
127
+ throw new Error('Unsupported Redis client type')
128
+ }
129
+
130
+ getRedisInfo = async section => {
131
+ if (!this.redisClient) throw new Error('Redis client not provided')
132
+
133
+ // node-redis v3 (uses callback)
134
+ if (this.redisClientType === REDIS_V3) {
135
+ return new Promise((resolve, reject) => {
136
+ this.redisClient.info(section, (err, result) => {
137
+ if (err) reject(err)
138
+ else resolve(result)
139
+ })
140
+ })
141
+ }
142
+
143
+ // node-redis v4 or ioredis (info returns Promise)
144
+ if (this.redisClientType === REDIS_V4 || this.redisClientType === IOREDIS) {
145
+ try {
146
+ return this.redisClient.info(section)
147
+ } catch (err) {
148
+ throw new Error(`Failed to get Redis INFO: ${err.message}`)
149
+ }
150
+ }
151
+
152
+ throw new Error('Unsupported Redis client type')
153
+ }
154
+
155
+ parseRedisConnections = clientsStr => {
156
+ return clientsStr
157
+ .split('\n')
158
+ .filter(line => line.trim() !== '')
159
+ .map(line => {
160
+ const parts = line.split(' ')
161
+ const client = {}
162
+ parts.forEach(p => {
163
+ const eqIdx = p.indexOf('=')
164
+ if (eqIdx === -1) return
165
+ const k = p.slice(0, eqIdx)
166
+ const v = p.slice(eqIdx + 1)
167
+ if (redisConnectionFields.includes(k)) {
168
+ client[k] = v
169
+ }
170
+ })
171
+ return client
172
+ })
173
+ }
174
+
175
+ /**
176
+ * Collect basic Redis INFO metrics: clients, memory, stats
177
+ * @returns {Promise<void>}
178
+ */
179
+ collectRedisMetrics = async () => {
180
+ try {
181
+ const [memoryInfoStr, statsInfoStr, connectionsInfoStr] =
182
+ await Promise.all([
183
+ this.getRedisInfo('memory'),
184
+ this.getRedisInfo('stats'),
185
+ this.getRedisConnections(),
186
+ ])
187
+
188
+ const labels = { app: this.appName, process_type: this.processType }
189
+
190
+ const connections = this.parseRedisConnections(connectionsInfoStr)
191
+
192
+ if (this.logValues) {
193
+ // "IN" data: raw client list from Redis
194
+ console.log(
195
+ '[queue-metrics] Redis CLIENT LIST (raw):\n',
196
+ connectionsInfoStr
197
+ )
198
+ console.log(
199
+ '[queue-metrics] Redis CLIENT LIST (raw) length:',
200
+ connectionsInfoStr.length
201
+ )
202
+
203
+ // "OUT" data: parsed fields used for metrics
204
+ console.log(
205
+ '[queue-metrics] Redis CLIENT LIST (parsed) count:',
206
+ connections.length
207
+ )
208
+ console.log(
209
+ '[queue-metrics] Redis CLIENT LIST (parsed sample, first 10):',
210
+ JSON.stringify(connections.slice(0, 10), null, 2)
211
+ )
212
+
213
+ const missing = { name: 0, flags: 0, cmd: 0, 'tot-mem': 0 }
214
+ connections.forEach(c => {
215
+ if (!c.name) missing.name += 1
216
+ if (!c.flags) missing.flags += 1
217
+ if (!c.cmd) missing.cmd += 1
218
+ if (!c['tot-mem']) missing['tot-mem'] += 1
219
+ })
220
+ console.log(
221
+ '[queue-metrics] Redis CLIENT LIST (parsed) missing fields:',
222
+ missing
223
+ )
224
+ }
225
+
226
+ const grouped = {}
227
+ connections.forEach(conn => {
228
+ const { name, flags, 'tot-mem': totMem, cmd } = conn
229
+
230
+ // build grouping key (includes default gauge labels later)
231
+ const key = JSON.stringify({ name, flags, cmd })
232
+
233
+ if (!grouped[key]) {
234
+ grouped[key] = {
235
+ labels: { name, flags, cmd },
236
+ count: 0,
237
+ memory: 0,
238
+ }
239
+ }
240
+
241
+ grouped[key].count += 1
242
+ const mem = parseInt(totMem, 10)
243
+ grouped[key].memory += Number.isFinite(mem) ? mem : 0
244
+ })
245
+
246
+ // Ensure sets exist even if older instance is hot-reloaded.
247
+ if (!this._redisConnSeenKeys) this._redisConnSeenKeys = new Set()
248
+ if (!this._redisConnZeroedKeys) this._redisConnZeroedKeys = new Set()
249
+
250
+ const currentKeys = new Set(Object.keys(grouped))
251
+ for (const k of currentKeys) {
252
+ this._redisConnSeenKeys.add(k)
253
+ if (this._redisConnZeroedKeys.has(k)) {
254
+ this._redisConnZeroedKeys.delete(k)
255
+ }
256
+ }
257
+
258
+ // Reset gauges each scrape so we only export:
259
+ // - current snapshot series
260
+ // - one-shot zeros for recently disappeared series
261
+ this.redisConnectionsGauge.reset()
262
+ this.redisConnectionsMemoryGauge.reset()
263
+
264
+ // Emit one-shot zeros for series that disappeared since last seen.
265
+ for (const k of this._redisConnSeenKeys) {
266
+ if (currentKeys.has(k)) continue
267
+ if (this._redisConnZeroedKeys.has(k)) continue
268
+ try {
269
+ const valueLabels = JSON.parse(k)
270
+ this.redisConnectionsGauge.set({ ...labels, ...valueLabels }, 0)
271
+ this.redisConnectionsMemoryGauge.set({ ...labels, ...valueLabels }, 0)
272
+ this._redisConnZeroedKeys.add(k)
273
+ } catch {
274
+ // ignore malformed key
275
+ }
276
+ }
277
+
278
+ if (this.logValues) {
279
+ const groups = Object.values(grouped)
280
+ const groupedTotal = groups.reduce((sum, g) => sum + (g.count || 0), 0)
281
+ console.log(
282
+ '[queue-metrics] Redis connections grouped buckets:',
283
+ groups.length
284
+ )
285
+ console.log(
286
+ '[queue-metrics] Redis connections grouped total:',
287
+ groupedTotal
288
+ )
289
+ console.log(
290
+ '[queue-metrics] Redis connections seen keys:',
291
+ this._redisConnSeenKeys.size
292
+ )
293
+ console.log(
294
+ '[queue-metrics] Redis connections zeroed keys:',
295
+ this._redisConnZeroedKeys.size
296
+ )
297
+ console.log(
298
+ '[queue-metrics] Redis connections grouped sample (first 10):',
299
+ JSON.stringify(groups.slice(0, 10), null, 2)
300
+ )
301
+ }
302
+
303
+ Object.values(grouped).forEach(
304
+ ({ labels: valueLabels, count, memory }) => {
305
+ this.redisConnectionsGauge.set({ ...labels, ...valueLabels }, count)
306
+ this.redisConnectionsMemoryGauge.set(
307
+ { ...labels, ...valueLabels },
308
+ memory
309
+ )
310
+ }
311
+ )
312
+
313
+ const parseRedisInfo = infoStr =>
314
+ Object.fromEntries(
315
+ infoStr
316
+ .split('\r\n')
317
+ .filter(line => line && !line.startsWith('#'))
318
+ .map(line => line.split(':', 2))
319
+ .filter(parts => parts.length === 2 && parts[0] && parts[1])
320
+ )
321
+
322
+ const memory = parseRedisInfo(memoryInfoStr)
323
+ const stats = parseRedisInfo(statsInfoStr)
324
+
325
+ if (memory.used_memory) {
326
+ this.redisMemoryGauge.set(
327
+ { ...labels, memory_type: 'used' },
328
+ parseInt(memory.used_memory, 10) || 0
329
+ )
330
+ }
331
+ if (memory.maxmemory) {
332
+ this.redisMemoryGauge.set(
333
+ { ...labels, memory_type: 'max' },
334
+ parseInt(memory.maxmemory, 10) || 0
335
+ )
336
+ }
337
+
338
+ if (stats.instantaneous_ops_per_sec) {
339
+ this.redisStatsGauge.set(
340
+ { ...labels, operation: 'ops_per_sec' },
341
+ parseInt(stats.instantaneous_ops_per_sec, 10) || 0
342
+ )
343
+ }
344
+ } catch (error) {
345
+ console.warn(
346
+ `[queue-metrics] Failed to collect Redis metrics:`,
347
+ error.message
348
+ )
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Collect metrics for all Redis and push to Prometheus Pushgateway
354
+ * @returns {Promise<void>}
355
+ */
356
+ pushRedisMetrics = async () => {
357
+ try {
358
+ await this.collectRedisMetrics()
359
+ await this.gatewayPush()
360
+ this.clearAllCounters()
361
+
362
+ if (this.metricsLogValues) {
363
+ const metricObjects = await this.registry.getMetricsAsJSON()
364
+ console.info(
365
+ `[queue-metrics] Collected metrics for Redis`,
366
+ JSON.stringify(metricObjects, null, 2)
367
+ )
368
+ }
369
+ } catch (error) {
370
+ console.error(
371
+ `[queue-metrics] Failed to collect Redis metrics: ${error.message}`
372
+ )
373
+ throw error
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Start periodic collection.
379
+ * @param {number} [intervalSec=this.intervalSec] - Interval in seconds
380
+ */
381
+ startPush = (intervalSec = this.intervalSec) => {
382
+ this._startPush(intervalSec, () => {
383
+ this.pushRedisMetrics().catch(err => {
384
+ console.error(`[queue-metrics] Failed to push Redis metrics:`, err)
385
+ })
386
+ })
387
+ }
388
+
389
+ /**
390
+ * Cleanup Redis client and exit process.
391
+ * @returns {Promise<void>}
392
+ */
393
+ cleanup = async () => {
394
+ try {
395
+ if (!this.redisClient) return
396
+
397
+ if (
398
+ this.redisClientType === REDIS_V3 ||
399
+ this.redisClientType === REDIS_V4
400
+ ) {
401
+ await this.redisClient.quit()
402
+ } else if (this.redisClientType === IOREDIS) {
403
+ await this.redisClient.disconnect()
404
+ }
405
+ } catch (err) {
406
+ console.error('[queue-metrics] Error closing Redis client:', err)
407
+ }
408
+ process.exit(0)
409
+ }
410
+
411
+ _setCleanupHandlers = () => {
412
+ process.on('SIGINT', this.cleanup)
413
+ process.on('SIGTERM', this.cleanup)
414
+ }
415
+ }
416
+
417
+ module.exports = { RedisMetricsClient }
@@ -0,0 +1,155 @@
1
+ const REDIS_V4 = 'REDIS_V4'
2
+ const REDIS_V3 = 'REDIS_V3'
3
+ const IOREDIS = 'IOREDIS'
4
+
5
+ const dyno = process.env.BUILD_DYNO_PROCESS_TYPE || 'undefined-dyno'
6
+ const defaultAppName = process.env.BUILD_APP_NAME
7
+
8
+ /**
9
+ * Get the default Redis client name.
10
+ *
11
+ * @param {Object} options - Options for generating Redis name.
12
+ * @param {string} [options.name='undefined-name'] - Fallback name if none is provided.
13
+ * @param {string} [options.appName] - Application name. Defaults to `defaultAppName` if not set.
14
+ * @param {string} [options.processName] - Process name. Defaults to `dyno` if not set.
15
+ * @returns {string} The generated Redis client name.
16
+ */
17
+ const getRedisName = ({ name = 'undefined-name', appName, processName }) => {
18
+ return `${appName || defaultAppName || 'undefined-app'}:${
19
+ processName || dyno
20
+ }:${name}`
21
+ }
22
+
23
+ /**
24
+ * Creates a configured setClientName function for node-redis v3.
25
+ *
26
+ * @param {string} [appName='undefined-app'] - Fallback app name if BUILD_APP_NAME is not set.
27
+ * @returns {(client: any, name: string) => void}
28
+ */
29
+ const createSetClientNameForRedisV3 = (appName = 'undefined-app') => {
30
+ return (client, name) => {
31
+ if (process.env.NODE_ENV !== 'test') {
32
+ client.on('connect', () => {
33
+ client.send_command(
34
+ 'CLIENT',
35
+ [
36
+ 'SETNAME',
37
+ getRedisName({ name, appName: defaultAppName || appName }),
38
+ ],
39
+ err => {
40
+ if (err) {
41
+ console.error(`Failed to set client name for ${name}:`, err)
42
+ } else {
43
+ console.log(`Connected to Redis for pid:${process.pid} (${name})`)
44
+ }
45
+ }
46
+ )
47
+ })
48
+ }
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Creates a function to set Redis client name for ioredis.
54
+ *
55
+ * @param {string} [appName='undefined-app']
56
+ * @returns {(client: any, name: string) => void}
57
+ */
58
+ const createSetClientNameForIoredis = (appName = 'undefined-app') => {
59
+ return (client, name) => {
60
+ if (process.env.NODE_ENV !== 'test') {
61
+ client.once('connect', () => {
62
+ client
63
+ .call('CLIENT', [
64
+ 'SETNAME',
65
+ getRedisName({ name, appName: defaultAppName || appName }),
66
+ ])
67
+ .then(() => {
68
+ console.log(`Connected to Redis for pid:${process.pid} (${name})`)
69
+ })
70
+ .catch(err => {
71
+ console.error(`Failed to set client name for ${name}:`, err)
72
+ })
73
+ })
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Creates a function to set Redis client name for node-redis v4.
80
+ *
81
+ * @param {string} [appName='undefined-app']
82
+ * @returns {(client: any, name: string) => void}
83
+ */
84
+ const createSetClientNameForRedisV4 = (appName = 'undefined-app') => {
85
+ return (client, name) => {
86
+ if (process.env.NODE_ENV !== 'test') {
87
+ client.on('ready', async () => {
88
+ try {
89
+ await client.sendCommand([
90
+ 'CLIENT',
91
+ 'SETNAME',
92
+ getRedisName({ name, appName: defaultAppName || appName }),
93
+ ])
94
+ console.log(`Connected to Redis for pid:${process.pid} (${name})`)
95
+ } catch (err) {
96
+ console.error(`Failed to set client name for ${name}:`, err)
97
+ }
98
+ })
99
+ }
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Check if a Redis client is an ioredis instance
105
+ *
106
+ * @param {any} client - Redis client instance
107
+ * @returns {boolean} True if the client is ioredis
108
+ */
109
+ const isIORedis = client => {
110
+ return (
111
+ client &&
112
+ typeof client.sendCommand === 'function' &&
113
+ typeof client.disconnect === 'function' &&
114
+ client.options !== undefined
115
+ )
116
+ }
117
+
118
+ /**
119
+ * Get Redis client type
120
+ *
121
+ * @param {any} client - Redis client instance
122
+ * @returns {string} One of IOREDIS, REDIS_V3, REDIS_V4
123
+ */
124
+ const getRedisClientType = client => {
125
+ if (typeof client?.send_command === 'function') {
126
+ console.log('Detected node-redis redis_v3')
127
+ return REDIS_V3
128
+ }
129
+ if (
130
+ typeof client?.info === 'function' &&
131
+ typeof client?.sendCommand === 'function' &&
132
+ typeof client?.setex !== 'function'
133
+ ) {
134
+ console.log('Detected node-redis redis_v4')
135
+ return REDIS_V4
136
+ }
137
+ if (isIORedis(client)) {
138
+ console.log('Detected node-redis ioredis')
139
+ return IOREDIS
140
+ }
141
+
142
+ throw new Error(`Failed to get Redis client type`)
143
+ }
144
+
145
+ module.exports = {
146
+ createSetClientNameForRedisV3,
147
+ createSetClientNameForRedisV4,
148
+ createSetClientNameForIoredis,
149
+ isIORedis,
150
+ getRedisClientType,
151
+ REDIS_V4,
152
+ REDIS_V3,
153
+ IOREDIS,
154
+ getRedisName,
155
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "esModuleInterop": true,
6
+ "isolatedModules": false,
7
+ "lib": ["ESNext", "DOM"],
8
+ "module": "CommonJS",
9
+ "moduleResolution": "node",
10
+ "outDir": "./lib",
11
+ "strict": true,
12
+ "suppressImplicitAnyIndexErrors": true,
13
+ "target": "ESNext",
14
+ "resolveJsonModule": true,
15
+ "typeRoots": ["./node_modules/@types"]
16
+ },
17
+ "include": ["./src"],
18
+ "exclude": ["./node_modules"]
19
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "declarationMap": true,
6
+ "emitDeclarationOnly": true,
7
+ "noEmit": false,
8
+ "sourceMap": true
9
+ },
10
+ "exclude": ["**/__tests__/**", "**/*.test.js", "**/*.test.ts"]
11
+ }