-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathmongo.ts
89 lines (77 loc) · 2.54 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
import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb';
import { defineIntegration } from '@sentry/core';
import type { IntegrationFn } from '@sentry/types';
import { generateInstrumentOnce } from '../../otel/instrument';
import { addOriginToSpan } from '../../utils/addOriginToSpan';
const INTEGRATION_NAME = 'Mongo';
export const instrumentMongo = generateInstrumentOnce(
INTEGRATION_NAME,
() =>
new MongoDBInstrumentation({
dbStatementSerializer: _defaultDbStatementSerializer,
responseHook(span) {
addOriginToSpan(span, 'auto.db.otel.mongo');
},
}),
);
/**
* Replaces values in document with '?', hiding PII and helping grouping.
*/
export function _defaultDbStatementSerializer(commandObj: Record<string, unknown>): string {
const resultObj = _scrubStatement(commandObj);
return JSON.stringify(resultObj);
}
function _scrubStatement(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(element => _scrubStatement(element));
}
if (isCommandObj(value)) {
const initial: Record<string, unknown> = {};
return Object.entries(value)
.map(([key, element]) => [key, _scrubStatement(element)])
.reduce((prev, current) => {
if (isCommandEntry(current)) {
prev[current[0]] = current[1];
}
return prev;
}, initial);
}
// A value like string or number, possible contains PII, scrub it
return '?';
}
function isCommandObj(value: Record<string, unknown> | unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !isBuffer(value);
}
function isBuffer(value: unknown): boolean {
let isBuffer = false;
if (typeof Buffer !== 'undefined') {
isBuffer = Buffer.isBuffer(value);
}
return isBuffer;
}
function isCommandEntry(value: [string, unknown] | unknown): value is [string, unknown] {
return Array.isArray(value);
}
const _mongoIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
instrumentMongo();
},
};
}) satisfies IntegrationFn;
/**
* Adds Sentry tracing instrumentation for the [mongodb](https://www.npmjs.com/package/mongodb) library.
*
* For more information, see the [`mongoIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/mongo/).
*
* @example
* ```javascript
* const Sentry = require('@sentry/node');
*
* Sentry.init({
* integrations: [Sentry.mongoIntegration()],
* });
* ```
*/
export const mongoIntegration = defineIntegration(_mongoIntegration);