forked from googleapis/nodejs-spanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session-pool.ts
1356 lines (1054 loc) · 39.1 KB
/
session-pool.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 2017 Google Inc. All Rights Reserved.
*
* 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
*
* http://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 * as assert from 'assert';
import {before, beforeEach, afterEach, describe, it} from 'mocha';
import * as events from 'events';
import * as extend from 'extend';
import PQueue from 'p-queue';
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';
import stackTrace = require('stack-trace');
import timeSpan = require('time-span');
import {Database} from '../src/database';
import {Session} from '../src/session';
import * as sp from '../src/session-pool';
import {Transaction} from '../src/transaction';
import {grpc} from 'google-gax';
let pQueueOverride: typeof PQueue | null = null;
function FakePQueue(options) {
return new (pQueueOverride || PQueue)(options);
}
FakePQueue.default = FakePQueue;
class FakeTransaction {
options;
constructor(options?) {
this.options = options;
}
async begin(): Promise<void> {}
}
const fakeStackTrace = extend({}, stackTrace);
function noop() {}
describe('SessionPool', () => {
let sessionPool: sp.SessionPool;
// tslint:disable-next-line variable-name
let SessionPool: typeof sp.SessionPool;
let inventory;
const DATABASE = {
batchCreateSessions: noop,
databaseRole: 'parent_role',
} as unknown as Database;
const sandbox = sinon.createSandbox();
const shouldNotBeCalled = sandbox.stub().throws('Should not be called.');
const createSession = (name = 'id', props?): Session => {
props = props || {};
return Object.assign(new Session(DATABASE, name), props, {
create: sandbox.stub().resolves(),
delete: sandbox.stub().resolves(),
keepAlive: sandbox.stub().resolves(),
transaction: sandbox.stub().returns(new FakeTransaction()),
});
};
const createStackFrame = (): stackTrace.StackFrame => {
return {
getFunctionName: sandbox.stub().returns('myFunction'),
getMethodName: sandbox.stub().returns('MyClass.myMethod'),
getFileName: sandbox.stub().returns('path/to/file.js'),
getLineNumber: sandbox.stub().returns('99'),
getColumnNumber: sandbox.stub().returns('13'),
getTypeName: sandbox.stub().returns('type'),
isNative: sandbox.stub().returns(false),
isConstructor: sandbox.stub().returns(false),
};
};
before(() => {
SessionPool = proxyquire('../src/session-pool.js', {
'p-queue': FakePQueue,
'stack-trace': fakeStackTrace,
}).SessionPool;
});
beforeEach(() => {
DATABASE.session = createSession;
sessionPool = new SessionPool(DATABASE);
inventory = sessionPool._inventory;
});
afterEach(() => {
pQueueOverride = null;
sandbox.restore();
});
describe('formatTrace', () => {
let stackFrame: stackTrace.StackFrame;
let fakeTrace: stackTrace.StackFrame[];
let file: string;
beforeEach(() => {
stackFrame = createStackFrame();
fakeTrace = [stackFrame];
file = `${stackFrame.getFileName()}:${stackFrame.getLineNumber()}:${stackFrame.getColumnNumber()}`;
});
it('should return a trace with the method name', () => {
(stackFrame.getFunctionName as sinon.SinonStub).returns(undefined);
const expected = `Session leak detected!\n at ${stackFrame.getMethodName()} (${file})`;
const actual = SessionPool.formatTrace(fakeTrace);
assert.strictEqual(expected, actual);
});
it('should return a trace with the function name', () => {
(stackFrame.getMethodName as sinon.SinonStub).returns(undefined);
const expected = `Session leak detected!\n at ${stackFrame.getFunctionName()} (${file})`;
const actual = SessionPool.formatTrace(fakeTrace);
assert.strictEqual(expected, actual);
});
});
describe('available', () => {
it('should return the number of available sessions', () => {
inventory.sessions = [createSession(), createSession(), createSession()];
assert.strictEqual(sessionPool.available, 3);
});
});
describe('borrowed', () => {
beforeEach(() => {
inventory.borrowed = new Set([createSession(), createSession()]);
});
it('should return the number of borrowed sessions', () => {
assert.strictEqual(sessionPool.borrowed, 2);
});
it('should factor in any creation pending sessions', () => {
sessionPool._pending = 1;
assert.strictEqual(sessionPool.borrowed, 3);
});
});
describe('isFull', () => {
it('should indicate if the pool is full', () => {
sessionPool.options.max = 1;
assert.strictEqual(sessionPool.isFull, false);
inventory.borrowed = new Set([createSession()]);
assert.strictEqual(sessionPool.isFull, true);
});
});
describe('size', () => {
it('should return the size of the pool', () => {
inventory.sessions = [createSession(), createSession(), createSession()];
inventory.borrowed = new Set([createSession()]);
assert.strictEqual(sessionPool.size, 4);
});
});
describe('writes', () => {
beforeEach(() => {
inventory.sessions = [createSession(), createSession(), createSession()];
});
it('should get the total number of read/write sessions', () => {
assert.strictEqual(sessionPool.size, 3);
});
it('should factor in borrowed sessions', () => {
const session = createSession('id', {});
inventory.borrowed.add(session);
assert.strictEqual(sessionPool.size, 4);
assert.strictEqual(sessionPool.available, 3);
assert.strictEqual(sessionPool.borrowed, 1);
});
});
describe('instantiation', () => {
it('should localize the database instance', () => {
assert.strictEqual(sessionPool.database, DATABASE);
});
describe('options', () => {
it('should apply defaults', () => {
assert.strictEqual(sessionPool.options.acquireTimeout, Infinity);
assert.strictEqual(sessionPool.options.concurrency, Infinity);
assert.strictEqual(sessionPool.options.fail, false);
assert.strictEqual(sessionPool.options.idlesAfter, 10);
assert.strictEqual(sessionPool.options.keepAlive, 30);
assert.deepStrictEqual(sessionPool.options.labels, {});
assert.strictEqual(sessionPool.options.min, 25);
assert.strictEqual(sessionPool.options.max, 100);
assert.strictEqual(sessionPool.options.maxIdle, 1);
});
it('should not override user options', () => {
sessionPool = new SessionPool(DATABASE, {acquireTimeout: 0});
assert.strictEqual(sessionPool.options.acquireTimeout, 0);
});
it('should override user options for databaseRole', () => {
sessionPool = new SessionPool(DATABASE, {databaseRole: 'child_role'});
assert.strictEqual(sessionPool.options.databaseRole, 'child_role');
});
it('should use default value of Database for databaseRole', () => {
sessionPool = new SessionPool(DATABASE);
assert.strictEqual(sessionPool.options.databaseRole, 'parent_role');
});
describe('min and max', () => {
const minGtMax = /Min sessions may not be greater than max sessions\./;
it('should not accept min>max', () => {
assert.throws(() => {
return new SessionPool(DATABASE, {min: 20, max: 10});
}, minGtMax);
});
});
});
it('should set isOpen to false', () => {
assert.strictEqual(sessionPool.isOpen, false);
});
it('should create an inventory object', () => {
assert.deepStrictEqual(inventory, {
sessions: [],
borrowed: new Set(),
});
});
it('should create a request queue', () => {
const poolOptions = {
concurrency: 11,
};
pQueueOverride = class {
constructor(options) {
return options;
}
} as typeof PQueue;
sessionPool = new SessionPool(DATABASE, poolOptions);
assert.deepStrictEqual(sessionPool._requests, {
concurrency: poolOptions.concurrency,
});
});
it('should create an acquire queue', () => {
pQueueOverride = class {
constructor(options) {
return options;
}
} as typeof PQueue;
sessionPool = new SessionPool(DATABASE);
assert.deepStrictEqual(sessionPool._acquires, {
concurrency: 1,
});
});
it('should create a map of traces', () => {
assert.deepStrictEqual(sessionPool._traces, new Map());
});
it('should inherit from EventEmitter', () => {
assert(sessionPool instanceof events.EventEmitter);
});
});
describe('close', () => {
beforeEach(() => {
inventory.sessions = [createSession(), createSession(), createSession()];
inventory.borrowed = new Set([createSession(), createSession()]);
sessionPool._destroy = sandbox.stub().resolves();
});
it('should clear the inventory', done => {
sessionPool.close(() => {
assert.strictEqual(sessionPool.size, 0);
done();
});
});
it('should stop housekeeping', done => {
sessionPool._stopHouseKeeping = done;
sessionPool.close(noop);
});
it('should set isOpen to false', () => {
sessionPool.isOpen = true;
sessionPool.close(noop);
assert.strictEqual(sessionPool.isOpen, false);
});
it('should emit the close event', done => {
sessionPool.on('close', done);
sessionPool.close(noop);
});
it('should destroy all the sessions', done => {
const sessions = [...inventory.sessions, ...inventory.borrowed];
let destroyed = 0;
sessionPool._destroy = async session => {
assert.strictEqual(session, sessions[destroyed++]);
};
sessionPool.close(err => {
assert.ifError(err);
assert.strictEqual(destroyed, sessions.length);
done();
});
});
it('should execute the callback on idle', done => {
const stub = sandbox.stub(sessionPool._requests, 'onIdle').resolves();
sessionPool.close(err => {
assert.ifError(err);
assert.strictEqual(stub.callCount, 1);
done();
});
});
it('should return a leak error', done => {
const fakeLeaks = ['a', 'b'];
sandbox.stub(sessionPool, '_getLeaks').returns(fakeLeaks);
sessionPool.close((err?: sp.SessionLeakError) => {
assert.strictEqual(err!.name, 'SessionLeakError');
assert.strictEqual(
err!.message,
`${fakeLeaks.length} session leak(s) detected.`
);
assert.strictEqual(err!.messages, fakeLeaks);
done();
});
});
});
describe('getSession', () => {
it('should acquire a session', done => {
const fakeSession = createSession();
sandbox.stub(sessionPool, '_acquire').resolves(fakeSession);
sessionPool.getSession((err, session) => {
assert.ifError(err);
assert.strictEqual(session, fakeSession);
done();
});
});
it('should pass any errors to the callback', done => {
const error = new Error('err');
sandbox.stub(sessionPool, '_acquire').rejects(error);
sessionPool.getSession(err => {
assert.strictEqual(err, error);
done();
});
});
it('should pass back the session and txn', done => {
const fakeTxn = new FakeTransaction() as unknown as Transaction;
const fakeSession = createSession();
fakeSession.txn = fakeTxn;
sandbox.stub(sessionPool, '_acquire').resolves(fakeSession);
sessionPool.getSession((err, session, txn) => {
assert.ifError(err);
assert.strictEqual(session, fakeSession);
assert.strictEqual(txn, fakeTxn);
done();
});
});
});
describe('open', () => {
let fillStub: sinon.SinonStub<[], Promise<void>>;
beforeEach(() => {
sessionPool._stopHouseKeeping = sandbox.stub();
fillStub = sandbox.stub(sessionPool, '_fill').resolves();
});
it('should create an onclose promise', () => {
sessionPool.open();
assert(sessionPool._onClose instanceof Promise);
setImmediate(() => sessionPool.emit('close'));
return sessionPool._onClose;
});
it('should start housekeeping', done => {
sessionPool._startHouseKeeping = done;
sessionPool.open();
});
it('should set isOpen to true', () => {
sessionPool.open();
assert.strictEqual(sessionPool.isOpen, true);
});
it('should emit the open event', done => {
sessionPool.on('open', done);
sessionPool.open();
});
it('should fill the pool', () => {
sessionPool.open();
assert.strictEqual(fillStub.callCount, 1);
});
it('should not trigger unhandled promise rejection', () => {
const error = {
code: grpc.status.PERMISSION_DENIED,
message: 'spanner.sessions.create',
} as grpc.ServiceError;
sandbox.restore();
sandbox.stub(sessionPool, '_fill').rejects(error);
const originalRejection = process.listeners('unhandledRejection').pop();
if (originalRejection) {
process.removeListener('unhandledRejection', originalRejection!);
}
process.once('unhandledRejection', err => {
assert.ifError(err);
});
sessionPool.open();
if (originalRejection) {
process.listeners('unhandledRejection').push(originalRejection!);
}
});
it('should not trigger unhandled promise rejection when default credentials not set', () => {
const error = {
message: 'Could not load the default credentials',
} as grpc.ServiceError;
sandbox.restore();
sandbox.stub(sessionPool, '_fill').rejects(error);
const originalRejection = process.listeners('unhandledRejection').pop();
if (originalRejection) {
process.removeListener('unhandledRejection', originalRejection!);
}
process.once('unhandledRejection', err => {
assert.ifError(err);
});
sessionPool.open();
if (originalRejection) {
process.listeners('unhandledRejection').push(originalRejection!);
}
});
it('should not trigger unhandled promise rejection when projectId not set', () => {
const error = {
message: 'Unable to detect a Project Id in the current environment',
} as grpc.ServiceError;
sandbox.restore();
sandbox.stub(sessionPool, '_fill').rejects(error);
const originalRejection = process.listeners('unhandledRejection').pop();
if (originalRejection) {
process.removeListener('unhandledRejection', originalRejection!);
}
process.once('unhandledRejection', err => {
assert.ifError(err);
});
sessionPool.open();
if (originalRejection) {
process.listeners('unhandledRejection').push(originalRejection!);
}
});
});
describe('release', () => {
let prepStub: sinon.SinonStub<[Session], void>;
beforeEach(() => {
prepStub = sandbox.stub(sessionPool, '_prepareTransaction').resolves();
});
it('should throw an error when returning unknown resources', () => {
const badResource = createSession();
try {
sessionPool.release(badResource);
shouldNotBeCalled();
} catch (e) {
assert.strictEqual(
(e as sp.ReleaseError).message,
'Unable to release unknown resource.'
);
assert.strictEqual((e as sp.ReleaseError).resource, badResource);
}
});
it('should delete any old transactions', () => {
const session = createSession();
sessionPool._release = noop;
inventory.borrowed.add(session);
session.txn = {} as Transaction;
sessionPool.release(session);
assert.strictEqual(session.txn, undefined);
});
it('should update the lastUsed timestamp', () => {
const session = createSession();
sessionPool._release = noop;
inventory.borrowed.add(session);
session.lastUsed = null!;
sessionPool.release(session);
assert(isAround(session.lastUsed, Date.now()));
});
describe('read and write', () => {
let fakeSession;
beforeEach(() => {
fakeSession = createSession('id');
inventory.borrowed.add(fakeSession);
});
it('should release the read/write session', done => {
prepStub.resolves();
sandbox
.stub(sessionPool, '_release')
.withArgs(fakeSession)
.callsFake(() => done());
sessionPool.release(fakeSession);
});
});
});
describe('_acquire', () => {
beforeEach(() => {
sessionPool.isOpen = true;
sessionPool._isValidSession = () => true;
});
it('should return a closed error if not open', async () => {
sessionPool.isOpen = false;
try {
await sessionPool._acquire();
shouldNotBeCalled();
} catch (e) {
assert.strictEqual(
(e as sp.ReleaseError).message,
'Database is closed.'
);
}
});
it('should return a timeout error if a timeout happens', async () => {
sessionPool.options.acquireTimeout = 1;
sessionPool._acquires.add = fn => {
return new Promise(r => setTimeout(r, 3)).then(fn);
};
try {
await sessionPool._acquire();
shouldNotBeCalled();
} catch (e) {
assert.strictEqual(
(e as sp.ReleaseError).message,
'Timeout occurred while acquiring session.'
);
}
});
it('should return a session', async () => {
const fakeSession = createSession();
const now = Date.now();
const stub = sandbox
.stub(sessionPool, '_getSession')
.resolves(fakeSession);
const session = await sessionPool._acquire();
const [startTime] = stub.getCall(0).args;
assert(isAround(startTime, now));
assert.strictEqual(session, fakeSession);
});
it('should drop expired sessions', async () => {
const badSession = createSession();
const goodSession = createSession();
sessionPool._isValidSession = session => session === goodSession;
inventory.borrowed.add(badSession);
inventory.borrowed.add(goodSession);
const stub = sandbox.stub(sessionPool, '_getSession');
stub.onFirstCall().resolves(badSession);
stub.onSecondCall().resolves(goodSession);
const session = await sessionPool._acquire();
assert.strictEqual(session, goodSession);
assert.strictEqual(sessionPool.size, 1);
});
it('should capture the stack trace', async () => {
const id = 'abc';
const fakeSession = createSession();
const fakeTrace = [];
fakeSession.id = id;
sandbox.stub(sessionPool, '_getSession').resolves(fakeSession);
sandbox.stub(fakeStackTrace, 'get').returns(fakeTrace);
await sessionPool._acquire();
const trace = sessionPool._traces.get(id);
assert.strictEqual(trace, fakeTrace);
});
it('should convert read sessions to write sessions', async () => {
const fakeSession = createSession('id');
sandbox.stub(sessionPool, '_getSession').resolves(fakeSession);
const prepStub = sandbox
.stub(sessionPool, '_prepareTransaction')
.withArgs(fakeSession);
const session = await sessionPool._acquire();
assert.strictEqual(session, fakeSession);
assert.strictEqual(prepStub.callCount, 1);
});
});
describe('_borrow', () => {
it('should mark the session as borrowed', () => {
const fakeSession = createSession();
inventory.sessions.push(fakeSession);
sessionPool._borrow(fakeSession);
assert.strictEqual(inventory.sessions.indexOf(fakeSession), -1);
assert(inventory.borrowed.has(fakeSession));
});
});
describe('_borrowFrom', () => {
it('should borrow the last pushed session', () => {
const fakeSession1 = createSession();
const fakeSession2 = createSession();
inventory.sessions.push(fakeSession1);
inventory.sessions.push(fakeSession2);
let session = sessionPool._borrowFrom();
assert.strictEqual(session, fakeSession2);
session = sessionPool._borrowFrom();
assert.strictEqual(session, fakeSession1);
});
});
describe('_borrowNextAvailableSession', () => {
it('should borrow when available', () => {
const fakeSession = createSession();
inventory.sessions.push(fakeSession);
sandbox.stub(sessionPool, '_borrowFrom').returns(fakeSession);
const session = sessionPool._borrowNextAvailableSession();
assert.strictEqual(session, fakeSession);
});
});
describe('_createSession', () => {
let stub: sinon.SinonStub<[number], Promise<void>>;
beforeEach(() => {
stub = sandbox.stub(sessionPool, '_createSessions').resolves();
});
it('should create a single session', () => {
sessionPool._createSession();
const [numbers] = stub.lastCall.args;
assert.deepStrictEqual(numbers, 1);
});
});
describe('_createSessions', () => {
const OPTIONS = 3;
const RESPONSE = [[{}, {}, {}]];
let stub;
let releaseStub;
beforeEach(() => {
stub = sandbox.stub(DATABASE, 'batchCreateSessions').resolves(RESPONSE);
releaseStub = sandbox.stub(sessionPool, 'release');
});
it('should update the number of pending sessions', async () => {
await sessionPool._createSessions(OPTIONS);
assert.strictEqual(sessionPool.size, 3);
});
it('should create the appropriate number of sessions', async () => {
await sessionPool._createSessions(OPTIONS);
const [options] = stub.lastCall.args;
assert.strictEqual(options.count, 3);
});
it('should pass the session labels', async () => {
const labels = {foo: 'bar'};
sessionPool.options.labels = labels;
await sessionPool._createSessions(OPTIONS);
const [options] = stub.lastCall.args;
assert.strictEqual(options.labels, labels);
});
it('should pass the session database role', async () => {
const databaseRole = 'child_role';
sessionPool.options.databaseRole = databaseRole;
await sessionPool._createSessions(OPTIONS);
const [options] = stub.lastCall.args;
assert.strictEqual(options.databaseRole, databaseRole);
});
it('should make multiple requests if needed', async () => {
stub.onCall(0).resolves([[{}, {}]]);
stub.onCall(1).resolves([[{}]]);
await sessionPool._createSessions(OPTIONS);
assert.strictEqual(stub.callCount, 2);
assert.strictEqual(sessionPool.size, 3);
});
it('should reject with any request errors', async () => {
const error = new Error('err');
stub.rejects(error);
try {
await sessionPool._createSessions(OPTIONS);
throw new Error('Should not make it this far.');
} catch (e) {
assert.strictEqual(e, error);
}
});
it('should add each session to the inventory', async () => {
await sessionPool._createSessions(OPTIONS);
assert.strictEqual(sessionPool.borrowed, 3);
setImmediate(() => {
RESPONSE[0].forEach((fakeSession, i) => {
const [session] = releaseStub.getCall(i).args;
assert.strictEqual(session, fakeSession);
});
});
});
it('should prepare the correct number of write sessions', async () => {
await sessionPool._createSessions(OPTIONS);
setImmediate(() => {
assert.strictEqual(sessionPool.size, OPTIONS);
});
});
});
describe('_destroy', () => {
it('should delete the session', async () => {
const fakeSession = createSession();
const stub = fakeSession.delete as sinon.SinonStub;
await sessionPool._destroy(fakeSession);
assert.strictEqual(stub.callCount, 1);
});
it('should emit any errors', done => {
const error = new Error('err');
const fakeSession = createSession();
const stub = fakeSession.delete as sinon.SinonStub;
stub.rejects(error);
sessionPool.on('error', err => {
assert.strictEqual(err, error);
done();
});
sessionPool._destroy(fakeSession);
});
});
describe('_evictIdleSessions', () => {
let destroyStub: sinon.SinonStub<[Session], Promise<void>>;
let fakeSessions;
beforeEach(() => {
inventory.sessions = [
createSession('id'),
createSession('id'),
createSession('id'),
];
sessionPool.options.maxIdle = 0;
sessionPool.options.min = 0;
fakeSessions = [...inventory.sessions];
sandbox
.stub(sessionPool, '_getIdleSessions')
.returns(fakeSessions.slice());
fakeSessions.reverse();
destroyStub = sandbox.stub(sessionPool, '_destroy').resolves();
});
it('should evict the sessions', () => {
sessionPool._evictIdleSessions();
assert.strictEqual(destroyStub.callCount, fakeSessions.length);
fakeSessions.forEach((session, i) => {
const destroyed = destroyStub.getCall(i).args[0];
assert.strictEqual(destroyed, session);
});
});
it('should respect the maxIdle option', () => {
sessionPool.options.maxIdle = 2;
sessionPool._evictIdleSessions();
assert.strictEqual(destroyStub.callCount, 1);
const destroyed = destroyStub.getCall(0).args[0];
assert.strictEqual(destroyed, fakeSessions[0]);
});
it('should respect the min value', () => {
sessionPool.options.min = 1;
sessionPool._evictIdleSessions();
assert.strictEqual(destroyStub.callCount, 2);
fakeSessions.slice(0, 2).forEach((session, i) => {
const destroyed = destroyStub.getCall(i).args[0];
assert.strictEqual(destroyed, session);
});
});
it('should not evict if the session is not there', () => {
sandbox.restore();
fakeSessions[1] = undefined;
sandbox
.stub(sessionPool, '_getIdleSessions')
.returns(fakeSessions.slice());
destroyStub = sandbox.stub(sessionPool, '_destroy').resolves();
sessionPool._evictIdleSessions();
assert.strictEqual(destroyStub.callCount, fakeSessions.length - 1);
});
});
describe('_fill', () => {
let stub: sinon.SinonStub<[number], Promise<void>>;
beforeEach(() => {
stub = sandbox.stub(sessionPool, '_createSessions');
sessionPool.options.min = 8;
});
it('should create the min number of required sessions', () => {
sessionPool._fill();
const amount = stub.lastCall.args[0];
assert.strictEqual(amount, 8);
});
it('should respect the current size of the pool', () => {
inventory.sessions = [createSession(), createSession(), createSession()];
sessionPool._fill();
const amount = stub.lastCall.args[0];
assert.strictEqual(amount, 5);
});
it('should noop when no sessions are needed', () => {
sessionPool.options.min = 0;
sessionPool._fill();
assert.strictEqual(stub.callCount, 0);
});
it('should emit any request errors that occur', done => {
const error = new Error('err');
stub.rejects(error);
sessionPool.once('error', err => {
assert.strictEqual(err, error);
done();
});
sessionPool._fill();
});
});
describe('_getIdleSessions', () => {
it('should return a list of idle sessions', () => {
const idlesAfter = (sessionPool.options.idlesAfter = 1); // 1 minute
const idleTimestamp = Date.now() - idlesAfter * 60000;
const fake = (inventory.sessions = [
{lastUsed: Date.now()},
{lastUsed: idleTimestamp},
{lastUsed: idleTimestamp},
]);
const expectedSessions = [fake[1], fake[2]];
const idleSessions = sessionPool._getIdleSessions();
assert.deepStrictEqual(idleSessions, expectedSessions);
});
});
describe('_getLeaks', () => {
it('should return an array of leaks', () => {
const trace1 = [createStackFrame()];
const trace2 = [createStackFrame(), createStackFrame()];
const formatted1 = 'c';
const formatted2 = 'd';
const stub = sandbox.stub(SessionPool, 'formatTrace');
stub.withArgs(trace1).returns(formatted1);
stub.withArgs(trace2).returns(formatted2);
sessionPool._traces.set('a', trace1);
sessionPool._traces.set('b', trace2);
const leaks = sessionPool._getLeaks();
assert.deepStrictEqual(leaks, [formatted1, formatted2]);