/
mongo.ts
227 lines (204 loc) · 8.31 KB
/
mongo.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
import { Hub } from '@sentry/hub';
import { EventProcessor, Integration, SpanContext } from '@sentry/types';
import { fill, isThenable, loadModule, logger } from '@sentry/utils';
// This allows us to use the same array for both defaults options and the type itself.
// (note `as const` at the end to make it a union of string literal types (i.e. "a" | "b" | ... )
// and not just a string[])
type Operation = typeof OPERATIONS[number];
const OPERATIONS = [
'aggregate', // aggregate(pipeline, options, callback)
'bulkWrite', // bulkWrite(operations, options, callback)
'countDocuments', // countDocuments(query, options, callback)
'createIndex', // createIndex(fieldOrSpec, options, callback)
'createIndexes', // createIndexes(indexSpecs, options, callback)
'deleteMany', // deleteMany(filter, options, callback)
'deleteOne', // deleteOne(filter, options, callback)
'distinct', // distinct(key, query, options, callback)
'drop', // drop(options, callback)
'dropIndex', // dropIndex(indexName, options, callback)
'dropIndexes', // dropIndexes(options, callback)
'estimatedDocumentCount', // estimatedDocumentCount(options, callback)
'find', // find(query, options, callback)
'findOne', // findOne(query, options, callback)
'findOneAndDelete', // findOneAndDelete(filter, options, callback)
'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)
'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)
'indexes', // indexes(options, callback)
'indexExists', // indexExists(indexes, options, callback)
'indexInformation', // indexInformation(options, callback)
'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)
'insertMany', // insertMany(docs, options, callback)
'insertOne', // insertOne(doc, options, callback)
'isCapped', // isCapped(options, callback)
'mapReduce', // mapReduce(map, reduce, options, callback)
'options', // options(options, callback)
'parallelCollectionScan', // parallelCollectionScan(options, callback)
'rename', // rename(newName, options, callback)
'replaceOne', // replaceOne(filter, doc, options, callback)
'stats', // stats(options, callback)
'updateMany', // updateMany(filter, update, options, callback)
'updateOne', // updateOne(filter, update, options, callback)
] as const;
// All of the operations above take `options` and `callback` as their final parameters, but some of them
// take additional parameters as well. For those operations, this is a map of
// { <operation name>: [<names of additional parameters>] }, as a way to know what to call the operation's
// positional arguments when we add them to the span's `data` object later
const OPERATION_SIGNATURES: {
[op in Operation]?: string[];
} = {
// aggregate intentionally not included because `pipeline` arguments are too complex to serialize well
// see https://github.com/getsentry/sentry-javascript/pull/3102
bulkWrite: ['operations'],
countDocuments: ['query'],
createIndex: ['fieldOrSpec'],
createIndexes: ['indexSpecs'],
deleteMany: ['filter'],
deleteOne: ['filter'],
distinct: ['key', 'query'],
dropIndex: ['indexName'],
find: ['query'],
findOne: ['query'],
findOneAndDelete: ['filter'],
findOneAndReplace: ['filter', 'replacement'],
findOneAndUpdate: ['filter', 'update'],
indexExists: ['indexes'],
insertMany: ['docs'],
insertOne: ['doc'],
mapReduce: ['map', 'reduce'],
rename: ['newName'],
replaceOne: ['filter', 'doc'],
updateMany: ['filter', 'update'],
updateOne: ['filter', 'update'],
};
interface MongoCollection {
collectionName: string;
dbName: string;
namespace: string;
prototype: {
[operation in Operation]: (...args: unknown[]) => unknown;
};
}
interface MongoOptions {
operations?: Operation[];
describeOperations?: boolean | Operation[];
useMongoose?: boolean;
}
/** Tracing integration for mongo package */
export class Mongo implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'Mongo';
/**
* @inheritDoc
*/
public name: string = Mongo.id;
private _operations: Operation[];
private _describeOperations?: boolean | Operation[];
private _useMongoose: boolean;
/**
* @inheritDoc
*/
public constructor(options: MongoOptions = {}) {
this._operations = Array.isArray(options.operations)
? options.operations
: ((OPERATIONS as unknown) as Operation[]);
this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;
this._useMongoose = !!options.useMongoose;
}
/**
* @inheritDoc
*/
public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {
const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';
const pkg = loadModule<{ Collection: MongoCollection }>(moduleName);
if (!pkg) {
logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`);
return;
}
this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);
}
/**
* Patches original collection methods
*/
private _instrumentOperations(collection: MongoCollection, operations: Operation[], getCurrentHub: () => Hub): void {
operations.forEach((operation: Operation) => this._patchOperation(collection, operation, getCurrentHub));
}
/**
* Patches original collection to utilize our tracing functionality
*/
private _patchOperation(collection: MongoCollection, operation: Operation, getCurrentHub: () => Hub): void {
if (!(operation in collection.prototype)) return;
const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);
fill(collection.prototype, operation, function(orig: () => void | Promise<unknown>) {
return function(this: unknown, ...args: unknown[]) {
const lastArg = args[args.length - 1];
const scope = getCurrentHub().getScope();
const parentSpan = scope?.getSpan();
// Check if the operation was passed a callback. (mapReduce requires a different check, as
// its (non-callback) arguments can also be functions.)
if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {
const span = parentSpan?.startChild(getSpanContext(this, operation, args));
const maybePromise = orig.call(this, ...args) as Promise<unknown>;
if (isThenable(maybePromise)) {
return maybePromise.then((res: unknown) => {
span?.finish();
return res;
});
} else {
span?.finish();
return maybePromise;
}
}
const span = parentSpan?.startChild(getSpanContext(this, operation, args.slice(0, -1)));
return orig.call(this, ...args.slice(0, -1), function(err: Error, result: unknown) {
span?.finish();
lastArg(err, result);
});
};
});
}
/**
* Form a SpanContext based on the user input to a given operation.
*/
private _getSpanContextFromOperationArguments(
collection: MongoCollection,
operation: Operation,
args: unknown[],
): SpanContext {
const data: { [key: string]: string } = {
collectionName: collection.collectionName,
dbName: collection.dbName,
namespace: collection.namespace,
};
const spanContext: SpanContext = {
op: `db`,
description: operation,
data,
};
// If the operation takes no arguments besides `options` and `callback`, or if argument
// collection is disabled for this operation, just return early.
const signature = OPERATION_SIGNATURES[operation];
const shouldDescribe = Array.isArray(this._describeOperations)
? this._describeOperations.includes(operation)
: this._describeOperations;
if (!signature || !shouldDescribe) {
return spanContext;
}
try {
// Special case for `mapReduce`, as the only one accepting functions as arguments.
if (operation === 'mapReduce') {
const [map, reduce] = args as { name?: string }[];
data[signature[0]] = typeof map === 'string' ? map : map.name || '<anonymous>';
data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '<anonymous>';
} else {
for (let i = 0; i < signature.length; i++) {
data[signature[i]] = JSON.stringify(args[i]);
}
}
} catch (_oO) {
// no-empty
}
return spanContext;
}
}