-
Notifications
You must be signed in to change notification settings - Fork 38
/
mongoose.ts
246 lines (217 loc) · 10.1 KB
/
mongoose.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
import { context, Span, trace, diag } from '@opentelemetry/api';
import { suppressTracing } from '@opentelemetry/core';
import type mongoose from 'mongoose';
import { MongooseInstrumentationConfig, SerializerPayload } from './types';
import { startSpan, handleCallbackResponse, handlePromiseResponse } from './utils';
import {
InstrumentationBase,
InstrumentationModuleDefinition,
InstrumentationNodeModuleDefinition,
} from '@opentelemetry/instrumentation';
import { VERSION } from './version';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
const contextCaptureFunctions = [
'remove',
'deleteOne',
'deleteMany',
'find',
'findOne',
'estimatedDocumentCount',
'countDocuments',
'count',
'distinct',
'where',
'$where',
'findOneAndUpdate',
'findOneAndDelete',
'findOneAndReplace',
'findOneAndRemove',
];
// when mongoose functions are called, we store the original call context
// and then set it as the parent for the spans created by Query/Aggregate exec()
// calls. this bypass the unlinked spans issue on thenables await operations.
export const _STORED_PARENT_SPAN: unique symbol = Symbol('stored-parent-span');
export class MongooseInstrumentation extends InstrumentationBase<typeof mongoose> {
static readonly component = 'mongoose';
protected override _config: MongooseInstrumentationConfig;
private moduleVersion: string;
constructor(config: MongooseInstrumentationConfig = {}) {
super('opentelemetry-instrumentation-mongoose', VERSION, Object.assign({}, config));
// According to specification, statement is not set by default on mongodb spans.
if (!config.dbStatementSerializer) this._config.dbStatementSerializer = () => undefined;
}
override setConfig(config: MongooseInstrumentationConfig = {}) {
this._config = Object.assign({}, config);
if (!config.dbStatementSerializer) this._config.dbStatementSerializer = () => undefined;
}
protected init(): InstrumentationModuleDefinition<typeof mongoose> {
const module = new InstrumentationNodeModuleDefinition<typeof mongoose>(
MongooseInstrumentation.component,
['*'],
this.patch.bind(this),
this.unpatch.bind(this)
);
return module;
}
protected patch(moduleExports: typeof mongoose, moduleVersion: string) {
diag.debug('mongoose instrumentation: patching');
this.moduleVersion = moduleVersion;
this._wrap(moduleExports.Model.prototype, 'save', this.patchOnModelMethods('save'));
this._wrap(moduleExports.Model.prototype, 'remove', this.patchOnModelMethods('remove'));
this._wrap(moduleExports.Query.prototype, 'exec', this.patchQueryExec());
this._wrap(moduleExports.Aggregate.prototype, 'exec', this.patchAggregateExec());
contextCaptureFunctions.forEach((funcName: string) => {
this._wrap(moduleExports.Query.prototype, funcName as any, this.patchAndCaptureSpanContext(funcName));
});
this._wrap(moduleExports.Model, 'aggregate', this.patchModelAggregate());
return moduleExports;
}
protected unpatch(moduleExports: typeof mongoose): void {
diag.debug('mongoose instrumentation: unpatch mongoose');
this._unwrap(moduleExports.Model.prototype, 'save');
this._unwrap(moduleExports.Model.prototype, 'remove');
this._unwrap(moduleExports.Query.prototype, 'exec');
this._unwrap(moduleExports.Aggregate.prototype, 'exec');
contextCaptureFunctions.forEach((funcName: string) => {
this._unwrap(moduleExports.Query.prototype, funcName as any);
});
this._unwrap(moduleExports.Model, 'aggregate');
}
private patchAggregateExec() {
const self = this;
diag.debug('mongoose instrumentation: patched mongoose Aggregate exec prototype');
return (originalAggregate: Function) => {
return function exec(this: any, callback?: Function) {
if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) {
return originalAggregate.apply(this, arguments);
}
const parentSpan = this[_STORED_PARENT_SPAN];
const attributes = {
[SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer('aggregate', {
options: this.options,
aggregatePipeline: this._pipeline,
}),
};
const span = startSpan({
tracer: self.tracer,
modelName: this._model?.modelName,
operation: 'aggregate',
attributes,
collection: this._model.collection,
parentSpan,
});
self._addModuleVersionIfNeeded(span);
return self._handleResponse(span, originalAggregate, this, arguments, callback);
};
};
}
private patchQueryExec() {
const self = this;
diag.debug('mongoose instrumentation: patched mongoose Query exec prototype');
return (originalExec: Function) => {
return function exec(this: any, callback?: Function) {
if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) {
return originalExec.apply(this, arguments);
}
const parentSpan = this[_STORED_PARENT_SPAN];
const attributes = {
[SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer(this.op, {
condition: this._conditions,
updates: this._update,
options: this.options,
}),
};
const span = startSpan({
tracer: self.tracer,
modelName: this.model.modelName,
operation: this.op,
attributes,
parentSpan,
collection: this.mongooseCollection,
});
self._addModuleVersionIfNeeded(span);
return self._handleResponse(span, originalExec, this, arguments, callback);
};
};
}
private patchOnModelMethods(op: string) {
const self = this;
diag.debug(`mongoose instrumentation: patched mongoose Model ${op} prototype`);
return (originalOnModelFunction: Function) => {
return function method(this: any, options?: any, callback?: Function) {
if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) {
return originalOnModelFunction.apply(this, arguments);
}
const serializePayload: SerializerPayload = { document: this };
if (options && !(options instanceof Function)) {
serializePayload.options = options;
}
const attributes = {
[SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer(op, serializePayload),
};
const span = startSpan({
tracer: self.tracer,
modelName: this.constructor.modelName,
operation: op,
attributes,
collection: this.constructor.collection,
});
self._addModuleVersionIfNeeded(span);
if (options instanceof Function) {
callback = options;
options = undefined;
}
return self._handleResponse(span, originalOnModelFunction, this, arguments, callback);
};
};
}
// we want to capture the otel span on the object which is calling exec.
// in the special case of aggregate, we need have no function to path
// on the Aggregate object to capture the context on, so we patch
// the aggregate of Model, and set the context on the Aggregate object
private patchModelAggregate() {
const self = this;
diag.debug(`mongoose instrumentation: patched mongoose model aggregate`);
return (original: Function) => {
return function captureSpanContext(this: any) {
const currentSpan = trace.getSpan(context.active());
const aggregate = self._callOriginalFunction(() => original.apply(this, arguments));
if (aggregate) aggregate[_STORED_PARENT_SPAN] = currentSpan;
return aggregate;
};
};
}
private patchAndCaptureSpanContext(funcName: string) {
const self = this;
diag.debug(`mongoose instrumentation: patched mongoose query ${funcName} prototype`);
return (original: Function) => {
return function captureSpanContext(this: any) {
this[_STORED_PARENT_SPAN] = trace.getSpan(context.active());
return self._callOriginalFunction(() => original.apply(this, arguments));
};
};
}
private _handleResponse(span: Span, exec: Function, originalThis: any, args: IArguments, callback?: Function) {
const self = this;
if (callback instanceof Function) {
return self._callOriginalFunction(() =>
handleCallbackResponse(callback, exec, originalThis, span, self._config.responseHook)
);
} else {
const response = self._callOriginalFunction(() => exec.apply(originalThis, args));
return handlePromiseResponse(response, span, self._config.responseHook);
}
}
private _callOriginalFunction<T>(originalFunction: (...args: any[]) => T): T {
if (this._config?.suppressInternalInstrumentation) {
return context.with(suppressTracing(context.active()), originalFunction);
} else {
return originalFunction();
}
}
private _addModuleVersionIfNeeded(span: Span) {
if (this._config.moduleVersionAttributeName) {
span.setAttribute(this._config.moduleVersionAttributeName, this.moduleVersion);
}
}
}