-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathredis-dc-subscriber.ts
More file actions
231 lines (211 loc) · 6.59 KB
/
redis-dc-subscriber.ts
File metadata and controls
231 lines (211 loc) · 6.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import type { Span } from '@opentelemetry/api';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SPAN_STATUS_ERROR,
startSpanManual,
} from '@sentry/core';
import { tracingChannel, type TracingChannelContextWithSpan } from '@sentry/opentelemetry/tracing-channel';
import { defaultDbStatementSerializer } from './vendored/redis-common';
import {
ATTR_DB_STATEMENT,
ATTR_DB_SYSTEM,
ATTR_NET_PEER_NAME,
ATTR_NET_PEER_PORT,
DB_SYSTEM_VALUE_REDIS,
} from './vendored/semconv';
import type { IORedisInstrumentationConfig } from './vendored/types';
// Channel names as published by node-redis >= 5.12.0.
// Hardcoded so we don't import `redis` at module-load time.
const CHANNEL_COMMAND = 'node-redis:command';
const CHANNEL_BATCH = 'node-redis:batch';
const CHANNEL_CONNECT = 'node-redis:connect';
const ORIGIN = 'auto.db.redis.diagnostic-channel';
interface CommandData {
command: string;
args: Array<string | Buffer>;
database?: number;
serverAddress?: string;
serverPort?: number;
result?: unknown;
error?: Error;
}
interface BatchData {
batchMode?: 'MULTI' | 'PIPELINE';
batchSize?: number;
database?: number;
clientId?: string | number;
serverAddress?: string;
serverPort?: number;
result?: unknown[];
error?: Error;
}
interface ConnectData {
serverAddress?: string;
serverPort?: number;
url?: string;
error?: Error;
}
const NOOP = (): void => {};
let subscribed = false;
let currentResponseHook: IORedisInstrumentationConfig['responseHook'] | undefined;
/**
* Subscribe Sentry handlers to node-redis diagnostics_channel events (>= 5.12.0).
*
* Uses `@sentry/opentelemetry/tracing-channel` so OTel AsyncLocalStorage context propagates
* automatically via `bindStore` — without it, spans created in `start` would not become
* the active context for subsequent operations.
*
* Safe on every runtime that exposes `node:diagnostics_channel` (Node, Bun, Deno, Workers).
* In node-redis < 5.12.0 the channels are never published to, so subscribers are inert and
* there is no double-instrumentation against the IITM-based patcher (gated to < 5.12.0).
*/
export function subscribeRedisDiagnosticChannels(
responseHook?: IORedisInstrumentationConfig['responseHook'],
): void {
currentResponseHook = responseHook;
if (subscribed) return;
try {
setupCommandChannel();
setupBatchChannel();
setupConnectChannel();
subscribed = true;
} catch {
// tracingChannel from @sentry/opentelemetry requires `node:diagnostics_channel`.
// On runtimes where it isn't available, fail closed.
}
}
function setupCommandChannel(): void {
const channel = tracingChannel<CommandData>(CHANNEL_COMMAND, data => {
const statement = safeSerialize(data.command, data.args);
return startSpanManual(
{
name: `redis-${data.command}`,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.redis',
[ATTR_DB_SYSTEM]: DB_SYSTEM_VALUE_REDIS,
...(statement != null ? { [ATTR_DB_STATEMENT]: statement } : {}),
...(data.serverAddress != null ? { [ATTR_NET_PEER_NAME]: data.serverAddress } : {}),
...(data.serverPort != null ? { [ATTR_NET_PEER_PORT]: data.serverPort } : {}),
},
},
span => span,
) as Span;
});
channel.subscribe({
start: NOOP,
asyncStart: NOOP,
end: NOOP,
asyncEnd: data => {
const span = data._sentrySpan;
if (!span) return;
runResponseHook(span, data.command, data.args, data.result);
span.end();
},
error: data => {
const span = data._sentrySpan;
if (!span) return;
if (data.error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: data.error.message });
}
span.end();
},
});
}
function setupBatchChannel(): void {
const channel = tracingChannel<BatchData>(CHANNEL_BATCH, data => {
const operationName = data.batchMode === 'PIPELINE' ? 'PIPELINE' : 'MULTI';
return startSpanManual(
{
name: operationName,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.redis',
[ATTR_DB_SYSTEM]: DB_SYSTEM_VALUE_REDIS,
...(data.batchSize != null ? { 'db.redis.batch_size': data.batchSize } : {}),
...(data.serverAddress != null ? { [ATTR_NET_PEER_NAME]: data.serverAddress } : {}),
...(data.serverPort != null ? { [ATTR_NET_PEER_PORT]: data.serverPort } : {}),
},
},
span => span,
) as Span;
});
channel.subscribe({
start: NOOP,
asyncStart: NOOP,
end: NOOP,
asyncEnd: data => {
data._sentrySpan?.end();
},
error: data => {
const span = data._sentrySpan;
if (!span) return;
if (data.error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: data.error.message });
}
span.end();
},
});
}
function setupConnectChannel(): void {
const channel = tracingChannel<ConnectData>(CHANNEL_CONNECT, data => {
return startSpanManual(
{
name: 'redis-connect',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db.redis.connect',
[ATTR_DB_SYSTEM]: DB_SYSTEM_VALUE_REDIS,
...(data.serverAddress != null ? { [ATTR_NET_PEER_NAME]: data.serverAddress } : {}),
...(data.serverPort != null ? { [ATTR_NET_PEER_PORT]: data.serverPort } : {}),
},
},
span => span,
) as Span;
});
channel.subscribe({
start: NOOP,
asyncStart: NOOP,
end: NOOP,
asyncEnd: data => {
data._sentrySpan?.end();
},
error: data => {
const span = data._sentrySpan;
if (!span) return;
if (data.error) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: data.error.message });
}
span.end();
},
});
}
function runResponseHook(
span: Span,
command: string,
args: Array<string | Buffer>,
result: unknown,
): void {
const hook = currentResponseHook;
if (!hook) return;
try {
hook(span, command, args as unknown as Parameters<typeof hook>[2], result);
} catch {
// never let user hooks break instrumentation
}
}
function safeSerialize(command: string, args: Array<string | Buffer>): string | undefined {
try {
return defaultDbStatementSerializer(command, args);
} catch {
return undefined;
}
}
// Test-only helper.
export function _resetRedisDiagnosticChannelsForTesting(): void {
subscribed = false;
currentResponseHook = undefined;
}
// Suppress unused-import lint when only used in types.
export type { TracingChannelContextWithSpan };