|
| 1 | +/** |
| 2 | + * Copyright 2026 Google, Inc. |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | + |
| 16 | +// [START memorystore_redis_client_side_metrics] |
| 17 | + |
| 18 | +'use strict'; |
| 19 | + |
| 20 | +const {trace, metrics} = require('@opentelemetry/api'); |
| 21 | +const {NodeTracerProvider} = require('@opentelemetry/sdk-trace-node'); |
| 22 | +const {BatchSpanProcessor} = require('@opentelemetry/sdk-trace-base'); |
| 23 | +const { |
| 24 | + TraceExporter, |
| 25 | +} = require('@google-cloud/opentelemetry-cloud-trace-exporter'); |
| 26 | +const { |
| 27 | + MeterProvider, |
| 28 | + PeriodicExportingMetricReader, |
| 29 | +} = require('@opentelemetry/sdk-metrics'); |
| 30 | +const { |
| 31 | + MetricExporter, |
| 32 | +} = require('@google-cloud/opentelemetry-cloud-monitoring-exporter'); |
| 33 | +const {RedisInstrumentation} = require('@opentelemetry/instrumentation-redis'); |
| 34 | +const {registerInstrumentations} = require('@opentelemetry/instrumentation'); |
| 35 | +const {performance} = require('perf_hooks'); |
| 36 | + |
| 37 | +// FIX: Pass spanProcessors in the constructor options for NodeTracerProvider in SDK 2.x |
| 38 | +const provider = new NodeTracerProvider({ |
| 39 | + spanProcessors: [new BatchSpanProcessor(new TraceExporter())], |
| 40 | +}); |
| 41 | +provider.register(); |
| 42 | + |
| 43 | +registerInstrumentations({ |
| 44 | + instrumentations: [new RedisInstrumentation()], |
| 45 | +}); |
| 46 | + |
| 47 | +const redis = require('redis'); |
| 48 | + |
| 49 | +const metricExporter = new MetricExporter(); |
| 50 | +const metricReader = new PeriodicExportingMetricReader({ |
| 51 | + exporter: metricExporter, |
| 52 | + exportIntervalMillis: 10000, |
| 53 | +}); |
| 54 | +const meterProvider = new MeterProvider({readers: [metricReader]}); |
| 55 | +metrics.setGlobalMeterProvider(meterProvider); |
| 56 | + |
| 57 | +const tracer = trace.getTracer('redis.client.node'); |
| 58 | +const meter = metrics.getMeter('redis.metrics.node'); |
| 59 | + |
| 60 | +const rttHist = meter.createHistogram('redis_client_rtt', {unit: 'ms'}); |
| 61 | +const appBlockHist = meter.createHistogram( |
| 62 | + 'redis_application_blocking_latency', |
| 63 | + {unit: 'ms'} |
| 64 | +); |
| 65 | +const retryCounter = meter.createCounter('redis_retry_count'); |
| 66 | +const connErrorCounter = meter.createCounter('redis_connectivity_error_count'); |
| 67 | + |
| 68 | +retryCounter.add(0, {operation: 'startup'}); |
| 69 | +connErrorCounter.add(0, {operation: 'startup'}); |
| 70 | + |
| 71 | +const REDISHOST = process.env.REDISHOST || 'localhost'; |
| 72 | +const REDISPORT = process.env.REDISPORT || 6379; |
| 73 | + |
| 74 | +const client = redis.createClient({ |
| 75 | + socket: { |
| 76 | + host: REDISHOST, |
| 77 | + port: REDISPORT, |
| 78 | + reconnectStrategy: retries => { |
| 79 | + connErrorCounter.add(1, {error: 'socket_reconnect'}); |
| 80 | + if (retries > 5) return new Error('Max retries reached'); |
| 81 | + return Math.min(retries * 100, 3000); |
| 82 | + }, |
| 83 | + }, |
| 84 | +}); |
| 85 | +client.on('error', err => console.log('Redis Client Error', err)); |
| 86 | + |
| 87 | +async function smartRedisCall(operationName, func, ...args) { |
| 88 | + let attempt = 0; |
| 89 | + while (attempt < 3) { |
| 90 | + try { |
| 91 | + const reqStart = performance.now(); |
| 92 | + const response = await func(...args); |
| 93 | + rttHist.record(performance.now() - reqStart, {operation: operationName}); |
| 94 | + |
| 95 | + const appParseStart = performance.now(); |
| 96 | + // eslint-disable-next-line no-unused-vars |
| 97 | + const _ = String(response); |
| 98 | + appBlockHist.record(performance.now() - appParseStart, { |
| 99 | + operation: operationName, |
| 100 | + }); |
| 101 | + |
| 102 | + return response; |
| 103 | + } catch (e) { |
| 104 | + attempt++; |
| 105 | + retryCounter.add(1, {operation: operationName}); |
| 106 | + if (attempt >= 3) throw e; |
| 107 | + await new Promise(resolve => |
| 108 | + setTimeout(resolve, Math.pow(2, attempt) * 100) |
| 109 | + ); |
| 110 | + } |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +async function main() { |
| 115 | + await client.connect(); |
| 116 | + |
| 117 | + await tracer.startActiveSpan('process_user_span', async span => { |
| 118 | + try { |
| 119 | + // Simple write and read operations |
| 120 | + await smartRedisCall( |
| 121 | + 'set_user', |
| 122 | + client.set.bind(client), |
| 123 | + 'user:123', |
| 124 | + 'active' |
| 125 | + ); |
| 126 | + |
| 127 | + const result = await smartRedisCall( |
| 128 | + 'get_user', |
| 129 | + client.get.bind(client), |
| 130 | + 'user:123' |
| 131 | + ); |
| 132 | + console.log('Retrieved:', result); |
| 133 | + } catch (e) { |
| 134 | + span.recordException(e); |
| 135 | + } finally { |
| 136 | + span.end(); |
| 137 | + } |
| 138 | + }); |
| 139 | + |
| 140 | + await client.quit(); |
| 141 | + await provider.forceFlush(); |
| 142 | + await meterProvider.forceFlush(); |
| 143 | +} |
| 144 | + |
| 145 | +// Only run the script automatically if it is executed directly (e.g. `node server.js`) |
| 146 | +if (require.main === module) { |
| 147 | + main().catch(console.error); |
| 148 | +} |
| 149 | + |
| 150 | +// Export for testability |
| 151 | +module.exports = { |
| 152 | + main, |
| 153 | + smartRedisCall, |
| 154 | +}; |
| 155 | + |
| 156 | +// [END memorystore_redis_client_side_metrics] |
0 commit comments