-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
5880 lines (5429 loc) · 196 KB
/
client_test.go
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 LLC
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.
*/
package spanner
import (
"context"
"fmt"
"io"
"math/big"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"cloud.google.com/go/civil"
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/GoogleCloudPlatform/grpc-gcp-go/grpcgcp"
"github.com/GoogleCloudPlatform/grpc-gcp-go/grpcgcp/grpc_gcp"
"github.com/GoogleCloudPlatform/grpc-gcp-go/grpcgcp/multiendpoint"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/googleapis/gax-go/v2"
itestutil "github.com/storj/exp-spanner/internal/testutil"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/status"
structpb "google.golang.org/protobuf/types/known/structpb"
vkit "github.com/storj/exp-spanner/apiv1"
. "github.com/storj/exp-spanner/internal/testutil"
)
var useGRPCgcp = strings.ToLower(os.Getenv("GCLOUD_TESTS_GOLANG_USE_GRPC_GCP")) == "true"
func setupMockedTestServer(t *testing.T) (server *MockedSpannerInMemTestServer, client *Client, teardown func()) {
return setupMockedTestServerWithConfig(t, ClientConfig{})
}
func setupMockedTestServerWithConfig(t *testing.T, config ClientConfig) (server *MockedSpannerInMemTestServer, client *Client, teardown func()) {
return setupMockedTestServerWithConfigAndClientOptions(t, config, []option.ClientOption{})
}
func setupMockedTestServerWithConfigAndClientOptions(t *testing.T, config ClientConfig, clientOptions []option.ClientOption) (server *MockedSpannerInMemTestServer, client *Client, teardown func()) {
return setupMockedTestServerWithConfigAndGCPMultiendpointPool(t, config, clientOptions, nil)
}
func setupMockedTestServerWithConfigAndGCPMultiendpointPool(t *testing.T, config ClientConfig, clientOptions []option.ClientOption, poolCfg *grpc_gcp.ChannelPoolConfig) (server *MockedSpannerInMemTestServer, client *Client, teardown func()) {
grpcHeaderChecker := &itestutil.HeadersEnforcer{
OnFailure: t.Fatalf,
Checkers: []*itestutil.HeaderChecker{
{
Key: "x-goog-api-client",
ValuesValidator: func(token ...string) error {
if len(token) != 1 {
return status.Errorf(codes.Internal, "unexpected number of api client token headers: %v", len(token))
}
if !strings.HasPrefix(token[0], "gl-go/") {
return status.Errorf(codes.Internal, "unexpected api client token: %v", token[0])
}
if !strings.Contains(token[0], "gccl/") {
return status.Errorf(codes.Internal, "unexpected api client token: %v", token[0])
}
return nil
},
},
},
}
if config.Compression == gzip.Name {
grpcHeaderChecker.Checkers = append(grpcHeaderChecker.Checkers, &itestutil.HeaderChecker{
Key: "x-response-encoding",
ValuesValidator: func(token ...string) error {
if len(token) != 1 {
return status.Errorf(codes.Internal, "unexpected number of compression headers: %v", len(token))
}
if token[0] != gzip.Name {
return status.Errorf(codes.Internal, "unexpected compression: %v", token[0])
}
return nil
},
})
}
clientOptions = append(clientOptions, grpcHeaderChecker.CallOptions()...)
server, opts, serverTeardown := NewMockedSpannerInMemTestServer(t)
opts = append(opts, clientOptions...)
ctx := context.Background()
formattedDatabase := fmt.Sprintf("projects/%s/instances/%s/databases/%s", "[PROJECT]", "[INSTANCE]", "[DATABASE]")
var err error
if useGRPCgcp {
gmeCfg := &grpcgcp.GCPMultiEndpointOptions{
GRPCgcpConfig: &grpc_gcp.ApiConfig{
ChannelPool: poolCfg,
},
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{server.ServerAddress},
},
},
Default: "default",
}
client, _, err = NewMultiEndpointClientWithConfig(ctx, formattedDatabase, config, gmeCfg, opts...)
} else {
client, err = NewClientWithConfig(ctx, formattedDatabase, config, opts...)
}
if err != nil {
t.Fatal(err)
}
return server, client, func() {
client.Close()
serverTeardown()
}
}
func makeClient(ctx context.Context, database string, target string, opts ...option.ClientOption) (*Client, error) {
if !useGRPCgcp {
return NewClient(ctx, database, opts...)
}
c, _, err := NewMultiEndpointClient(
ctx,
database,
&grpcgcp.GCPMultiEndpointOptions{
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{target},
},
},
Default: "default",
},
opts...,
)
return c, err
}
func makeClientWithConfig(ctx context.Context, database string, config ClientConfig, target string, opts ...option.ClientOption) (*Client, error) {
if !useGRPCgcp {
return NewClientWithConfig(ctx, database, config, opts...)
}
c, _, err := NewMultiEndpointClientWithConfig(
ctx,
database,
config,
&grpcgcp.GCPMultiEndpointOptions{
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{target},
},
},
Default: "default",
},
opts...,
)
return c, err
}
// Test validDatabaseName()
func TestValidDatabaseName(t *testing.T) {
validDbURI := "projects/spanner-cloud-test/instances/foo/databases/foodb"
invalidDbUris := []string{
// Completely wrong DB URI.
"foobarDB",
// Project ID contains "/".
"projects/spanner-cloud/test/instances/foo/databases/foodb",
// No instance ID.
"projects/spanner-cloud-test/instances//databases/foodb",
}
if err := validDatabaseName(validDbURI); err != nil {
t.Errorf("validateDatabaseName(%q) = %v, want nil", validDbURI, err)
}
for _, d := range invalidDbUris {
if err, wantErr := validDatabaseName(d), "should conform to pattern"; !strings.Contains(err.Error(), wantErr) {
t.Errorf("validateDatabaseName(%q) = %q, want error pattern %q", validDbURI, err, wantErr)
}
}
}
func TestReadOnlyTransactionClose(t *testing.T) {
// Closing a ReadOnlyTransaction shouldn't panic.
c := &Client{}
tx := c.ReadOnlyTransaction()
tx.Close()
}
func TestClient_MultiEndpoint(t *testing.T) {
if !useGRPCgcp {
t.Skip("gRPC-GCP only test")
}
t.Parallel()
server, opts, serverTeardown := NewMockedSpannerInMemTestServerWithAddr(t, "localhost:0")
defer serverTeardown()
mirrorAvailable := true
connCount := uint32(0)
makeMirror := func(enable *bool) string {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatal(err)
}
proxy := func(connA, connB net.Conn) {
buf := make([]byte, 1024)
for {
n, err := connA.Read(buf)
if !*enable || err == io.EOF {
connA.Close()
return
}
if err != nil {
t.Logf("error reading from conn: %v", err)
return
}
_, err = connB.Write(buf[:n])
if err != nil {
t.Logf("error writing to conn: %v", err)
return
}
}
}
handleConn := func(c net.Conn) {
if !*enable {
c.Close()
return
}
// Open connection to the mocked server.
conn, err := net.Dial("tcp", server.ServerAddress)
if err != nil {
t.Logf("cannot open connection: %v", err)
return
}
// Close connections when mirror is disabled.
go func() {
for *enable {
time.Sleep(time.Millisecond * 5)
}
c.Close()
conn.Close()
}()
go proxy(c, conn)
go proxy(conn, c)
atomic.AddUint32(&connCount, 1)
}
// Serve.
go func() {
for {
c, err := lis.Accept()
if err != nil {
t.Logf("cannot accept connection: %v", err)
return
}
go handleConn(c)
}
}()
return lis.Addr().String()
}
mirrorAddress := makeMirror(&mirrorAvailable)
stable := true
stableMirrorAddress := makeMirror(&stable)
// Configuring MultiEndpoint with two endpoints.
gmeCfg := &grpcgcp.GCPMultiEndpointOptions{
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{
mirrorAddress,
stableMirrorAddress,
},
},
},
Default: "default",
}
ctx := context.Background()
formattedDatabase := fmt.Sprintf("projects/%s/instances/%s/databases/%s", "[PROJECT]", "[INSTANCE]", "[DATABASE]")
client, gme, err := NewMultiEndpointClient(ctx, formattedDatabase, gmeCfg, opts...)
if err != nil {
t.Fatal(err)
}
defer client.Close()
// Let both endpoints connect.
for atomic.LoadUint32(&connCount) < numChannels*2 {
time.Sleep(time.Millisecond * 5)
}
// Works via mirror.
err = executeSingerQueryWithTimeout(ctx, client.Single(), time.Second)
if err != nil {
t.Fatal(err)
}
// Breaking the mirror.
mirrorAvailable = false
// Let some time to detect breakage.
time.Sleep(time.Millisecond * 20)
// Should work via stable mirror.
err = executeSingerQueryWithTimeout(ctx, client.Single(), time.Second)
if err != nil {
t.Fatal(err)
}
// Reversing the order of endpoints.
gmeCfg = &grpcgcp.GCPMultiEndpointOptions{
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{
stableMirrorAddress,
mirrorAddress,
},
},
},
Default: "default",
}
if err := gme.UpdateMultiEndpoints(gmeCfg); err != nil {
t.Fatal(err)
}
// Should work in reverse order.
err = executeSingerQueryWithTimeout(ctx, client.Single(), time.Second)
if err != nil {
t.Fatal(err)
}
// Moving the stable endpoint to a different MultiEndpoint.
gmeCfg = &grpcgcp.GCPMultiEndpointOptions{
MultiEndpoints: map[string]*multiendpoint.MultiEndpointOptions{
"default": {
Endpoints: []string{
mirrorAddress,
},
},
"stable": {
Endpoints: []string{
stableMirrorAddress,
},
},
},
Default: "default",
}
if err := gme.UpdateMultiEndpoints(gmeCfg); err != nil {
t.Fatal(err)
}
// Should fail as the mirror is the only endpoint and it is broken.
err = executeSingerQueryWithTimeout(ctx, client.Single(), time.Millisecond*100)
if err == nil {
t.Fatalf("deadline exceeded error expected, got: %v", err)
}
// Should work via stable MultiEndpoint.
stableCtx := grpcgcp.NewMEContext(ctx, "stable")
err = executeSingerQueryWithTimeout(stableCtx, client.Single(), time.Second)
if err != nil {
t.Fatal(err)
}
// Restoring the mirror.
mirrorAvailable = true
// Should work via the mirror again by default.
err = executeSingerQueryWithTimeout(ctx, client.Single(), time.Second*3)
if err != nil {
t.Fatal(err)
}
}
func TestClient_Single(t *testing.T) {
t.Parallel()
err := testSingleQuery(t, nil)
if err != nil {
t.Fatal(err)
}
}
func TestClient_Single_Unavailable(t *testing.T) {
t.Parallel()
err := testSingleQuery(t, status.Error(codes.Unavailable, "Temporary unavailable"))
if err != nil {
t.Fatal(err)
}
}
func TestClient_Single_InvalidArgument(t *testing.T) {
t.Parallel()
err := testSingleQuery(t, status.Error(codes.InvalidArgument, "Invalid argument"))
if status.Code(err) != codes.InvalidArgument {
t.Fatalf("got: %v, want: %v", err, codes.InvalidArgument)
}
}
func TestClient_Single_SessionNotFound(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.PutExecutionTime(
MethodExecuteStreamingSql,
SimulatedExecutionTime{Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")}},
)
ctx := context.Background()
iter := client.Single().Query(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums))
defer iter.Stop()
rowCount := int64(0)
for {
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatal(err)
}
rowCount++
}
if rowCount != SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount {
t.Fatalf("row count mismatch\nGot: %v\nWant: %v", rowCount, SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount)
}
}
func TestClient_Single_Read_SessionNotFound(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.PutExecutionTime(
MethodStreamingRead,
SimulatedExecutionTime{Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")}},
)
ctx := context.Background()
iter := client.Single().Read(ctx, "Albums", KeySets(Key{"foo"}), []string{"SingerId", "AlbumId", "AlbumTitle"})
defer iter.Stop()
rowCount := int64(0)
for {
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatal(err)
}
rowCount++
}
if rowCount != SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount {
t.Fatalf("row count mismatch\nGot: %v\nWant: %v", rowCount, SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount)
}
}
func TestClient_Single_WhenInactiveTransactionsAndSessionIsNotFoundOnBackend_RemoveSessionFromPool(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 1,
MaxOpened: 1,
InactiveTransactionRemovalOptions: InactiveTransactionRemovalOptions{
ActionOnInactiveTransaction: WarnAndClose,
},
},
})
defer teardown()
server.TestSpanner.PutExecutionTime(
MethodExecuteStreamingSql,
SimulatedExecutionTime{Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")}},
)
ctx := context.Background()
single := client.Single()
iter := single.Query(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums))
p := client.idleSessions
sh := single.sh
// simulate session to be last used before 60 mins
sh.mu.Lock()
sh.lastUseTime = time.Now().Add(-time.Hour)
sh.mu.Unlock()
// force run task to clean up unexpected long-running sessions
p.removeLongRunningSessions()
rowCount := int64(0)
for {
// Backend throws SessionNotFoundError. Session gets replaced with new session
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatal(err)
}
rowCount++
}
// New session returns back to pool
iter.Stop()
p.mu.Lock()
defer p.mu.Unlock()
if g, w := p.idleList.Len(), 1; g != w {
t.Fatalf("Idle Sessions in pool, count mismatch\nGot: %d\nWant: %d\n", g, w)
}
if g, w := p.numInUse, uint64(0); g != w {
t.Fatalf("Number of sessions currently in use mismatch\nGot: %d\nWant: %d\n", g, w)
}
if g, w := p.numOpened, uint64(1); g != w {
t.Fatalf("Session pool size mismatch\nGot: %d\nWant: %d\n", g, w)
}
sh.mu.Lock()
defer sh.mu.Unlock()
if g, w := sh.eligibleForLongRunning, false; g != w {
t.Fatalf("isLongRunningTransaction mismatch\nGot: %v\nWant: %v\n", g, w)
}
if g, w := p.numOfLeakedSessionsRemoved, uint64(1); g != w {
t.Fatalf("Number of leaked sessions removed mismatch\nGot: %d\nWant: %d\n", g, w)
}
}
func TestClient_Single_ReadRow_SessionNotFound(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.PutExecutionTime(
MethodStreamingRead,
SimulatedExecutionTime{Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")}},
)
ctx := context.Background()
row, err := client.Single().ReadRow(ctx, "Albums", Key{"foo"}, []string{"SingerId", "AlbumId", "AlbumTitle"})
if err != nil {
t.Fatalf("Unexpected error for read row: %v", err)
}
if row == nil {
t.Fatal("ReadRow did not return a row")
}
}
func TestClient_Single_RetryableErrorOnPartialResultSet(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
// Add two errors that will be returned by the mock server when the client
// is trying to fetch a partial result set. Both errors are retryable.
// The errors are not 'sticky' on the mocked server, i.e. once the error
// has been returned once, the next call for the same partial result set
// will succeed.
// When the client is fetching the partial result set with resume token 2,
// the mock server will respond with an internal error with the message
// 'stream terminated by RST_STREAM'. The client will retry the call to get
// this partial result set.
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "stream terminated by RST_STREAM"),
},
)
// When the client is fetching the partial result set with resume token 3,
// the mock server will respond with a 'Unavailable' error. The client will
// retry the call to get this partial result set.
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(3),
Err: status.Errorf(codes.Unavailable, "server is unavailable"),
},
)
ctx := context.Background()
if err := executeSingerQuery(ctx, client.Single()); err != nil {
t.Fatal(err)
}
}
func TestClient_Single_NonRetryableErrorOnPartialResultSet(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
// Add two errors that will be returned by the mock server when the client
// is trying to fetch a partial result set. The first error is retryable,
// the second is not.
// This error will automatically be retried.
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "stream terminated by RST_STREAM"),
},
)
// 'Session not found' is not retryable and the error will be returned to
// the user.
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(3),
Err: newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s"),
},
)
ctx := context.Background()
err := executeSingerQuery(ctx, client.Single())
if status.Code(err) != codes.NotFound {
t.Fatalf("Error mismatch:\ngot: %v\nwant: %v", err, codes.NotFound)
}
}
func TestClient_Single_NonRetryableInternalErrors(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "grpc: error while marshaling: string field contains invalid UTF-8"),
},
)
ctx := context.Background()
err := executeSingerQuery(ctx, client.Single())
if status.Code(err) != codes.Internal {
t.Fatalf("Error mismatch:\ngot: %v\nwant: %v", err, codes.Internal)
}
}
func TestClient_Single_DeadlineExceeded_NoErrors(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.PutExecutionTime(MethodExecuteStreamingSql,
SimulatedExecutionTime{
MinimumExecutionTime: 50 * time.Millisecond,
})
ctx := context.Background()
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(5*time.Millisecond))
defer cancel()
err := executeSingerQuery(ctx, client.Single())
if status.Code(err) != codes.DeadlineExceeded {
t.Fatalf("Error mismatch:\ngot: %v\nwant: %v", err, codes.DeadlineExceeded)
}
}
func TestClient_Single_DeadlineExceeded_WithErrors(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "stream terminated by RST_STREAM"),
},
)
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(3),
Err: status.Errorf(codes.Unavailable, "server is unavailable"),
ExecutionTime: 50 * time.Millisecond,
},
)
ctx := context.Background()
ctx, cancel := context.WithDeadline(ctx, time.Now().Add(25*time.Millisecond))
defer cancel()
err := executeSingerQuery(ctx, client.Single())
if status.Code(err) != codes.DeadlineExceeded {
t.Fatalf("got unexpected error %v, expected DeadlineExceeded", err)
}
}
func TestClient_Single_ContextCanceled_noDeclaredServerErrors(t *testing.T) {
t.Parallel()
_, client, teardown := setupMockedTestServer(t)
defer teardown()
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
cancel()
err := executeSingerQuery(ctx, client.Single())
if status.Code(err) != codes.Canceled {
t.Fatalf("got unexpected error %v, expected Canceled", err)
}
}
func TestClient_Single_ContextCanceled_withDeclaredServerErrors(t *testing.T) {
t.Parallel()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(2),
Err: status.Errorf(codes.Internal, "stream terminated by RST_STREAM"),
},
)
server.TestSpanner.AddPartialResultSetError(
SelectSingerIDAlbumIDAlbumTitleFromAlbums,
PartialResultSetExecutionTime{
ResumeToken: EncodeResumeToken(3),
Err: status.Errorf(codes.Unavailable, "server is unavailable"),
},
)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
f := func(rowCount int64) error {
if rowCount == 2 {
cancel()
}
return nil
}
iter := client.Single().Query(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums))
defer iter.Stop()
err := executeSingerQueryWithRowFunc(ctx, client.Single(), f)
if status.Code(err) != codes.Canceled {
t.Fatalf("got unexpected error %v, expected Canceled", err)
}
}
func TestClient_Single_QueryOptions(t *testing.T) {
for _, tt := range queryOptionsTestCases() {
t.Run(tt.name, func(t *testing.T) {
if tt.env.Options != nil {
unset := setQueryOptionsEnvVars(tt.env.Options)
defer unset()
}
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{QueryOptions: tt.client})
defer teardown()
var iter *RowIterator
if tt.query.Options == nil {
iter = client.Single().Query(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums))
} else {
iter = client.Single().QueryWithOptions(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums), tt.query)
}
testQueryOptions(t, iter, server.TestSpanner, tt.want)
})
}
}
func TestClient_Single_ReadOptions(t *testing.T) {
for _, tt := range readOptionsTestCases() {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{ReadOptions: *tt.client})
defer teardown()
var iter *RowIterator
if tt.read == nil {
iter = client.Single().Read(ctx, "Albums", KeySets(Key{"foo"}), []string{"SingerId", "AlbumId", "AlbumTitle"})
} else {
iter = client.Single().ReadWithOptions(ctx, "Albums", KeySets(Key{"foo"}), []string{"SingerId", "AlbumId", "AlbumTitle"}, tt.read)
}
testReadOptions(t, iter, server.TestSpanner, *tt.want)
})
}
}
func TestClient_ReturnDatabaseName(t *testing.T) {
t.Parallel()
_, client, teardown := setupMockedTestServer(t)
defer teardown()
got := client.DatabaseName()
want := "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]"
if got != want {
t.Fatalf("Incorrect database name returned, got: %s, want: %s", got, want)
}
}
func testQueryOptions(t *testing.T, iter *RowIterator, server InMemSpannerServer, qo QueryOptions) {
defer iter.Stop()
_, err := iter.Next()
if err != nil {
t.Fatalf("Failed to read from the iterator: %v", err)
}
checkReqsForQueryOptions(t, server, qo)
}
func checkReqsForQueryOptions(t *testing.T, server InMemSpannerServer, qo QueryOptions) {
reqs := drainRequestsFromServer(server)
sqlReqs := []*sppb.ExecuteSqlRequest{}
for _, req := range reqs {
if sqlReq, ok := req.(*sppb.ExecuteSqlRequest); ok {
sqlReqs = append(sqlReqs, sqlReq)
}
}
if got, want := len(sqlReqs), 1; got != want {
t.Fatalf("Length mismatch, got %v, want %v", got, want)
}
sqlReq := sqlReqs[0]
reqQueryOptions := sqlReq.QueryOptions
if got, want := reqQueryOptions.OptimizerVersion, qo.Options.OptimizerVersion; got != want {
t.Fatalf("Optimizer version mismatch, got %v, want %v", got, want)
}
if got, want := reqQueryOptions.OptimizerStatisticsPackage, qo.Options.OptimizerStatisticsPackage; got != want {
t.Fatalf("Optimizer statistics package mismatch, got %v, want %v", got, want)
}
if got, want := sqlReq.DirectedReadOptions, qo.DirectedReadOptions; got.String() != want.String() {
t.Fatalf("Directed Read Options mismatch, got %v, want %v", got, want)
}
}
func testReadOptions(t *testing.T, iter *RowIterator, server InMemSpannerServer, ro ReadOptions) {
defer iter.Stop()
_, err := iter.Next()
if err != nil {
t.Fatalf("Failed to read from the iterator: %v", err)
}
checkReqsForReadOptions(t, server, ro)
}
func checkReqsForReadOptions(t *testing.T, server InMemSpannerServer, ro ReadOptions) {
reqs := drainRequestsFromServer(server)
sqlReqs := []*sppb.ReadRequest{}
for _, req := range reqs {
if sqlReq, ok := req.(*sppb.ReadRequest); ok {
sqlReqs = append(sqlReqs, sqlReq)
}
}
if got, want := len(sqlReqs), 1; got != want {
t.Fatalf("Length mismatch, got %v, want %v", got, want)
}
sqlReq := sqlReqs[0]
if got, want := sqlReq.Index, ro.Index; got != want {
t.Fatalf("Index mismatch, got %v, want %v", got, want)
}
if got, want := sqlReq.Limit, ro.Limit; got != int64(want) {
t.Fatalf("Limit mismatch, got %v, want %v", got, want)
}
reqRequestOptions := sqlReq.RequestOptions
if got, want := reqRequestOptions.Priority, ro.Priority; got != want {
t.Fatalf("Priority mismatch, got %v, want %v", got, want)
}
if got, want := reqRequestOptions.RequestTag, ro.RequestTag; got != want {
t.Fatalf("Request tag mismatch, got %v, want %v", got, want)
}
if got, want := sqlReq.DirectedReadOptions, ro.DirectedReadOptions; got.String() != want.String() {
t.Fatalf("Directed Read Options mismatch, got %v, want %v", got, want)
}
}
func checkReqsForTransactionOptions(t *testing.T, server InMemSpannerServer, txo TransactionOptions) {
reqs := drainRequestsFromServer(server)
sqlReqs := []*sppb.CommitRequest{}
for _, req := range reqs {
if sqlReq, ok := req.(*sppb.CommitRequest); ok {
sqlReqs = append(sqlReqs, sqlReq)
}
}
if got, want := len(sqlReqs), 1; got != want {
t.Fatalf("Length mismatch, got %v, want %v", got, want)
}
sqlReq := sqlReqs[0]
if got, want := sqlReq.ReturnCommitStats, txo.CommitOptions.ReturnCommitStats; got != want {
t.Fatalf("Return commit stats mismatch, got %v, want %v", got, want)
}
reqRequestOptions := sqlReq.RequestOptions
if got, want := reqRequestOptions.Priority, txo.CommitPriority; got != want {
t.Fatalf("Commit priority mismatch, got %v, want %v", got, want)
}
if got, want := reqRequestOptions.TransactionTag, txo.TransactionTag; got != want {
t.Fatalf("Transaction tag mismatch, got %v, want %v", got, want)
}
}
func testSingleQuery(t *testing.T, serverError error) error {
ctx := context.Background()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
if serverError != nil {
server.TestSpanner.SetError(serverError)
}
return executeSingerQuery(ctx, client.Single())
}
func executeSingerQuery(ctx context.Context, tx *ReadOnlyTransaction) error {
return executeSingerQueryWithRowFunc(ctx, tx, nil)
}
func executeSingerQueryWithTimeout(ctx context.Context, tx *ReadOnlyTransaction, to time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, to)
defer cancel()
return executeSingerQueryWithRowFunc(ctx, tx, nil)
}
func executeSingerQueryWithRowFunc(ctx context.Context, tx *ReadOnlyTransaction, f func(rowCount int64) error) error {
iter := tx.Query(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums))
defer iter.Stop()
rowCount := int64(0)
for {
row, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return err
}
var singerID, albumID int64
var albumTitle string
if err := row.Columns(&singerID, &albumID, &albumTitle); err != nil {
return err
}
rowCount++
if f != nil {
if err := f(rowCount); err != nil {
return err
}
}
}
if rowCount != SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount {
return status.Errorf(codes.Internal, "Row count mismatch, got %v, expected %v", rowCount, SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount)
}
return nil
}
func createSimulatedExecutionTimeWithTwoUnavailableErrors(method string) map[string]SimulatedExecutionTime {
errors := make([]error, 2)
errors[0] = status.Error(codes.Unavailable, "Temporary unavailable")
errors[1] = status.Error(codes.Unavailable, "Temporary unavailable")
executionTimes := make(map[string]SimulatedExecutionTime)
executionTimes[method] = SimulatedExecutionTime{
Errors: errors,
}
return executionTimes
}
func TestClient_ReadOnlyTransaction(t *testing.T) {
t.Parallel()
if err := testReadOnlyTransaction(t, make(map[string]SimulatedExecutionTime)); err != nil {
t.Fatal(err)
}
}
func TestClient_ReadOnlyTransaction_UnavailableOnSessionCreate(t *testing.T) {
t.Parallel()
if err := testReadOnlyTransaction(t, createSimulatedExecutionTimeWithTwoUnavailableErrors(MethodCreateSession)); err != nil {
t.Fatal(err)
}
}
func TestClient_ReadOnlyTransaction_UnavailableOnBeginTransaction(t *testing.T) {
t.Parallel()
if err := testReadOnlyTransaction(t, createSimulatedExecutionTimeWithTwoUnavailableErrors(MethodBeginTransaction)); err != nil {
t.Fatal(err)
}
}
func TestClient_ReadOnlyTransaction_UnavailableOnExecuteStreamingSql(t *testing.T) {
t.Parallel()
if err := testReadOnlyTransaction(t, createSimulatedExecutionTimeWithTwoUnavailableErrors(MethodExecuteStreamingSql)); err != nil {
t.Fatal(err)
}
}
func TestClient_ReadOnlyTransaction_SessionNotFoundOnExecuteStreamingSql(t *testing.T) {
t.Parallel()
// Session not found is not retryable for a query on a multi-use read-only
// transaction, as we would need to start a new transaction on a new
// session.