-
Notifications
You must be signed in to change notification settings - Fork 532
/
instrumentation.ts
346 lines (323 loc) · 11 KB
/
instrumentation.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
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { getRPCMetadata, RPCType } from '@opentelemetry/core';
import {
trace,
context,
diag,
Attributes,
SpanStatusCode,
} from '@opentelemetry/api';
import type * as express from 'express';
import { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';
import { ExpressLayerType } from './enums/ExpressLayerType';
import { AttributeNames } from './enums/AttributeNames';
import {
asErrorAndMessage,
getLayerMetadata,
getLayerPath,
isLayerIgnored,
storeLayerPath,
} from './utils';
import { PACKAGE_NAME, PACKAGE_VERSION } from './version';
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
isWrapped,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';
import {
ExpressLayer,
ExpressRouter,
kLayerPatched,
PatchedRequest,
_LAYERS_STORE_PROPERTY,
} from './internal-types';
/** Express instrumentation for OpenTelemetry */
export class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumentationConfig> {
constructor(config: ExpressInstrumentationConfig = {}) {
super(PACKAGE_NAME, PACKAGE_VERSION, config);
}
init() {
return [
new InstrumentationNodeModuleDefinition(
'express',
['>=4.0.0 <5'],
moduleExports => {
const routerProto = moduleExports.Router as unknown as express.Router;
// patch express.Router.route
if (isWrapped(routerProto.route)) {
this._unwrap(routerProto, 'route');
}
this._wrap(routerProto, 'route', this._getRoutePatch());
// patch express.Router.use
if (isWrapped(routerProto.use)) {
this._unwrap(routerProto, 'use');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);
// patch express.Application.use
if (isWrapped(moduleExports.application.use)) {
this._unwrap(moduleExports.application, 'use');
}
this._wrap(
moduleExports.application,
'use',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._getAppUsePatch() as any
);
return moduleExports;
},
moduleExports => {
if (moduleExports === undefined) return;
const routerProto = moduleExports.Router as unknown as express.Router;
this._unwrap(routerProto, 'route');
this._unwrap(routerProto, 'use');
this._unwrap(moduleExports.application, 'use');
}
),
];
}
/**
* Get the patch for Router.route function
*/
private _getRoutePatch() {
const instrumentation = this;
return function (original: express.Router['route']) {
return function route_trace(
this: ExpressRouter,
...args: Parameters<typeof original>
) {
const route = original.apply(this, args);
const layer = this.stack[this.stack.length - 1] as ExpressLayer;
instrumentation._applyPatch(layer, getLayerPath(args));
return route;
};
};
}
/**
* Get the patch for Router.use function
*/
private _getRouterUsePatch() {
const instrumentation = this;
return function (original: express.Router['use']) {
return function use(
this: express.Application,
...args: Parameters<typeof original>
) {
const route = original.apply(this, args);
const layer = this.stack[this.stack.length - 1] as ExpressLayer;
instrumentation._applyPatch(layer, getLayerPath(args));
return route;
};
};
}
/**
* Get the patch for Application.use function
*/
private _getAppUsePatch() {
const instrumentation = this;
return function (original: express.Application['use']) {
return function use(
this: { _router: ExpressRouter },
...args: Parameters<typeof original>
) {
const route = original.apply(this, args);
const layer = this._router.stack[this._router.stack.length - 1];
instrumentation._applyPatch(layer, getLayerPath(args));
return route;
};
};
}
/** Patch each express layer to create span and propagate context */
private _applyPatch(
this: ExpressInstrumentation,
layer: ExpressLayer,
layerPath?: string
) {
const instrumentation = this;
// avoid patching multiple times the same layer
if (layer[kLayerPatched] === true) return;
layer[kLayerPatched] = true;
this._wrap(layer, 'handle', original => {
// TODO: instrument error handlers
if (original.length === 4) return original;
const patched = function (
this: ExpressLayer,
req: PatchedRequest,
res: express.Response
) {
storeLayerPath(req, layerPath);
const route = (req[_LAYERS_STORE_PROPERTY] as string[])
.filter(path => path !== '/' && path !== '/*')
.join('')
// remove duplicate slashes to normalize route
.replace(/\/{2,}/g, '/');
const attributes: Attributes = {
[SEMATTRS_HTTP_ROUTE]: route.length > 0 ? route : '/',
};
const metadata = getLayerMetadata(route, layer, layerPath);
const type = metadata.attributes[
AttributeNames.EXPRESS_TYPE
] as ExpressLayerType;
const rpcMetadata = getRPCMetadata(context.active());
if (rpcMetadata?.type === RPCType.HTTP) {
rpcMetadata.route = route || '/';
}
// verify against the config if the layer should be ignored
if (isLayerIgnored(metadata.name, type, instrumentation.getConfig())) {
if (type === ExpressLayerType.MIDDLEWARE) {
(req[_LAYERS_STORE_PROPERTY] as string[]).pop();
}
return original.apply(this, arguments);
}
if (trace.getSpan(context.active()) === undefined) {
return original.apply(this, arguments);
}
const spanName = instrumentation._getSpanName(
{
request: req,
layerType: type,
route,
},
metadata.name
);
const span = instrumentation.tracer.startSpan(spanName, {
attributes: Object.assign(attributes, metadata.attributes),
});
const { requestHook } = instrumentation.getConfig();
if (requestHook) {
safeExecuteInTheMiddle(
() =>
requestHook(span, {
request: req,
layerType: type,
route,
}),
e => {
if (e) {
diag.error('express instrumentation: request hook failed', e);
}
},
true
);
}
let spanHasEnded = false;
if (
metadata.attributes[AttributeNames.EXPRESS_TYPE] !==
ExpressLayerType.MIDDLEWARE
) {
span.end();
spanHasEnded = true;
}
// listener for response.on('finish')
const onResponseFinish = () => {
if (spanHasEnded === false) {
spanHasEnded = true;
span.end();
}
};
// verify we have a callback
const args = Array.from(arguments);
const callbackIdx = args.findIndex(arg => typeof arg === 'function');
if (callbackIdx >= 0) {
arguments[callbackIdx] = function () {
// express considers anything but an empty value, "route" or "router"
// passed to its callback to be an error
const maybeError = arguments[0];
const isError = ![undefined, null, 'route', 'router'].includes(
maybeError
);
if (!spanHasEnded && isError) {
const [error, message] = asErrorAndMessage(maybeError);
span.recordException(error);
span.setStatus({
code: SpanStatusCode.ERROR,
message,
});
}
if (spanHasEnded === false) {
spanHasEnded = true;
req.res?.removeListener('finish', onResponseFinish);
span.end();
}
if (!(req.route && isError)) {
(req[_LAYERS_STORE_PROPERTY] as string[]).pop();
}
const callback = args[callbackIdx] as Function;
return callback.apply(this, arguments);
};
}
try {
return original.apply(this, arguments);
} catch (anyError) {
const [error, message] = asErrorAndMessage(anyError);
span.recordException(error);
span.setStatus({
code: SpanStatusCode.ERROR,
message,
});
throw anyError;
} finally {
/**
* At this point if the callback wasn't called, that means either the
* layer is asynchronous (so it will call the callback later on) or that
* the layer directly end the http response, so we'll hook into the "finish"
* event to handle the later case.
*/
if (!spanHasEnded) {
res.once('finish', onResponseFinish);
}
}
};
// `handle` isn't just a regular function in some cases. It also contains
// some properties holding metadata and state so we need to proxy them
// through through patched function
// ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950
// Also some apps/libs do their own patching before OTEL and have these properties
// in the proptotype. So we use a `for...in` loop to get own properties and also
// any enumerable prop in the prototype chain
// ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271
for (const key in original) {
Object.defineProperty(patched, key, {
get() {
return original[key];
},
set(value) {
original[key] = value;
},
});
}
return patched;
});
}
_getSpanName(info: ExpressRequestInfo, defaultName: string) {
const { spanNameHook } = this.getConfig();
if (!(spanNameHook instanceof Function)) {
return defaultName;
}
try {
return spanNameHook(info, defaultName) ?? defaultName;
} catch (err) {
diag.error(
'express instrumentation: error calling span name rewrite hook',
err
);
return defaultName;
}
}
}