-
Notifications
You must be signed in to change notification settings - Fork 38
/
sequelize.ts
185 lines (161 loc) · 7.36 KB
/
sequelize.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
import { context, Span, SpanKind, SpanStatusCode, trace, diag } from '@opentelemetry/api';
import { suppressTracing } from '@opentelemetry/core';
import { NetTransportValues, SemanticAttributes } from '@opentelemetry/semantic-conventions';
import * as sequelize from 'sequelize';
import { SequelizeInstrumentationConfig } from './types';
import { VERSION } from './version';
import { extractTableFromQuery } from './utils';
import {
InstrumentationBase,
InstrumentationModuleDefinition,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
export class SequelizeInstrumentation extends InstrumentationBase<typeof sequelize> {
static readonly component = 'sequelize';
protected override _config!: SequelizeInstrumentationConfig;
private moduleVersion: string;
constructor(config: SequelizeInstrumentationConfig = {}) {
super('opentelemetry-instrumentation-sequelize', VERSION, Object.assign({}, config));
}
override setConfig(config: SequelizeInstrumentationConfig = {}) {
this._config = Object.assign({}, config);
}
protected init(): InstrumentationModuleDefinition<typeof sequelize> {
const connectionManagerInstrumentation = new InstrumentationNodeModuleFile<any>(
'sequelize/lib/dialects/abstract/connection-manager.js',
['*'],
this.patchConnectionManager.bind(this),
this.unpatchConnectionManager.bind(this)
);
const module = new InstrumentationNodeModuleDefinition<typeof sequelize>(
SequelizeInstrumentation.component,
['*'],
this.patch.bind(this),
this.unpatch.bind(this),
[connectionManagerInstrumentation]
);
return module;
}
protected patchConnectionManager(moduleExports: any): any {
if (moduleExports === undefined || moduleExports === null) {
return moduleExports;
}
diag.debug(`sequelize instrumentation: applying patch to sequelize ConnectionManager`);
this.unpatchConnectionManager(moduleExports);
this._wrap(moduleExports.ConnectionManager.prototype, 'getConnection', this._getConnectionPatch.bind(this));
return moduleExports;
}
protected unpatchConnectionManager(moduleExports: any): any {
if (isWrapped(moduleExports?.ConnectionManager?.prototype?.getConnection)) {
this._unwrap(moduleExports.ConnectionManager.prototype, 'getConnection');
}
return moduleExports;
}
protected patch(moduleExports: typeof sequelize, moduleVersion: string) {
this.moduleVersion = moduleVersion;
if (moduleExports === undefined || moduleExports === null) {
return moduleExports;
}
diag.debug(`sequelize instrumentation: applying patch to sequelize`);
this.unpatch(moduleExports);
this._wrap(moduleExports.Sequelize.prototype, 'query', this._createQueryPatch.bind(this));
return moduleExports;
}
protected unpatch(moduleExports: typeof sequelize): void {
if (isWrapped(moduleExports.Sequelize.prototype.query)) {
this._unwrap(moduleExports.Sequelize.prototype, 'query');
}
}
// run getConnection with suppressTracing, as it might call internally to `databaseVersion` function
// which calls `query` and create internal span which we don't need to instrument
private _getConnectionPatch(original: Function) {
return function (...args: unknown[]) {
return context.with(suppressTracing(context.active()), () => original.apply(this, args));
};
}
private _createQueryPatch(original: Function) {
const self = this;
return function (sql: any, option: any) {
if (self._config?.ignoreOrphanedSpans && !trace.getSpan(context.active())) {
return original.apply(this, arguments);
}
let statement = sql?.query ? sql.query : sql;
let operation = option?.type;
if (typeof statement === 'string') {
statement = statement.trim();
if (!operation) operation = statement.split(' ')[0];
}
const sequelizeInstance: sequelize.Sequelize = this;
const config = sequelizeInstance?.config;
let tableName = option?.instance?.constructor?.tableName;
if (!tableName) {
if (Array.isArray(option?.tableNames) && option.tableNames.length > 0)
tableName = option?.tableNames.sort().join(',');
else tableName = extractTableFromQuery(statement);
}
const attributes = {
[SemanticAttributes.DB_SYSTEM]: sequelizeInstance.getDialect(),
[SemanticAttributes.DB_USER]: config?.username,
[SemanticAttributes.NET_PEER_NAME]: config?.host,
[SemanticAttributes.NET_PEER_PORT]: config?.port ? Number(config?.port) : undefined,
[SemanticAttributes.NET_TRANSPORT]: self._getNetTransport(config?.protocol),
[SemanticAttributes.DB_NAME]: config?.database,
[SemanticAttributes.DB_OPERATION]: operation,
[SemanticAttributes.DB_STATEMENT]: statement,
[SemanticAttributes.DB_SQL_TABLE]: tableName,
// [SemanticAttributes.NET_PEER_IP]: '?', // Part of protocol
};
if (self._config.moduleVersionAttributeName) {
attributes[self._config.moduleVersionAttributeName] = self.moduleVersion;
}
Object.entries(attributes).forEach(([key, value]) => {
if (value === undefined) delete attributes[key];
});
const newSpan: Span = self.tracer.startSpan(`Sequelize ${operation}`, {
kind: SpanKind.CLIENT,
attributes,
});
const activeContextWithSpan = trace.setSpan(context.active(), newSpan);
return context
.with(
self._config.suppressInternalInstrumentation
? suppressTracing(activeContextWithSpan)
: activeContextWithSpan,
() => original.apply(this, arguments)
)
.then((response: any) => {
if (self._config?.responseHook) {
safeExecuteInTheMiddle(
() => self._config.responseHook(newSpan, response),
(e: Error) => {
if (e) diag.error('sequelize instrumentation: responseHook error', e);
},
true
);
}
return response;
})
.catch((err: Error) => {
newSpan.setStatus({
code: SpanStatusCode.ERROR,
message: err.message,
});
throw err;
})
.finally(() => {
newSpan.end();
});
};
}
private _getNetTransport(protocol: string) {
switch (protocol) {
case 'tcp':
return NetTransportValues.IP_TCP;
default:
return undefined;
}
}
}