/
instrumentation.ts
428 lines (387 loc) · 14.3 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
* 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 {
isWrapped,
InstrumentationBase,
InstrumentationNodeModuleDefinition,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import {
context,
trace,
Span,
SpanStatusCode,
SpanKind,
} from '@opentelemetry/api';
import type * as pgTypes from 'pg';
import type * as pgPoolTypes from 'pg-pool';
import {
PgClientConnect,
PgClientExtended,
PostgresCallback,
PgPoolExtended,
PgPoolCallback,
} from './internal-types';
import { PgInstrumentationConfig } from './types';
import * as utils from './utils';
import { AttributeNames } from './enums/AttributeNames';
import {
SemanticAttributes,
DbSystemValues,
} from '@opentelemetry/semantic-conventions';
import { addSqlCommenterComment } from '@opentelemetry/sql-common';
import { VERSION } from './version';
const PG_POOL_COMPONENT = 'pg-pool';
export class PgInstrumentation extends InstrumentationBase {
static readonly COMPONENT = 'pg';
static readonly BASE_SPAN_NAME = PgInstrumentation.COMPONENT + '.query';
constructor(config: PgInstrumentationConfig = {}) {
super(
'@opentelemetry/instrumentation-pg',
VERSION,
Object.assign({}, config)
);
}
protected init() {
const modulePG = new InstrumentationNodeModuleDefinition<typeof pgTypes>(
'pg',
['8.*'],
(module: any, moduleVersion) => {
this._diag.debug(`Applying patch for pg@${moduleVersion}`);
const moduleExports: typeof pgTypes =
module[Symbol.toStringTag] === 'Module'
? module.default // ESM
: module; // CommonJS
if (isWrapped(moduleExports.Client.prototype.query)) {
this._unwrap(moduleExports.Client.prototype, 'query');
}
if (isWrapped(moduleExports.Client.prototype.connect)) {
this._unwrap(moduleExports.Client.prototype, 'connect');
}
this._wrap(
moduleExports.Client.prototype,
'query',
this._getClientQueryPatch() as any
);
this._wrap(
moduleExports.Client.prototype,
'connect',
this._getClientConnectPatch() as any
);
return module;
},
(module: any, moduleVersion) => {
const moduleExports: typeof pgTypes =
module[Symbol.toStringTag] === 'Module'
? module.default // ESM
: module; // CommonJS
this._diag.debug(`Removing patch for pg@${moduleVersion}`);
if (isWrapped(moduleExports.Client.prototype.query)) {
this._unwrap(moduleExports.Client.prototype, 'query');
}
}
);
const modulePGPool = new InstrumentationNodeModuleDefinition<
typeof pgPoolTypes
>(
'pg-pool',
['2.*', '3.*'],
(moduleExports, moduleVersion) => {
this._diag.debug(`Applying patch for pg-pool@${moduleVersion}`);
if (isWrapped(moduleExports.prototype.connect)) {
this._unwrap(moduleExports.prototype, 'connect');
}
this._wrap(
moduleExports.prototype,
'connect',
this._getPoolConnectPatch() as any
);
return moduleExports;
},
(moduleExports, moduleVersion) => {
this._diag.debug(`Removing patch for pg-pool@${moduleVersion}`);
if (isWrapped(moduleExports.prototype.connect)) {
this._unwrap(moduleExports.prototype, 'connect');
}
}
);
return [modulePG, modulePGPool];
}
override setConfig(config: PgInstrumentationConfig = {}) {
this._config = Object.assign({}, config);
}
override getConfig(): PgInstrumentationConfig {
return this._config as PgInstrumentationConfig;
}
private _getClientConnectPatch() {
const plugin = this;
return (original: PgClientConnect) => {
return function connect(this: pgTypes.Client, callback?: Function) {
if (utils.shouldSkipInstrumentation(plugin.getConfig())) {
return original.call(this, callback);
}
const span = plugin.tracer.startSpan(
`${PgInstrumentation.COMPONENT}.connect`,
{
kind: SpanKind.CLIENT,
attributes: {
[SemanticAttributes.DB_SYSTEM]: DbSystemValues.POSTGRESQL,
...utils.getSemanticAttributesFromConnection(this),
},
}
);
if (callback) {
const parentSpan = trace.getSpan(context.active());
callback = utils.patchClientConnectCallback(span, callback);
if (parentSpan) {
callback = context.bind(context.active(), callback);
}
}
const connectResult: unknown = context.with(
trace.setSpan(context.active(), span),
() => {
return original.call(this, callback);
}
);
return handleConnectResult(span, connectResult);
};
};
}
private _getClientQueryPatch() {
const plugin = this;
return (original: typeof pgTypes.Client.prototype.query) => {
this._diag.debug(
`Patching ${PgInstrumentation.COMPONENT}.Client.prototype.query`
);
return function query(this: PgClientExtended, ...args: unknown[]) {
if (utils.shouldSkipInstrumentation(plugin.getConfig())) {
return original.apply(this, args as never);
}
// client.query(text, cb?), client.query(text, values, cb?), and
// client.query(configObj, cb?) are all valid signatures. We construct
// a queryConfig obj from all (valid) signatures to build the span in a
// unified way. We verify that we at least have query text, and code
// defensively when dealing with `queryConfig` after that (to handle all
// the other invalid cases, like a non-array for values being provided).
// The type casts here reflect only what we've actually validated.
const arg0 = args[0];
const firstArgIsString = typeof arg0 === 'string';
const firstArgIsQueryObjectWithText =
utils.isObjectWithTextString(arg0);
// TODO: remove the `as ...` casts below when the TS version is upgraded.
// Newer TS versions will use the result of firstArgIsQueryObjectWithText
// to properly narrow arg0, but TS 4.3.5 does not.
const queryConfig = firstArgIsString
? {
text: arg0 as string,
values: Array.isArray(args[1]) ? args[1] : undefined,
}
: firstArgIsQueryObjectWithText
? (arg0 as utils.ObjectWithText)
: undefined;
const instrumentationConfig = plugin.getConfig();
const span = utils.handleConfigQuery.call(
this,
plugin.tracer,
instrumentationConfig,
queryConfig
);
// Modify query text w/ a tracing comment before invoking original for
// tracing, but only if args[0] has one of our expected shapes.
if (instrumentationConfig.addSqlCommenterCommentToQueries) {
args[0] = firstArgIsString
? addSqlCommenterComment(span, arg0)
: firstArgIsQueryObjectWithText
? {
...arg0,
text: addSqlCommenterComment(span, arg0.text),
}
: args[0];
}
// Bind callback (if any) to parent span (if any)
if (args.length > 0) {
const parentSpan = trace.getSpan(context.active());
if (typeof args[args.length - 1] === 'function') {
// Patch ParameterQuery callback
args[args.length - 1] = utils.patchCallback(
instrumentationConfig,
span,
args[args.length - 1] as PostgresCallback // nb: not type safe.
);
// If a parent span exists, bind the callback
if (parentSpan) {
args[args.length - 1] = context.bind(
context.active(),
args[args.length - 1]
);
}
} else if (typeof queryConfig?.callback === 'function') {
// Patch ConfigQuery callback
let callback = utils.patchCallback(
plugin.getConfig(),
span,
queryConfig.callback as PostgresCallback // nb: not type safe.
);
// If a parent span existed, bind the callback
if (parentSpan) {
callback = context.bind(context.active(), callback);
}
(args[0] as { callback?: PostgresCallback }).callback = callback;
}
}
if (
typeof instrumentationConfig.requestHook === 'function' &&
queryConfig
) {
safeExecuteInTheMiddle(
() => {
// pick keys to expose explicitly, so we're not leaking pg package
// internals that are subject to change
const { database, host, port, user } = this.connectionParameters;
const connection = { database, host, port, user };
instrumentationConfig.requestHook!(span, {
connection,
query: {
text: queryConfig.text,
// nb: if `client.query` is called with illegal arguments
// (e.g., if `queryConfig.values` is passed explicitly, but a
// non-array is given), then the type casts will be wrong. But
// we leave it up to the queryHook to handle that, and we
// catch and swallow any errors it throws. The other options
// are all worse. E.g., we could leave `queryConfig.values`
// and `queryConfig.name` as `unknown`, but then the hook body
// would be forced to validate (or cast) them before using
// them, which seems incredibly cumbersome given that these
// casts will be correct 99.9% of the time -- and pg.query
// will immediately throw during development in the other .1%
// of cases. Alternatively, we could simply skip calling the
// hook when `values` or `name` don't have the expected type,
// but that would add unnecessary validation overhead to every
// hook invocation and possibly be even more confusing/unexpected.
values: queryConfig.values as unknown[],
name: queryConfig.name as string | undefined,
},
});
},
err => {
if (err) {
plugin._diag.error('Error running query hook', err);
}
},
true
);
}
let result: unknown;
try {
result = original.apply(this, args as never);
} catch (e: unknown) {
// span.recordException(e);
span.setStatus({
code: SpanStatusCode.ERROR,
message: utils.getErrorMessage(e),
});
span.end();
throw e;
}
// Bind promise to parent span and end the span
if (result instanceof Promise) {
return result
.then((result: unknown) => {
// Return a pass-along promise which ends the span and then goes to user's orig resolvers
return new Promise(resolve => {
utils.handleExecutionResult(plugin.getConfig(), span, result);
span.end();
resolve(result);
});
})
.catch((error: Error) => {
return new Promise((_, reject) => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
span.end();
reject(error);
});
});
}
// else returns void
return result; // void
};
};
}
private _getPoolConnectPatch() {
const plugin = this;
return (originalConnect: typeof pgPoolTypes.prototype.connect) => {
return function connect(this: PgPoolExtended, callback?: PgPoolCallback) {
if (utils.shouldSkipInstrumentation(plugin.getConfig())) {
return originalConnect.call(this, callback as any);
}
// setup span
const span = plugin.tracer.startSpan(`${PG_POOL_COMPONENT}.connect`, {
kind: SpanKind.CLIENT,
attributes: {
[SemanticAttributes.DB_SYSTEM]: DbSystemValues.POSTGRESQL,
...utils.getSemanticAttributesFromConnection(this.options),
[AttributeNames.IDLE_TIMEOUT_MILLIS]:
this.options.idleTimeoutMillis,
[AttributeNames.MAX_CLIENT]: this.options.maxClient,
},
});
if (callback) {
const parentSpan = trace.getSpan(context.active());
callback = utils.patchCallbackPGPool(
span,
callback
) as PgPoolCallback;
// If a parent span exists, bind the callback
if (parentSpan) {
callback = context.bind(context.active(), callback);
}
}
const connectResult: unknown = context.with(
trace.setSpan(context.active(), span),
() => {
return originalConnect.call(this, callback as any);
}
);
return handleConnectResult(span, connectResult);
};
};
}
}
function handleConnectResult(span: Span, connectResult: unknown) {
if (!(connectResult instanceof Promise)) {
return connectResult;
}
const connectResultPromise = connectResult as Promise<unknown>;
return context.bind(
context.active(),
connectResultPromise
.then(result => {
span.end();
return result;
})
.catch((error: unknown) => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: utils.getErrorMessage(error),
});
span.end();
return Promise.reject(error);
})
);
}