/
pg.test.ts
550 lines (502 loc) · 17.4 KB
/
pg.test.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/*
* 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 {
SpanAttributes,
SpanStatusCode,
context,
Span,
SpanKind,
SpanStatus,
trace,
} from '@opentelemetry/api';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
import * as testUtils from '@opentelemetry/test-utils';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/tracing';
import * as assert from 'assert';
import type * as pg from 'pg';
import {
PgInstrumentation,
PgInstrumentationConfig,
PgResponseHookInformation,
} from '../src';
import { AttributeNames } from '../src/enums/AttributeNames';
import { TimedEvent } from './types';
import {
SemanticAttributes,
DbSystemValues,
} from '@opentelemetry/semantic-conventions';
const memoryExporter = new InMemorySpanExporter();
const CONFIG = {
user: process.env.POSTGRES_USER || 'postgres',
password: process.env.POSTGRES_PASSWORD || 'postgres',
database: process.env.POSTGRES_DB || 'postgres',
host: process.env.POSTGRES_HOST || 'localhost',
port: process.env.POSTGRES_PORT
? parseInt(process.env.POSTGRES_PORT, 10)
: 54320,
};
const DEFAULT_ATTRIBUTES = {
[SemanticAttributes.DB_SYSTEM]: DbSystemValues.POSTGRESQL,
[SemanticAttributes.DB_NAME]: CONFIG.database,
[SemanticAttributes.NET_PEER_NAME]: CONFIG.host,
[SemanticAttributes.DB_CONNECTION_STRING]: `jdbc:postgresql://${CONFIG.host}:${CONFIG.port}/${CONFIG.database}`,
[SemanticAttributes.NET_PEER_PORT]: CONFIG.port,
[SemanticAttributes.DB_USER]: CONFIG.user,
};
const unsetStatus: SpanStatus = {
code: SpanStatusCode.UNSET,
};
const errorStatus: SpanStatus = {
code: SpanStatusCode.ERROR,
};
const runCallbackTest = (
span: Span | null,
attributes: SpanAttributes,
events: TimedEvent[],
status: SpanStatus = unsetStatus,
spansLength = 1,
spansIndex = 0
) => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, spansLength);
const pgSpan = spans[spansIndex];
testUtils.assertSpan(pgSpan, SpanKind.CLIENT, attributes, events, status);
if (span) {
testUtils.assertPropagation(pgSpan, span);
}
};
describe('pg@7.x', () => {
function create(config: PgInstrumentationConfig = {}) {
instrumentation.setConfig(config);
instrumentation.enable();
}
let client: pg.Client;
let instrumentation: PgInstrumentation;
let contextManager: AsyncHooksContextManager;
const provider = new BasicTracerProvider();
const tracer = provider.getTracer('external');
const testPostgres = process.env.RUN_POSTGRES_TESTS; // For CI: assumes local postgres db is already available
const testPostgresLocally = process.env.RUN_POSTGRES_TESTS_LOCAL; // For local: spins up local postgres db via docker
const shouldTest = testPostgres || testPostgresLocally; // Skips these tests if false (default)
before(async function () {
if (!shouldTest) {
// this.skip() workaround
// https://github.com/mochajs/mocha/issues/2683#issuecomment-375629901
this.test!.parent!.pending = true;
this.skip();
}
provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter));
if (testPostgresLocally) {
testUtils.startDocker('postgres');
}
instrumentation = new PgInstrumentation();
contextManager = new AsyncHooksContextManager().enable();
context.setGlobalContextManager(contextManager);
instrumentation.setTracerProvider(provider);
const pg = require('pg');
client = new pg.Client(CONFIG);
await client.connect();
});
after(async () => {
if (testPostgresLocally) {
testUtils.cleanUpDocker('postgres');
}
await client.end();
});
beforeEach(() => {
contextManager = new AsyncHooksContextManager().enable();
context.setGlobalContextManager(contextManager);
});
afterEach(() => {
memoryExporter.reset();
context.disable();
});
it('should return an instrumentation', () => {
assert.ok(instrumentation instanceof PgInstrumentation);
});
it('should have correct name', () => {
assert.strictEqual(
instrumentation.instrumentationName,
'@opentelemetry/instrumentation-pg'
);
});
it('should maintain pg module error throwing behavior with bad arguments', () => {
const assertPgError = (e: Error) => {
const src = e.stack!.split('\n').map(line => line.trim())[1];
return /node_modules[/\\]pg/.test(src);
};
assert.throws(
() => {
(client as any).query();
},
assertPgError,
'pg should throw when no args provided'
);
runCallbackTest(null, DEFAULT_ATTRIBUTES, [], errorStatus);
memoryExporter.reset();
assert.doesNotThrow(
() =>
(client as any).query({ foo: 'bar' }, undefined, () => {
runCallbackTest(
null,
{
...DEFAULT_ATTRIBUTES,
},
[],
errorStatus
);
}),
'pg should not throw when invalid config args are provided'
);
});
describe('#client.query(...)', () => {
it('should not return a promise if callback is provided', done => {
const res = client.query('SELECT NOW()', (err, res) => {
assert.strictEqual(err, null);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
it('should return a promise if callback is not provided', done => {
const resPromise = client.query('SELECT NOW()');
resPromise
.then(res => {
assert.ok(res);
done();
})
.catch((err: Error) => {
assert.ok(false, err.message);
});
});
it('should intercept client.query(text, callback)', done => {
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: 'SELECT NOW()',
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const res = client.query('SELECT NOW()', (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
});
it('should intercept client.query(text, values, callback)', done => {
const query = 'SELECT $1::text';
const values = ['0'];
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const resNoPromise = client.query(query, values, (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
assert.strictEqual(resNoPromise, undefined, 'No promise is returned');
});
});
it('should intercept client.query({text, callback})', done => {
const query = 'SELECT NOW()';
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const resNoPromise = client.query({
text: query,
callback: (err: Error, res: pg.QueryResult) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
},
} as pg.QueryConfig);
assert.strictEqual(resNoPromise, undefined, 'No promise is returned');
});
});
it('should intercept client.query({text}, callback)', done => {
const query = 'SELECT NOW()';
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const resNoPromise = client.query({ text: query }, (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
assert.strictEqual(resNoPromise, undefined, 'No promise is returned');
});
});
it('should intercept client.query(text, values)', async () => {
const query = 'SELECT $1::text';
const values = ['0'];
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
const resPromise = await client.query(query, values);
try {
assert.ok(resPromise);
runCallbackTest(span, attributes, events);
} catch (e) {
assert.ok(false, e.message);
}
});
});
it('should intercept client.query({text, values})', async () => {
const query = 'SELECT $1::text';
const values = ['0'];
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
const resPromise = await client.query({
text: query,
values: values,
});
try {
assert.ok(resPromise);
runCallbackTest(span, attributes, events);
} catch (e) {
assert.ok(false, e.message);
}
});
});
it('should intercept client.query(plan)', async () => {
const name = 'fetch-text';
const query = 'SELECT $1::text';
const values = ['0'];
const attributes = {
...DEFAULT_ATTRIBUTES,
[AttributeNames.PG_PLAN]: name,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
try {
const resPromise = await client.query({
name: name,
text: query,
values: values,
});
assert.strictEqual(resPromise.command, 'SELECT');
runCallbackTest(span, attributes, events);
} catch (e) {
assert.ok(false, e.message);
}
});
});
it('should intercept client.query(text)', async () => {
const query = 'SELECT NOW()';
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
const events: TimedEvent[] = [];
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
try {
const resPromise = await client.query(query);
assert.ok(resPromise);
runCallbackTest(span, attributes, events);
} catch (e) {
assert.ok(false, e.message);
}
});
});
describe('when specifying a responseHook configuration', () => {
const dataAttributeName = 'pg_data';
const query = 'SELECT 0::text';
const events: TimedEvent[] = [];
describe('AND valid responseHook', () => {
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
[dataAttributeName]: '{"rowCount":1}',
};
beforeEach(async () => {
const config: PgInstrumentationConfig = {
enhancedDatabaseReporting: true,
responseHook: (
span: Span,
responseInfo: PgResponseHookInformation
) =>
span.setAttribute(
dataAttributeName,
JSON.stringify({ rowCount: responseInfo?.data.rowCount })
),
};
create(config);
});
it('should attach response hook data to resulting spans for query with callback ', done => {
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const res = client.query(query, (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
});
it('should attach response hook data to resulting spans for query returning a Promise', async () => {
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
[dataAttributeName]: '{"rowCount":1}',
};
const span = tracer.startSpan('test span');
await context.with(
trace.setSpan(context.active(), span),
async () => {
const resPromise = await client.query({
text: query,
});
try {
assert.ok(resPromise);
runCallbackTest(span, attributes, events);
} catch (e) {
assert.ok(false, e.message);
}
}
);
});
});
describe('AND invalid responseHook', () => {
const attributes = {
...DEFAULT_ATTRIBUTES,
[SemanticAttributes.DB_STATEMENT]: query,
};
beforeEach(async () => {
create({
enhancedDatabaseReporting: true,
responseHook: (
span: Span,
responseInfo: PgResponseHookInformation
) => {
throw 'some kind of failure!';
},
});
});
it('should not do any harm when throwing an exception', done => {
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const res = client.query(query, (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
});
});
});
it('should handle the same callback being given to multiple client.query()s', done => {
let events = 0;
const parent = tracer.startSpan('parent');
const queryHandler = (err?: Error, res?: pg.QueryResult) => {
const span = trace.getSpan(context.active());
assert.deepStrictEqual(span!.spanContext(), parent.spanContext());
if (err) {
throw err;
}
events += 1;
if (events === 7) {
done();
}
};
const config = {
text: 'SELECT NOW()',
callback: queryHandler,
};
context.with(trace.setSpan(context.active(), parent), () => {
client.query(config.text, config.callback); // 1
client.query(config); // 2
client.query(config.text, queryHandler); // 3
client.query(config.text, queryHandler); // 4
client
.query(config.text)
.then(result => queryHandler(undefined, result))
.catch(err => queryHandler(err)); // 5
client.query(config); // 6
client.query(config); // 7
});
});
it('should preserve correct context even when using the same callback in client.query()', done => {
const spans = [tracer.startSpan('span 1'), tracer.startSpan('span 2')];
const currentSpans: (Span | undefined)[] = [];
const queryHandler = () => {
currentSpans.push(trace.getSpan(context.active()));
if (currentSpans.length === 2) {
assert.deepStrictEqual(currentSpans, spans);
done();
}
};
context.with(trace.setSpan(context.active(), spans[0]), () => {
client.query('SELECT NOW()', queryHandler);
});
context.with(trace.setSpan(context.active(), spans[1]), () => {
client.query('SELECT NOW()', queryHandler);
});
});
it('should preserve correct context even when using the same promise resolver in client.query()', done => {
const spans = [tracer.startSpan('span 1'), tracer.startSpan('span 2')];
const currentSpans: (Span | undefined)[] = [];
const queryHandler = () => {
currentSpans.push(trace.getSpan(context.active()));
if (currentSpans.length === 2) {
assert.deepStrictEqual(currentSpans, spans);
done();
}
};
context.with(trace.setSpan(context.active(), spans[0]), () => {
client.query('SELECT NOW()').then(queryHandler);
});
context.with(trace.setSpan(context.active(), spans[1]), () => {
client.query('SELECT NOW()').then(queryHandler);
});
});
});
});