-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathspanner.ts
1187 lines (1122 loc) · 36.5 KB
/
spanner.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 2020 Google LLC. 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 * as grpc from 'grpc';
import {status} from 'grpc';
import {Database, Instance, SessionPool, Snapshot, Spanner} from '../src';
import * as mock from './mockserver/mockspanner';
import {MockError, SimulatedExecutionTime} from './mockserver/mockspanner';
import * as mockInstanceAdmin from './mockserver/mockinstanceadmin';
import {TEST_INSTANCE_NAME} from './mockserver/mockinstanceadmin';
import * as mockDatabaseAdmin from './mockserver/mockdatabaseadmin';
import * as sinon from 'sinon';
import {google} from '../protos/protos';
import {types} from '../src/session';
import {ExecuteSqlRequest} from '../src/transaction';
import {PartialResultStream, Row} from '../src/partial-result-stream';
import {
SessionLeakError,
SessionPoolExhaustedError,
SessionPoolOptions,
} from '../src/session-pool';
import CreateInstanceMetadata = google.spanner.admin.instance.v1.CreateInstanceMetadata;
function numberToEnglishWord(num: number): string {
switch (num) {
case 1:
return 'One';
case 2:
return 'Two';
case 3:
return 'Three';
default:
throw new Error(`Unknown or unsupported number: ${num}`);
}
}
describe('Spanner with mock server', () => {
let sandbox: sinon.SinonSandbox;
const selectSql = 'SELECT NUM, NAME FROM NUMBERS';
const invalidSql = 'SELECT * FROM FOO';
const insertSql = `INSERT INTO NUMBER (NUM, NAME) VALUES (4, 'Four')`;
const fooNotFoundErr = Object.assign(new Error('Table FOO not found'), {
code: grpc.status.NOT_FOUND,
});
const server = new grpc.Server();
const spannerMock = mock.createMockSpanner(server);
mockInstanceAdmin.createMockInstanceAdmin(server);
mockDatabaseAdmin.createMockDatabaseAdmin(server);
let spanner: Spanner;
let instance: Instance;
let dbCounter = 1;
function newTestDatabase(options?: SessionPoolOptions): Database {
return instance.database(`database-${dbCounter++}`, options);
}
before(() => {
sandbox = sinon.createSandbox();
const port = server.bind(
'0.0.0.0:0',
grpc.ServerCredentials.createInsecure()
);
server.start();
spannerMock.putStatementResult(
selectSql,
mock.StatementResult.resultSet(mock.createSimpleResultSet())
);
spannerMock.putStatementResult(
invalidSql,
mock.StatementResult.error(fooNotFoundErr)
);
spannerMock.putStatementResult(
insertSql,
mock.StatementResult.updateCount(1)
);
// TODO(loite): Enable when SPANNER_EMULATOR_HOST is supported.
// Set environment variable for SPANNER_EMULATOR_HOST to the mock server.
// process.env.SPANNER_EMULATOR_HOST = `localhost:${port}`;
spanner = new Spanner({
projectId: 'fake-project-id',
servicePath: 'localhost',
port,
sslCreds: grpc.credentials.createInsecure(),
});
// Gets a reference to a Cloud Spanner instance and database
instance = spanner.instance('instance');
});
after(() => {
server.tryShutdown(() => {});
delete process.env.SPANNER_EMULATOR_HOST;
sandbox.restore();
});
describe('basics', () => {
it('should return different database instances when the same database is requested twice with different session pool options', async () => {
const dbWithDefaultOptions = newTestDatabase();
const dbWithWriteSessions = instance.database(dbWithDefaultOptions.id!, {
writes: 1.0,
});
assert.notStrictEqual(dbWithDefaultOptions, dbWithWriteSessions);
});
it('should execute query', async () => {
// The query to execute
const query = {
sql: selectSql,
};
const database = newTestDatabase();
try {
const [rows] = await database.run(query);
assert.strictEqual(rows.length, 3);
let i = 0;
rows.forEach(row => {
i++;
assert.strictEqual(row[0].name, 'NUM');
assert.strictEqual(row[0].value.valueOf(), i);
assert.strictEqual(row[1].name, 'NAME');
assert.strictEqual(row[1].value.valueOf(), numberToEnglishWord(i));
});
} finally {
await database.close();
}
});
it('should execute update', async () => {
const update = {
sql: insertSql,
};
const database = newTestDatabase();
try {
const updated = await executeSimpleUpdate(database, update);
assert.deepStrictEqual(updated, [1]);
} finally {
await database.close();
}
});
it('should execute queries in parallel', async () => {
// The query to execute
const query = {
sql: selectSql,
};
const database = newTestDatabase();
try {
const pool = database.pool_ as SessionPool;
const promises: Array<Promise<Row[]>> = [];
for (let i = 0; i < 10; i++) {
promises.push(database.run(query));
}
await Promise.all(promises);
assert.ok(
pool.size >= 1 && pool.size <= 10,
'Pool size should be between 1 and 10'
);
} finally {
await database.close();
}
});
it('should execute updates in parallel', async () => {
spannerMock.freeze();
const update = {
sql: insertSql,
};
const database = newTestDatabase();
try {
const pool = database.pool_ as SessionPool;
const promises: Array<Promise<number | number[]>> = [];
for (let i = 0; i < 10; i++) {
promises.push(executeSimpleUpdate(database, update));
}
spannerMock.unfreeze();
await Promise.all(promises);
assert.ok(
pool.size >= 1 && pool.size <= 10,
'Pool size should be between 1 and 10'
);
} finally {
await database.close();
}
});
it('should retry UNAVAILABLE from executeStreamingSql with a callback', done => {
const database = newTestDatabase();
const err = {
message: 'Temporary unavailable',
code: status.UNAVAILABLE,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
database.run(selectSql, (err, rows) => {
if (err) {
assert.fail(err);
} else {
assert.strictEqual(rows!.length, 3);
}
done();
});
});
it('should not retry non-retryable error from executeStreamingSql with a callback', done => {
const database = newTestDatabase();
const err = {
message: 'Non-retryable error',
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
database.run(selectSql, (err, _) => {
if (!err) {
assert.fail('Missing expected error');
} else {
assert.strictEqual(err.message, '2 UNKNOWN: Non-retryable error');
}
done();
});
});
it('should emit non-retryable error to runStream', done => {
const database = newTestDatabase();
const err = {
message: 'Test error',
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
const rows: Row[] = [];
const stream = database.runStream(selectSql);
stream
.on('error', err => {
assert.strictEqual(err.message, '2 UNKNOWN: Test error');
database.close();
done();
})
.on('data', row => {
rows.push(row);
})
.on('end', () => {
if (rows.length) {
assert.fail('Should not receive data');
}
assert.fail('Missing expected error');
done();
});
});
it('should retry UNAVAILABLE from executeStreamingSql', async () => {
const database = newTestDatabase();
const err = {
message: 'Temporary unavailable',
code: status.UNAVAILABLE,
details: 'Transient error',
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
try {
const [rows] = await database.run(selectSql);
assert.strictEqual(rows.length, 3);
} finally {
await database.close();
}
});
it('should not retry non-retryable errors from executeStreamingSql', async () => {
const database = newTestDatabase();
const err = {
message: 'Test error',
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
try {
await database.run(selectSql);
assert.fail('missing expected error');
} catch (e) {
assert.strictEqual(e.message, '2 UNKNOWN: Test error');
} finally {
await database.close();
}
});
describe('PartialResultStream', () => {
const streamIndexes = [1, 2];
streamIndexes.forEach(index => {
it('should retry UNAVAILABLE during streaming', async () => {
const database = newTestDatabase();
const err = {
message: 'Temporary unavailable',
code: status.UNAVAILABLE,
streamIndex: index,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
const [rows] = await database.run(selectSql);
assert.strictEqual(rows.length, 3);
});
it('should not retry non-retryable error during streaming', async () => {
const database = newTestDatabase();
const err = {
message: 'Test error',
streamIndex: index,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
try {
await database.run(selectSql);
assert.fail('missing expected error');
} catch (e) {
assert.strictEqual(e.message, '2 UNKNOWN: Test error');
}
});
it('should retry UNAVAILABLE during streaming with a callback', done => {
const database = newTestDatabase();
const err = {
message: 'Temporary unavailable',
code: status.UNAVAILABLE,
streamIndex: index,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
database.run(selectSql, (err, rows) => {
if (err) {
assert.fail(err);
} else {
assert.strictEqual(rows!.length, 3);
}
done();
});
});
it('should not retry non-retryable error during streaming with a callback', done => {
const database = newTestDatabase();
const err = {
message: 'Non-retryable error',
streamIndex: index,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
database.run(selectSql, (err, _) => {
if (!err) {
assert.fail('Missing expected error');
} else {
assert.strictEqual(err.message, '2 UNKNOWN: Non-retryable error');
}
done();
});
});
it('should emit non-retryable error during streaming to stream', done => {
const database = newTestDatabase();
const err = {
message: 'Non-retryable error',
streamIndex: index,
} as MockError;
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofError(err)
);
const receivedRows: Row[] = [];
database
.runStream(selectSql)
.on('error', err => {
assert.strictEqual(err.message, '2 UNKNOWN: Non-retryable error');
assert.strictEqual(receivedRows.length, index);
done();
})
.on('data', row => {
// We will receive data for the partial result sets that are
// returned before the error occurs.
receivedRows.push(row);
})
.on('end', () => {
assert.fail('Missing expected error');
done();
});
});
});
});
it('should retry UNAVAILABLE from executeStreamingSql with multiple errors during streaming', async () => {
const database = newTestDatabase();
const errors: MockError[] = [];
for (const index of [0, 1, 1, 2, 2]) {
errors.push({
message: 'Temporary unavailable',
code: status.UNAVAILABLE,
streamIndex: index,
} as MockError);
}
spannerMock.setExecutionTime(
spannerMock.executeStreamingSql,
SimulatedExecutionTime.ofErrors(errors)
);
const [rows] = await database.run(selectSql);
assert.strictEqual(rows.length, 3);
await database.close();
});
});
describe('session-pool', () => {
it('should execute table mutations without leaking sessions', async () => {
const database = newTestDatabase();
try {
await database.table('foo').upsert({id: 1, name: 'bar'});
} finally {
await database.close();
}
});
it('should throw an error with a stacktrace when leaking a session', async () => {
await testLeakSession();
});
async function testLeakSession() {
// The query to execute
const query = {
sql: selectSql,
};
const db = newTestDatabase();
let transaction: Snapshot;
await db
.getSnapshot({strong: true, returnReadTimestamp: true})
.then(([tx]) => {
transaction = tx;
return tx.run(query);
})
.then(([rows]) => {
// Assert that we get all results from the server.
assert.strictEqual(rows.length, 3);
// Note that we do not call transaction.end(). This will cause a session leak.
})
.catch(reason => {
assert.fail(reason);
});
await db
.close()
.then(() => {
assert.fail('Missing expected SessionLeakError');
})
.catch((reason: SessionLeakError) => {
assert.strictEqual(reason.name, 'SessionLeakError', reason);
assert.strictEqual(reason.messages.length, 1);
assert.ok(reason.messages[0].indexOf('testLeakSession') > -1);
});
}
it('should reuse sessions', async () => {
const database = newTestDatabase();
try {
await verifyReadSessionReuse(database);
} finally {
await database.close();
}
});
it('should reuse sessions when fail=true', async () => {
const db = newTestDatabase({
max: 10,
concurrency: 5,
writes: 0.1,
fail: true,
});
try {
await verifyReadSessionReuse(db);
} finally {
await db.close();
}
});
async function verifyReadSessionReuse(database: Database) {
// The query to execute
const query = {
sql: selectSql,
};
const pool = database.pool_ as SessionPool;
let sessionId = '';
for (let i = 0; i < 10; i++) {
const [rows] = await database.run(query);
assert.strictEqual(rows.length, 3);
rows.forEach(() => {});
assert.strictEqual(pool.size, 1);
if (i > 0) {
assert.strictEqual(pool._inventory[types.ReadOnly][0].id, sessionId);
}
sessionId = pool._inventory[types.ReadOnly][0].id;
}
}
it('should throw SessionPoolExhaustedError with stacktraces when pool is exhausted', async () => {
await testSessionPoolExhaustedError();
});
async function testSessionPoolExhaustedError() {
const database = newTestDatabase({
max: 1,
fail: true,
});
try {
const [tx1] = await database.getSnapshot();
try {
await database.getSnapshot();
assert.fail('missing expected exception');
} catch (e) {
assert.strictEqual(e.name, SessionPoolExhaustedError.name);
const exhausted = e as SessionPoolExhaustedError;
assert.ok(exhausted.messages);
assert.strictEqual(exhausted.messages.length, 1);
assert.ok(
exhausted.messages[0].indexOf('testSessionPoolExhaustedError') > -1
);
}
tx1.end();
} finally {
await database.close();
}
}
it('should reuse sessions after executing invalid sql', async () => {
// The query to execute
const query = {
sql: invalidSql,
};
const database = newTestDatabase();
try {
const pool = database.pool_ as SessionPool;
for (let i = 0; i < 10; i++) {
try {
const [rows] = await database.run(query);
assert.fail(`missing expected exception, got ${rows.length} rows`);
} catch (e) {
assert.strictEqual(
e.message,
`${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`
);
}
}
assert.strictEqual(pool.size, 1);
} finally {
await database.close();
}
});
it('should reuse sessions after executing streaming sql', async () => {
// The query to execute
const query = {
sql: selectSql,
};
const database = newTestDatabase();
try {
const pool = database.pool_ as SessionPool;
for (let i = 0; i < 10; i++) {
const rowCount = await getRowCountFromStreamingSql(database, query);
assert.strictEqual(rowCount, 3);
}
assert.strictEqual(pool.size, 1);
} finally {
await database.close();
}
});
it('should reuse sessions after executing an invalid streaming sql', async () => {
// The query to execute
const query = {
sql: invalidSql,
};
const database = newTestDatabase();
try {
const pool = database.pool_ as SessionPool;
for (let i = 0; i < 10; i++) {
try {
const rowCount = await getRowCountFromStreamingSql(database, query);
assert.fail(`missing expected exception, got ${rowCount}`);
} catch (e) {
assert.strictEqual(
e.message,
`${grpc.status.NOT_FOUND} NOT_FOUND: ${fooNotFoundErr.message}`
);
}
}
assert.strictEqual(pool.size, 1);
} finally {
await database.close();
}
});
it('should reuse write sessions', async () => {
const database = newTestDatabase();
try {
await verifyWriteSessionReuse(database);
} finally {
await database.close();
}
});
it('should reuse write sessions when fail=true', async () => {
const db = newTestDatabase({
max: 10,
concurrency: 5,
writes: 0.1,
fail: true,
});
try {
await verifyWriteSessionReuse(db);
} finally {
await db.close();
}
});
async function verifyWriteSessionReuse(database: Database) {
const update = {
sql: insertSql,
};
const pool = database.pool_ as SessionPool;
for (let i = 0; i < 10; i++) {
await executeSimpleUpdate(database, update);
// The pool should not contain more sessions than the number of transactions that we have executed.
// The exact number depends on the time needed to prepare new transactions, as checking in a read/write
// transaction to the pool will cause the session to be prepared with a read/write transaction before it is added
// to the list of available sessions.
assert.ok(pool.size <= i + 1);
}
}
it('should fail on session pool exhaustion and fail=true', async () => {
const database = newTestDatabase({
max: 1,
fail: true,
});
let tx1;
try {
try {
[tx1] = await database.getSnapshot();
await database.getSnapshot();
assert.fail('missing expected exception');
} catch (e) {
assert.strictEqual(e.message, 'No resources available.');
}
} finally {
if (tx1) {
tx1.end();
}
await database.close();
}
});
// tslint:disable-next-line:ban
it.skip('should not create unnecessary write-prepared sessions', async () => {
const query = {
sql: selectSql,
};
const update = {
sql: insertSql,
};
const database = newTestDatabase({
writes: 0.2,
min: 100,
});
const pool = database.pool_ as SessionPool;
try {
// First execute three consecutive read/write transactions.
const promises: Array<Promise<Row[] | number | [number]>> = [];
for (let i = 0; i < 3; i++) {
promises.push(executeSimpleUpdate(database, update));
const ms = Math.floor(Math.random() * 5) + 1;
await sleep(ms);
}
let maxWriteSessions = 0;
for (let i = 0; i < 1000; i++) {
if (Math.random() < 0.8) {
promises.push(database.run(query));
} else {
promises.push(executeSimpleUpdate(database, update));
}
maxWriteSessions = Math.max(maxWriteSessions, pool.writes);
const ms = Math.floor(Math.random() * 5) + 1;
await sleep(ms);
}
await Promise.all(promises);
console.log(`Session pool size: ${pool.size}`);
console.log(`Session pool read sessions: ${pool.reads}`);
console.log(`Session pool write sessions: ${pool.writes}`);
console.log(`Session pool max write sessions: ${maxWriteSessions}`);
} finally {
await database.close();
}
});
it('should pre-fill session pool', async () => {
const database = newTestDatabase({
writes: 0.2,
min: 100,
max: 200,
});
const pool = database.pool_ as SessionPool;
const expectedWrites = pool.options.min! * pool.options.writes!;
const expectedReads = pool.options.min! - expectedWrites;
assert.strictEqual(pool.size, expectedReads + expectedWrites);
// Wait until all sessions have been created and prepared.
const started = new Date().getTime();
while (
(pool.reads < expectedReads || pool.writes < expectedWrites) &&
new Date().getTime() - started < 1000
) {
await sleep(1);
}
assert.strictEqual(pool.reads, expectedReads);
assert.strictEqual(pool.writes, expectedWrites);
});
it('should use pre-filled session pool', async () => {
const database = newTestDatabase({
writes: 0.2,
min: 100,
max: 200,
});
const pool = database.pool_ as SessionPool;
const expectedWrites = pool.options.min! * pool.options.writes!;
const expectedReads = pool.options.min! - expectedWrites;
// Start executing a query. This query should use one of the sessions that
// has been pre-filled into the pool.
const [rows] = await database.run(selectSql);
assert.strictEqual(rows.length, 3);
// Wait until all sessions have been created and prepared.
const started = new Date().getTime();
while (
(pool.reads < expectedReads || pool.writes < expectedWrites) &&
new Date().getTime() - started < 1000
) {
await sleep(1);
}
assert.strictEqual(pool.reads, expectedReads);
assert.strictEqual(pool.writes, expectedWrites);
assert.strictEqual(pool.size, expectedReads + expectedWrites);
});
it('should create new session when numWaiters >= pending', async () => {
const database = newTestDatabase({
min: 1,
max: 10,
});
const pool = database.pool_ as SessionPool;
// Start executing a query. This query should use the one session that is
// being pre-filled into the pool.
const promise1 = database.run(selectSql);
// Start executing another query. This query should initiate the creation
// of a new session.
const promise2 = database.run(selectSql);
const rows = await Promise.all([promise1, promise2]);
assert.strictEqual(pool.size, 2);
assert.strictEqual(rows[0][0].length, 3);
assert.strictEqual(rows[1][0].length, 3);
});
it('should use pre-filled write sessions', async () => {
const database = newTestDatabase({
writes: 0.2,
min: 100,
max: 200,
});
const pool = database.pool_ as SessionPool;
const expectedWrites = pool.options.min! * pool.options.writes!;
const expectedReads = pool.options.min! - expectedWrites;
// Execute an update.
const [count] = await database.runTransactionAsync(
(transaction): Promise<[number]> => {
return transaction.runUpdate(insertSql).then(updateCount => {
transaction.commit();
return updateCount;
});
}
);
assert.strictEqual(count, 1);
// Wait until all sessions have been created and prepared.
const started = new Date().getTime();
while (
(pool.pending > 0 || pool.pendingPrepare > 0) &&
new Date().getTime() - started < 1000
) {
await sleep(1);
}
assert.strictEqual(pool.reads, expectedReads);
assert.strictEqual(pool.writes, expectedWrites);
assert.strictEqual(pool.size, expectedReads + expectedWrites);
});
});
describe('transaction', () => {
it('should retry on aborted query', async () => {
let aborted = false;
const database = newTestDatabase();
const rowCount = await database.runTransactionAsync(
(transaction): Promise<number> => {
if (!aborted) {
spannerMock.abortTransaction(transaction);
aborted = true;
}
return transaction.run(selectSql).then(([rows]) => {
let count = 0;
rows.forEach(() => count++);
return transaction.commit().then(_ => count);
});
}
);
assert.strictEqual(rowCount, 3);
assert.ok(aborted);
});
it('should retry on aborted query with callback', done => {
let aborted = false;
const database = newTestDatabase();
let rowCount = 0;
database.runTransaction((err, transaction) => {
if (err) {
assert.fail(err);
done(err);
return;
}
transaction!.run(selectSql, (err, rows) => {
if (err) {
assert.fail(err);
done(err);
return;
}
rows.forEach(() => rowCount++);
assert.strictEqual(rowCount, 3);
aborted = true;
assert.ok(aborted);
done();
});
});
});
it('should retry on aborted update statement', async () => {
let aborted = false;
let attempts = 0;
const database = newTestDatabase();
const [updated] = await database.runTransactionAsync(
(transaction): Promise<number[]> => {
attempts++;
if (!aborted) {
spannerMock.abortTransaction(transaction);
aborted = true;
}
return transaction
.runUpdate(insertSql)
.then(updateCount => transaction.commit().then(_ => updateCount));
}
);
assert.strictEqual(updated, 1);
assert.ok(aborted);
assert.strictEqual(attempts, 2);
});
it('should retry on aborted update statement with callback', done => {
let aborted = false;
let attempts = 0;
const database = newTestDatabase();
database.runTransaction((err, transaction) => {
attempts++;
assert.ifError(err);
if (!aborted) {
spannerMock.abortTransaction(transaction!);
aborted = true;
}
transaction!.runUpdate(insertSql, (err, rowCount) => {
assert.ifError(err);
transaction!.commit((err, _) => {
assert.ifError(err);
assert.strictEqual(rowCount, 1);
assert.ok(aborted);
assert.strictEqual(attempts, 2);
done();
});
});
});
});
it('should retry on aborted commit', async () => {
let aborted = false;
const database = newTestDatabase();
const [updated] = await database.runTransactionAsync(
(transaction): Promise<number[]> => {
return transaction.runUpdate(insertSql).then(updateCount => {
if (!aborted) {
spannerMock.abortTransaction(transaction);
aborted = true;
}
return transaction.commit().then(_ => updateCount);
});
}
);
assert.strictEqual(updated, 1);
assert.ok(aborted);
});
it('should throw DeadlineError', async () => {
let attempts = 0;
const database = newTestDatabase();
try {
await database.runTransactionAsync(
{timeout: 1},
(transaction): Promise<number[]> => {
attempts++;
return transaction.runUpdate(insertSql).then(updateCount => {
// Always abort the transaction.
spannerMock.abortTransaction(transaction);
return transaction.commit().then(_ => updateCount);
});
}
);
assert.fail('missing expected DEADLINE_EXCEEDED error');
} catch (e) {
assert.strictEqual(
e.code,
status.DEADLINE_EXCEEDED,
`Got unexpected error ${e} with code ${e.code}`
);
// The transaction should be tried at least once before timing out.
assert.ok(attempts >= 1);
}
});
});
describe('instanceAdmin', () => {
it('should list instance configurations', async () => {
const [configs] = await spanner.getInstanceConfigs();
assert.strictEqual(configs.length, 1);
});
it('should return all instance configs in a stream', done => {
let count = 0;
const stream = spanner.getInstanceConfigsStream();
stream
.on('error', err => {
assert.fail(err);
done(err);
})
.on('data', () => {
count++;
})
.on('end', () => {
assert.strictEqual(count, 1);
done();
});
});
it('should list all instances', async () => {
const [instances] = await spanner.getInstances();
assert.strictEqual(instances.length, 2);
});
it('should filter instances', async () => {
const [instances] = await spanner.getInstances({
filter: `name:${TEST_INSTANCE_NAME}`,
});
assert.strictEqual(instances.length, 1);
});
it('should cap results', async () => {
const [instances] = await spanner.getInstances({
maxResults: 1,
});
assert.strictEqual(instances.length, 1);
});
it('should maximize api calls', async () => {
const [instances] = await spanner.getInstances({