-
Notifications
You must be signed in to change notification settings - Fork 544
/
Copy pathpg.test.ts
1125 lines (1014 loc) · 35.5 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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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/contrib-test-utils';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { DataPoint, Histogram } from '@opentelemetry/sdk-metrics';
import * as assert from 'assert';
import type * as pg from 'pg';
import * as sinon from 'sinon';
import stringify from 'safe-stable-stringify';
import {
PgInstrumentation,
PgInstrumentationConfig,
PgResponseHookInformation,
} from '../src';
import { AttributeNames } from '../src/enums/AttributeNames';
import { TimedEvent } from './types';
import {
SEMATTRS_DB_STATEMENT,
SEMATTRS_DB_SYSTEM,
SEMATTRS_DB_NAME,
SEMATTRS_NET_PEER_NAME,
SEMATTRS_DB_CONNECTION_STRING,
SEMATTRS_NET_PEER_PORT,
SEMATTRS_DB_USER,
DBSYSTEMVALUES_POSTGRESQL,
ATTR_ERROR_TYPE,
} from '@opentelemetry/semantic-conventions';
import {
METRIC_DB_CLIENT_OPERATION_DURATION,
ATTR_DB_OPERATION_NAME,
} from '../src/semconv';
import { addSqlCommenterComment } from '@opentelemetry/sql-common';
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 = {
[SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_POSTGRESQL,
[SEMATTRS_DB_NAME]: CONFIG.database,
[SEMATTRS_NET_PEER_NAME]: CONFIG.host,
[SEMATTRS_DB_CONNECTION_STRING]: `postgresql://${CONFIG.host}:${CONFIG.port}/${CONFIG.database}`,
[SEMATTRS_NET_PEER_PORT]: CONFIG.port,
[SEMATTRS_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', () => {
function create(config: PgInstrumentationConfig = {}) {
instrumentation.setConfig(config);
instrumentation.enable();
// Disable and enable the instrumentation to visit unwrap calls
instrumentation.disable();
instrumentation.enable();
}
let postgres: typeof pg;
let client: pg.Client;
let instrumentation: PgInstrumentation;
let contextManager: AsyncHooksContextManager;
const provider = new BasicTracerProvider({
spanProcessors: [new SimpleSpanProcessor(memoryExporter)],
});
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)
function getExecutedQueries() {
return (client as any).queryQueue.push.args.flat() as (pg.Query & {
text?: string;
})[];
}
before(async function () {
const skip = () => {
// this.skip() workaround
// https://github.com/mochajs/mocha/issues/2683#issuecomment-375629901
this.test!.parent!.pending = true;
this.skip();
};
if (!shouldTest) {
skip();
}
if (testPostgresLocally) {
testUtils.startDocker('postgres');
}
instrumentation = new PgInstrumentation();
contextManager = new AsyncHooksContextManager().enable();
context.setGlobalContextManager(contextManager);
instrumentation.setTracerProvider(provider);
postgres = require('pg');
client = new postgres.Client(CONFIG);
await client.connect();
});
after(async () => {
if (testPostgresLocally) {
testUtils.cleanUpDocker('postgres');
}
await client.end();
});
beforeEach(() => {
contextManager = new AsyncHooksContextManager().enable();
context.setGlobalContextManager(contextManager);
// Add a spy on the underlying client's internal query queue so that
// we could assert on what the final queries are that are executed
sinon.spy((client as any).queryQueue, 'push');
});
afterEach(() => {
memoryExporter.reset();
context.disable();
sinon.restore();
});
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.throws(
() => {
(client as any).query(null);
},
assertPgError,
'pg should throw when null provided as only arg'
);
runCallbackTest(null, DEFAULT_ATTRIBUTES, [], errorStatus);
memoryExporter.reset();
assert.throws(
() => {
(client as any).query(undefined);
},
assertPgError,
'pg should throw when undefined provided as only arg'
);
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.connect(...)', () => {
let connClient: pg.Client;
beforeEach(() => {
connClient = new postgres.Client(CONFIG);
});
afterEach(async () => {
await connClient.end();
});
it('should not return a promise when callback is provided', done => {
const res = connClient.connect(err => {
assert.strictEqual(err, null);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
it('should pass the client connection object in the callback function', done => {
connClient.connect(function (err: Error) {
// Even though the documented signature for connect() callback is `(err) => void`
// `pg` actually also passes the client if the connection was successful and some
// packages(`knex`) might rely on that
// https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/client.js#L282
assert.strictEqual(arguments[1], connClient);
done();
});
});
it('should return a promise if callback is not provided', done => {
const resPromise = connClient.connect();
resPromise
.then(res => {
assert.equal(res, undefined);
assert.deepStrictEqual(
memoryExporter.getFinishedSpans()[0].name,
'pg.connect'
);
done();
})
.catch((err: Error) => {
assert.ok(false, err.message);
});
});
it('should throw on failure', done => {
connClient = new postgres.Client({ ...CONFIG, port: 59999 });
connClient
.connect()
.then(() => assert.fail('expected connect to throw'))
.catch(err => {
assert(err instanceof Error);
done();
});
});
it('should call back with an error', done => {
connClient = new postgres.Client({ ...CONFIG, port: 59999 });
connClient.connect(err => {
assert(err instanceof Error);
done();
});
});
it('should intercept connect', async () => {
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), async () => {
await connClient.connect();
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 1);
const connectSpan = spans[0];
assert.deepStrictEqual(connectSpan.name, 'pg.connect');
testUtils.assertSpan(
connectSpan,
SpanKind.CLIENT,
DEFAULT_ATTRIBUTES,
[],
{ code: SpanStatusCode.UNSET }
);
testUtils.assertPropagation(connectSpan, span);
});
});
it('should not generate traces when requireParentSpan=true is specified', async () => {
instrumentation.setConfig({
requireParentSpan: true,
});
memoryExporter.reset();
await connClient.connect();
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 0);
});
});
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,
[SEMATTRS_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,
[SEMATTRS_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,
[SEMATTRS_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,
[SEMATTRS_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,
[SEMATTRS_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: any) {
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,
[SEMATTRS_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: any) {
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,
[SEMATTRS_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: any) {
assert.ok(false, e.message);
}
});
});
it('should intercept client.query(text)', async () => {
const query = 'SELECT NOW()';
const attributes = {
...DEFAULT_ATTRIBUTES,
[SEMATTRS_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: any) {
assert.ok(false, e.message);
}
});
});
describe('Check configuration enhancedDatabaseReporting:true', () => {
const obj = { type: 'Fiat', model: '500', color: 'white' };
const buf = Buffer.from('abc');
const objWithToPostgres = {
toPostgres: () => {
return 'custom value';
},
};
const query =
'SELECT $1::text as msg1, $2::bytea as bufferParam, $3::integer as numberParam, $4::jsonb as objectParam, $5::text as objToPostgres, $6::text as msg2, $7::text as msg3';
const values = [
'Hello,World',
buf,
6,
obj,
objWithToPostgres,
null,
undefined,
];
const events: TimedEvent[] = [];
const attributes = {
...DEFAULT_ATTRIBUTES,
[SEMATTRS_DB_STATEMENT]: query,
[AttributeNames.PG_VALUES]: [
'Hello,World',
'abc',
'6',
'{"type":"Fiat","model":"500","color":"white"}',
'custom value',
'null',
'null',
],
};
beforeEach(async () => {
create({
enhancedDatabaseReporting: true,
});
});
it('When enhancedDatabaseReporting:true, values should appear as parsable array of strings', done => {
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
client.query(query, values, (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
runCallbackTest(span, attributes, events);
done();
});
});
});
});
describe('when specifying a requestHook configuration', () => {
const dataAttributeName = 'pg_data';
const query = 'SELECT 0::text';
const events: TimedEvent[] = [];
// these are the attributes that we'd expect would end up on the final
// span if there is no requestHook.
const attributes = {
...DEFAULT_ATTRIBUTES,
[SEMATTRS_DB_STATEMENT]: query,
};
// These are the attributes we expect on the span after the requestHook
// has run. We set up the hook to just add to the span a stringified
// version of the args it receives (which is an easy way to assert both
// that the proper args were passed and that the hook was called).
const attributesAfterHook = {
...attributes,
[dataAttributeName]: stringify({
connection: {
database: CONFIG.database,
port: CONFIG.port,
host: CONFIG.host,
user: CONFIG.user,
},
query: { text: query },
}),
};
describe('AND valid requestHook', () => {
beforeEach(async () => {
create({
enhancedDatabaseReporting: true,
requestHook: (span, requestInfo) => {
span.setAttribute(dataAttributeName, stringify(requestInfo));
},
});
});
it('should attach request 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, attributesAfterHook, events);
done();
});
assert.strictEqual(res, undefined, 'No promise is returned');
});
});
it('should attach request hook data to resulting spans for query returning a Promise', async () => {
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, attributesAfterHook, events);
} catch (e: any) {
assert.ok(false, e.message);
}
}
);
});
});
describe('AND invalid requestHook', () => {
beforeEach(async () => {
create({
enhancedDatabaseReporting: true,
requestHook: (_span, _requestInfo) => {
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');
});
});
});
});
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,
[SEMATTRS_DB_STATEMENT]: query,
[dataAttributeName]: '{"rowCount":1}',
};
beforeEach(async () => {
create({
enhancedDatabaseReporting: true,
responseHook: (
span: Span,
responseInfo: PgResponseHookInformation
) =>
span.setAttribute(
dataAttributeName,
JSON.stringify({ rowCount: responseInfo?.data.rowCount })
),
});
});
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,
[SEMATTRS_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: any) {
assert.ok(false, e.message);
}
}
);
});
});
describe('AND invalid responseHook', () => {
const attributes = {
...DEFAULT_ATTRIBUTES,
[SEMATTRS_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);
});
});
it('should not add sqlcommenter comment when flag is not specified', async () => {
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
try {
const query = 'SELECT NOW()';
const resPromise = await client.query(query);
assert.ok(resPromise);
const [span] = memoryExporter.getFinishedSpans();
assert.ok(span);
const executedQueries = getExecutedQueries();
assert.equal(executedQueries.length, 1);
assert.equal(executedQueries[0].text, query);
} catch (e: any) {
assert.ok(false, e.message);
}
});
});
it('should not add sqlcommenter comment with client.query({text, callback}) when flag is not specified', done => {
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const query = 'SELECT NOW()';
client.query({
text: query,
callback: (err: Error, res: pg.QueryResult) => {
assert.strictEqual(err, null);
assert.ok(res);
const [span] = memoryExporter.getFinishedSpans();
assert.ok(span);
const executedQueries = getExecutedQueries();
assert.equal(executedQueries.length, 1);
assert.equal(executedQueries[0].text, query);
done();
},
} as pg.QueryConfig);
});
});
it('should add sqlcommenter comment when addSqlCommenterCommentToQueries=true is specified', async () => {
instrumentation.setConfig({
addSqlCommenterCommentToQueries: true,
});
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
try {
const query = 'SELECT NOW()';
const resPromise = await client.query(query);
assert.ok(resPromise);
const [span] = memoryExporter.getFinishedSpans();
const commentedQuery = addSqlCommenterComment(
trace.wrapSpanContext(span.spanContext()),
query
);
const executedQueries = getExecutedQueries();
assert.equal(executedQueries.length, 1);
assert.equal(executedQueries[0].text, commentedQuery);
assert.notEqual(query, commentedQuery);
} catch (e: any) {
assert.ok(false, e.message);
}
});
});
it('should add sqlcommenter comment when addSqlCommenterCommentToQueries=true is specified with client.query({text, callback})', done => {
instrumentation.setConfig({
addSqlCommenterCommentToQueries: true,
});
const span = tracer.startSpan('test span');
context.with(trace.setSpan(context.active(), span), () => {
const query = 'SELECT NOW()';
client.query({
text: query,
callback: (err: Error, res: pg.QueryResult) => {
assert.strictEqual(err, null);
assert.ok(res);
const [span] = memoryExporter.getFinishedSpans();
const commentedQuery = addSqlCommenterComment(
trace.wrapSpanContext(span.spanContext()),
query
);
const executedQueries = getExecutedQueries();
assert.equal(executedQueries.length, 1);
assert.equal(executedQueries[0].text, commentedQuery);
assert.notEqual(query, commentedQuery);
done();
},
} as pg.QueryConfig);
});
});
it('should not add sqlcommenter comment when addSqlCommenterCommentToQueries=true is specified with a prepared statement', async () => {
instrumentation.setConfig({
addSqlCommenterCommentToQueries: true,
});
const span = tracer.startSpan('test span');
await context.with(trace.setSpan(context.active(), span), async () => {
try {
const query = 'SELECT NOW()';
const resPromise = await client.query({
text: query,
name: 'prepared sqlcommenter',
});
assert.ok(resPromise);
const [span] = memoryExporter.getFinishedSpans();
assert.ok(span);
const executedQueries = getExecutedQueries();
assert.equal(executedQueries.length, 1);
assert.equal(executedQueries[0].text, query);
} catch (e: any) {
assert.ok(false, e.message);
}
});
});
it('should not generate traces for client.query() when requireParentSpan=true is specified', done => {
instrumentation.setConfig({
requireParentSpan: true,
});
memoryExporter.reset();
client.query('SELECT NOW()', (err, res) => {
assert.strictEqual(err, null);
assert.ok(res);
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 0);
done();
});
});
});
describe('pg metrics', () => {
let metricReader: testUtils.TestMetricReader;
beforeEach(() => {
metricReader = testUtils.initMeterProvider(instrumentation);
});