-
Notifications
You must be signed in to change notification settings - Fork 38
/
amqplib.ts
417 lines (383 loc) · 17.1 KB
/
amqplib.ts
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import { context, diag, propagation, trace, Span, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import {
InstrumentationBase,
InstrumentationModuleDefinition,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import {
SemanticAttributes,
MessagingOperationValues,
MessagingDestinationKindValues,
} from '@opentelemetry/semantic-conventions';
import type amqp from 'amqplib';
import { AmqplibInstrumentationConfig, DEFAULT_CONFIG, EndOperation } from './types';
import {
CHANNEL_CONSUME_TIMEOUT_TIMER,
CHANNEL_SPANS_NOT_ENDED,
CONNECTION_ATTRIBUTES,
getConnectionAttributesFromUrl,
MESSAGE_STORED_SPAN,
normalizeExchange,
} from './utils';
import { VERSION } from './version';
export class AmqplibInstrumentation extends InstrumentationBase<typeof amqp> {
protected override _config: AmqplibInstrumentationConfig;
constructor(config: AmqplibInstrumentationConfig = {}) {
super('opentelemetry-instrumentation-amqplib', VERSION, Object.assign({}, DEFAULT_CONFIG, config));
}
override setConfig(config: AmqplibInstrumentationConfig = {}) {
this._config = Object.assign({}, DEFAULT_CONFIG, config);
}
protected init(): InstrumentationModuleDefinition<typeof amqp> {
const channelModelModuleFile = new InstrumentationNodeModuleFile<amqp.Channel>(
`amqplib/lib/channel_model.js`,
['>=0.5.5'],
this.patchChannelModel.bind(this),
this.unpatchChannelModel.bind(this)
);
const callbackModelModuleFile = new InstrumentationNodeModuleFile<amqp.Channel>(
`amqplib/lib/callback_model.js`,
['>=0.5.5'],
this.patchChannelModel.bind(this),
this.unpatchChannelModel.bind(this)
);
const connectModuleFile = new InstrumentationNodeModuleFile<amqp.Channel>(
`amqplib/lib/connect.js`,
['>=0.5.5'],
this.patchConnect.bind(this),
this.unpatchConnect.bind(this)
);
const module = new InstrumentationNodeModuleDefinition<typeof amqp>(
'amqplib',
['>=0.5.5'],
undefined,
undefined,
[channelModelModuleFile, connectModuleFile, callbackModelModuleFile]
);
return module;
}
private patchConnect(moduleExports: any) {
moduleExports = this.unpatchConnect(moduleExports);
this._wrap(moduleExports, 'connect', this.getConnectPatch.bind(this));
return moduleExports;
}
private unpatchConnect(moduleExports: any) {
if (isWrapped(moduleExports.connect)) {
this._unwrap(moduleExports, 'connect');
}
return moduleExports;
}
private patchChannelModel(moduleExports: any, moduleVersion: string) {
this._wrap(moduleExports.Channel.prototype, 'publish', this.getPublishPatch.bind(this, moduleVersion));
this._wrap(moduleExports.Channel.prototype, 'consume', this.getConsumePatch.bind(this, moduleVersion));
this._wrap(moduleExports.Channel.prototype, 'ack', this.getAckPatch.bind(this, false, EndOperation.Ack));
this._wrap(moduleExports.Channel.prototype, 'nack', this.getAckPatch.bind(this, true, EndOperation.Nack));
this._wrap(moduleExports.Channel.prototype, 'reject', this.getAckPatch.bind(this, true, EndOperation.Reject));
this._wrap(
moduleExports.Channel.prototype,
'ackAll',
this.getAckAllPatch.bind(this, false, EndOperation.AckAll)
);
this._wrap(
moduleExports.Channel.prototype,
'nackAll',
this.getAckAllPatch.bind(this, true, EndOperation.NackAll)
);
this._wrap(moduleExports.Channel.prototype, 'emit', this.getChannelEmitPatch.bind(this));
return moduleExports;
}
private unpatchChannelModel(moduleExports: any) {
if (isWrapped(moduleExports.Channel.prototype.publish)) {
this._unwrap(moduleExports.Channel.prototype, 'publish');
}
if (isWrapped(moduleExports.Channel.prototype.consume)) {
this._unwrap(moduleExports.Channel.prototype, 'consume');
}
if (isWrapped(moduleExports.Channel.prototype.ack)) {
this._unwrap(moduleExports.Channel.prototype, 'ack');
}
if (isWrapped(moduleExports.Channel.prototype.nack)) {
this._unwrap(moduleExports.Channel.prototype, 'nack');
}
if (isWrapped(moduleExports.Channel.prototype.reject)) {
this._unwrap(moduleExports.Channel.prototype, 'reject');
}
if (isWrapped(moduleExports.Channel.prototype.ackAll)) {
this._unwrap(moduleExports.Channel.prototype, 'ackAll');
}
if (isWrapped(moduleExports.Channel.prototype.nackAll)) {
this._unwrap(moduleExports.Channel.prototype, 'nackAll');
}
if (isWrapped(moduleExports.Channel.prototype.emit)) {
this._unwrap(moduleExports.Channel.prototype, 'emit');
}
return moduleExports;
}
private getConnectPatch(
original: (url: string | amqp.Options.Connect, socketOptions, openCallback) => amqp.Connection
) {
return function patchedConnect(url: string | amqp.Options.Connect, socketOptions, openCallback) {
return original.call(this, url, socketOptions, function (err, conn: amqp.Connection) {
if (err === null) {
Object.defineProperty(conn, CONNECTION_ATTRIBUTES, {
value: getConnectionAttributesFromUrl(url, conn),
enumerable: false,
});
}
openCallback.apply(this, arguments);
});
};
}
private getChannelEmitPatch(original: (eventName: string, ...args: unknown[]) => void) {
const self = this;
return function emit(eventName: string) {
if (eventName === 'close') {
self.endAllSpansOnChannel(this, true, EndOperation.ChannelClosed);
const activeTimer = this[CHANNEL_CONSUME_TIMEOUT_TIMER];
if (activeTimer) {
clearInterval(activeTimer);
}
delete this[CHANNEL_CONSUME_TIMEOUT_TIMER];
} else if (eventName === 'error') {
self.endAllSpansOnChannel(this, true, EndOperation.ChannelError);
}
return original.apply(this, arguments);
};
}
private getAckAllPatch(isRejected: boolean, endOperation: EndOperation, original: () => void) {
const self = this;
return function ackAll(): void {
self.endAllSpansOnChannel(this, isRejected, endOperation);
return original.apply(this, arguments);
};
}
private getAckPatch(
isRejected: boolean,
endOperation: EndOperation,
original: (message: amqp.Message, allUpTo?: boolean, requeue?: boolean) => void
) {
const self = this;
return function ack(message: amqp.Message, allUpTo?: boolean, requeue?: boolean): void {
const channel = this;
// we use this patch in reject function as well, but it has different signature
const requeueResolved = endOperation === EndOperation.Reject ? allUpTo : requeue;
const spansNotEnded: { msg: amqp.Message }[] = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];
const msgIndex = spansNotEnded.findIndex((msgDetails) => msgDetails.msg === message);
if (msgIndex < 0) {
// should not happen in happy flow
// but possible if user is calling the api function ack twice with same message
self.endConsumerSpan(message, isRejected, endOperation, requeueResolved);
} else if (endOperation !== EndOperation.Reject && allUpTo) {
for (let i = 0; i <= msgIndex; i++) {
self.endConsumerSpan(spansNotEnded[i].msg, isRejected, endOperation, requeueResolved);
}
spansNotEnded.splice(0, msgIndex + 1);
} else {
self.endConsumerSpan(message, isRejected, endOperation, requeueResolved);
spansNotEnded.splice(msgIndex, 1);
}
return original.apply(this, arguments);
};
}
private getConsumePatch(
moduleVersion: string,
original: (
queue: string,
onMessage: (msg: amqp.ConsumeMessage | null) => void,
options?: amqp.Options.Consume
) => Promise<amqp.Replies.Consume>
) {
const self = this;
return function consume(
queue: string,
onMessage: (msg: amqp.ConsumeMessage | null) => void,
options?: amqp.Options.Consume
): Promise<amqp.Replies.Consume> {
const channel = this;
if (!channel.hasOwnProperty(CHANNEL_SPANS_NOT_ENDED)) {
if (self._config.consumeTimeoutMs) {
const timer = setInterval(() => {
self.checkConsumeTimeoutOnChannel(channel);
}, self._config.consumeTimeoutMs);
timer.unref();
Object.defineProperty(channel, CHANNEL_CONSUME_TIMEOUT_TIMER, {
value: timer,
enumerable: false,
configurable: true,
});
}
Object.defineProperty(channel, CHANNEL_SPANS_NOT_ENDED, {
value: [],
enumerable: false,
configurable: true,
});
}
const patchedOnMessage = function (msg: amqp.ConsumeMessage | null) {
const headers = msg.properties.headers;
const parentContext = propagation.extract(context.active(), headers);
const exchange = msg?.fields?.exchange;
const span = self.tracer.startSpan(
`${queue} process`,
{
kind: SpanKind.CONSUMER,
attributes: {
...channel?.connection?.[CONNECTION_ATTRIBUTES],
[SemanticAttributes.MESSAGING_DESTINATION]: exchange,
[SemanticAttributes.MESSAGING_DESTINATION_KIND]: MessagingDestinationKindValues.TOPIC,
['messaging.rabbitmq.routing_key']: msg?.fields?.routingKey,
[SemanticAttributes.MESSAGING_OPERATION]: MessagingOperationValues.PROCESS,
},
},
parentContext
);
if (self._config.moduleVersionAttributeName) {
span.setAttribute(self._config.moduleVersionAttributeName, moduleVersion);
}
if (self._config.consumeHook) {
safeExecuteInTheMiddle(
() => self._config.consumeHook(span, msg),
(e) => {
if (e) {
diag.error('amqplib instrumentation: consumerHook error', e);
}
},
true
);
}
if (!options?.noAck) {
// store the message on the channel so we can close the span on ackAll etc
channel[CHANNEL_SPANS_NOT_ENDED].push({ msg, timeOfConsume: new Date() });
// store the span on the message, so we can end it when user call 'ack' on it
Object.defineProperty(msg, MESSAGE_STORED_SPAN, {
value: span,
enumerable: false,
configurable: true,
});
}
context.with(trace.setSpan(context.active(), span), () => {
onMessage.call(this, msg);
});
if (options?.noAck) {
self.callConsumeEndHook(span, msg, false, EndOperation.AutoAck);
span.end();
}
};
arguments[1] = patchedOnMessage;
return original.apply(this, arguments);
};
}
private getPublishPatch(
moduleVersion: string,
original: (exchange: string, routingKey: string, content: Buffer, options?: amqp.Options.Publish) => boolean
) {
const self = this;
return function publish(
exchange: string,
routingKey: string,
content: Buffer,
options?: amqp.Options.Publish
): boolean {
const normalizedExchange = normalizeExchange(exchange);
const span = self.tracer.startSpan(`${normalizedExchange} -> ${routingKey} send`, {
kind: SpanKind.PRODUCER,
attributes: {
...this.connection[CONNECTION_ATTRIBUTES],
[SemanticAttributes.MESSAGING_DESTINATION]: exchange,
[SemanticAttributes.MESSAGING_DESTINATION_KIND]: MessagingDestinationKindValues.TOPIC,
['messaging.rabbitmq.routing_key']: routingKey,
},
});
if (self._config.moduleVersionAttributeName) {
span.setAttribute(self._config.moduleVersionAttributeName, moduleVersion);
}
const modifiedOptions = options ?? {};
modifiedOptions.headers = modifiedOptions.headers ?? {};
propagation.inject(trace.setSpan(context.active(), span), modifiedOptions.headers);
if (self._config.publishHook) {
safeExecuteInTheMiddle(
() => self._config.publishHook(span, { exchange, routingKey, content, options }),
(e) => {
if (e) {
diag.error('amqplib instrumentation: publishHook error', e);
}
},
true
);
}
// calling original publish function is only storing the message in queue.
// it does not send it and waits for an ack, so the span duration is expected to be very short.
const argumentsCopy = [...arguments];
argumentsCopy[3] = modifiedOptions;
const originalRes = original.apply(this, argumentsCopy);
if (!originalRes) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: 'write buffer is full, message should be published again after drain event',
});
}
span.end();
return originalRes;
};
}
private endConsumerSpan(message: amqp.Message, isRejected: boolean, operation: EndOperation, requeue: boolean) {
const storedSpan: Span = message[MESSAGE_STORED_SPAN];
if (!storedSpan) return;
if (isRejected !== false) {
storedSpan.setStatus({
code: SpanStatusCode.ERROR,
message:
operation !== EndOperation.ChannelClosed && operation !== EndOperation.ChannelError
? `${operation} called on message ${requeue ? 'with' : 'without'} requeue`
: operation,
});
}
this.callConsumeEndHook(storedSpan, message, isRejected, operation);
storedSpan.end();
delete message[MESSAGE_STORED_SPAN];
}
private endAllSpansOnChannel(channel: amqp.Channel, isRejected: boolean, operation: EndOperation) {
const spansNotEnded: { msg: amqp.Message }[] = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];
spansNotEnded.forEach((msgDetails) => {
this.endConsumerSpan(msgDetails.msg, isRejected, operation, null);
});
Object.defineProperty(channel, CHANNEL_SPANS_NOT_ENDED, {
value: [],
enumerable: false,
configurable: true,
});
}
private callConsumeEndHook(
span: Span,
msg: amqp.ConsumeMessage | null,
rejected: boolean,
endOperation: EndOperation
) {
if (!this._config.consumeEndHook) return;
safeExecuteInTheMiddle(
() => this._config.consumeEndHook(span, msg, rejected, endOperation),
(e) => {
if (e) {
diag.error('amqplib instrumentation: consumerEndHook error', e);
}
},
true
);
}
private checkConsumeTimeoutOnChannel(channel: amqp.Channel) {
const currentTime = new Date().getTime();
const spansNotEnded: { msg: amqp.Message; timeOfConsume: Date }[] = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];
let i: number;
for (i = 0; i < spansNotEnded.length; i++) {
const currMessage = spansNotEnded[i];
const timeFromConsume = currentTime - currMessage.timeOfConsume.getTime();
if (timeFromConsume < this._config.consumeTimeoutMs) {
break;
}
this.endConsumerSpan(currMessage.msg, null, EndOperation.InstrumentationTimeout, true);
}
spansNotEnded.splice(0, i);
}
}