-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
1898 lines (1760 loc) · 63.6 KB
/
transaction.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"
"sync"
"sync/atomic"
"time"
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/googleapis/gax-go/v2"
"github.com/storj/exp-spanner/internal/trace"
"google.golang.org/api/iterator"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
vkit "github.com/storj/exp-spanner/apiv1"
durationpb "google.golang.org/protobuf/types/known/durationpb"
)
// transactionID stores a transaction ID which uniquely identifies a transaction
// in Cloud Spanner.
type transactionID []byte
// txReadEnv manages a read-transaction environment consisting of a session
// handle and a transaction selector.
type txReadEnv interface {
// acquire returns a read-transaction environment that can be used to
// perform a transactional read.
acquire(ctx context.Context) (*sessionHandle, *sppb.TransactionSelector, error)
// getTransactionSelector returns the transaction selector based on state of the transaction it is in
getTransactionSelector() *sppb.TransactionSelector
// sets the transactionID
setTransactionID(id transactionID)
// sets the transaction's read timestamp
setTimestamp(time.Time)
// release should be called at the end of every transactional read to deal
// with session recycling.
release(error)
setSessionEligibilityForLongRunning(sh *sessionHandle)
}
// txReadOnly contains methods for doing transactional reads.
type txReadOnly struct {
// read-transaction environment for performing transactional read
// operations.
txReadEnv
// Atomic. Only needed for DML statements, but used forall.
sequenceNumber int64
// replaceSessionFunc is a function that can be called to replace the
// session that is used by the transaction. This function should only be
// defined for single-use transactions that can safely be retried on a
// different session. All other transactions will set this function to nil.
replaceSessionFunc func(ctx context.Context) error
// sp is the session pool for allocating a session to execute the read-only
// transaction. It is set only once during initialization of the
// txReadOnly.
sp *sessionPool
// sh is the sessionHandle allocated from sp.
sh *sessionHandle
// qo provides options for executing a sql query.
qo QueryOptions
// ro provides options for reading rows from a database.
ro ReadOptions
// txOpts provides options for a transaction.
txOpts TransactionOptions
// commonTags for opencensus metrics
ct *commonTags
// disableRouteToLeader specifies if all the requests of type read-write and PDML
// need to be routed to the leader region.
disableRouteToLeader bool
otConfig *openTelemetryConfig
}
// TransactionOptions provides options for a transaction.
type TransactionOptions struct {
CommitOptions CommitOptions
// The transaction tag to use for a read/write transaction.
// This tag is automatically included with each statement and the commit
// request of a read/write transaction.
TransactionTag string
// CommitPriority is the priority to use for the Commit RPC for the
// transaction.
CommitPriority sppb.RequestOptions_Priority
// the transaction lock mode is used to specify a concurrency mode for the
// read/query operations. It works for a read/write transaction only.
ReadLockMode sppb.TransactionOptions_ReadWrite_ReadLockMode
// Controls whether to exclude recording modifications in current transaction
// from the allowed tracking change streams(with DDL option allow_txn_exclusion=true).
ExcludeTxnFromChangeStreams bool
}
// merge combines two TransactionOptions that the input parameter will have higher
// order of precedence.
func (to TransactionOptions) merge(opts TransactionOptions) TransactionOptions {
merged := TransactionOptions{
CommitOptions: to.CommitOptions.merge(opts.CommitOptions),
TransactionTag: to.TransactionTag,
CommitPriority: to.CommitPriority,
ExcludeTxnFromChangeStreams: to.ExcludeTxnFromChangeStreams || opts.ExcludeTxnFromChangeStreams,
}
if opts.TransactionTag != "" {
merged.TransactionTag = opts.TransactionTag
}
if opts.CommitPriority != sppb.RequestOptions_PRIORITY_UNSPECIFIED {
merged.CommitPriority = opts.CommitPriority
}
if opts.ReadLockMode != sppb.TransactionOptions_ReadWrite_READ_LOCK_MODE_UNSPECIFIED {
merged.ReadLockMode = opts.ReadLockMode
}
return merged
}
// errSessionClosed returns error for using a recycled/destroyed session
func errSessionClosed(sh *sessionHandle) error {
return spannerErrorf(codes.FailedPrecondition,
"session is already recycled / destroyed: session_id = %q, rpc_client = %v", sh.getID(), sh.getClient())
}
// Read returns a RowIterator for reading multiple rows from the database.
func (t *txReadOnly) Read(ctx context.Context, table string, keys KeySet, columns []string) *RowIterator {
return t.ReadWithOptions(ctx, table, keys, columns, nil)
}
// ReadUsingIndex calls ReadWithOptions with ReadOptions{Index: index}.
func (t *txReadOnly) ReadUsingIndex(ctx context.Context, table, index string, keys KeySet, columns []string) (ri *RowIterator) {
return t.ReadWithOptions(ctx, table, keys, columns, &ReadOptions{Index: index})
}
// ReadOptions provides options for reading rows from a database.
type ReadOptions struct {
// The index to use for reading. If non-empty, you can only read columns
// that are part of the index key, part of the primary key, or stored in the
// index due to a STORING clause in the index definition.
Index string
// The maximum number of rows to read. A limit value less than 1 means no
// limit.
Limit int
// Priority is the RPC priority to use for the operation.
Priority sppb.RequestOptions_Priority
// The request tag to use for this request.
RequestTag string
// If this is for a partitioned read and DataBoostEnabled field is set to true, the request will be executed
// via Spanner independent compute resources. Setting this option for regular read operations has no effect.
DataBoostEnabled bool
// ReadOptions option used to set the DirectedReadOptions for all ReadRequests which indicate
// which replicas or regions should be used for running read operations.
DirectedReadOptions *sppb.DirectedReadOptions
}
// merge combines two ReadOptions that the input parameter will have higher
// order of precedence.
func (ro ReadOptions) merge(opts ReadOptions) ReadOptions {
merged := ReadOptions{
Index: ro.Index,
Limit: ro.Limit,
Priority: ro.Priority,
RequestTag: ro.RequestTag,
DataBoostEnabled: ro.DataBoostEnabled,
DirectedReadOptions: ro.DirectedReadOptions,
}
if opts.Index != "" {
merged.Index = opts.Index
}
if opts.Limit > 0 {
merged.Limit = opts.Limit
}
if opts.Priority != sppb.RequestOptions_PRIORITY_UNSPECIFIED {
merged.Priority = opts.Priority
}
if opts.RequestTag != "" {
merged.RequestTag = opts.RequestTag
}
if opts.DataBoostEnabled {
merged.DataBoostEnabled = opts.DataBoostEnabled
}
if opts.DirectedReadOptions != nil {
merged.DirectedReadOptions = opts.DirectedReadOptions
}
return merged
}
// ReadWithOptions returns a RowIterator for reading multiple rows from the
// database. Pass a ReadOptions to modify the read operation.
func (t *txReadOnly) ReadWithOptions(ctx context.Context, table string, keys KeySet, columns []string, opts *ReadOptions) (ri *RowIterator) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/spanner.Read")
defer func() { trace.EndSpan(ctx, ri.err) }()
var (
sh *sessionHandle
ts *sppb.TransactionSelector
err error
)
kset, err := keys.keySetProto()
if err != nil {
return &RowIterator{err: err}
}
if sh, ts, err = t.acquire(ctx); err != nil {
return &RowIterator{err: err}
}
// Cloud Spanner will return "Session not found" on bad sessions.
client := sh.getClient()
if client == nil {
// Might happen if transaction is closed in the middle of a API call.
return &RowIterator{err: errSessionClosed(sh)}
}
index := t.ro.Index
limit := t.ro.Limit
prio := t.ro.Priority
requestTag := t.ro.RequestTag
dataBoostEnabled := t.ro.DataBoostEnabled
directedReadOptions := t.ro.DirectedReadOptions
if opts != nil {
index = opts.Index
if opts.Limit > 0 {
limit = opts.Limit
}
prio = opts.Priority
requestTag = opts.RequestTag
if opts.DataBoostEnabled {
dataBoostEnabled = opts.DataBoostEnabled
}
if opts.DirectedReadOptions != nil {
directedReadOptions = opts.DirectedReadOptions
}
}
var setTransactionID func(transactionID)
if _, ok := ts.Selector.(*sppb.TransactionSelector_Begin); ok {
setTransactionID = t.setTransactionID
} else {
setTransactionID = nil
}
return streamWithReplaceSessionFunc(
contextWithOutgoingMetadata(ctx, sh.getMetadata(), t.disableRouteToLeader),
sh.session.logger,
func(ctx context.Context, resumeToken []byte) (streamingReceiver, error) {
if t.sh != nil {
t.sh.updateLastUseTime()
}
client, err := client.StreamingRead(ctx,
&sppb.ReadRequest{
Session: t.sh.getID(),
Transaction: t.getTransactionSelector(),
Table: table,
Index: index,
Columns: columns,
KeySet: kset,
ResumeToken: resumeToken,
Limit: int64(limit),
RequestOptions: createRequestOptions(prio, requestTag, t.txOpts.TransactionTag),
DataBoostEnabled: dataBoostEnabled,
DirectedReadOptions: directedReadOptions,
})
if err != nil {
if _, ok := t.getTransactionSelector().GetSelector().(*sppb.TransactionSelector_Begin); ok {
t.setTransactionID(nil)
return client, errInlineBeginTransactionFailed()
}
return client, err
}
md, err := client.Header()
if getGFELatencyMetricsFlag() && md != nil && t.ct != nil {
if err := createContextAndCaptureGFELatencyMetrics(ctx, t.ct, md, "ReadWithOptions"); err != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency. Try disabling and rerunning. Error: %v", err)
}
}
if metricErr := recordGFELatencyMetricsOT(ctx, md, "ReadWithOptions", t.otConfig); metricErr != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency through OpenTelemetry. Error: %v", metricErr)
}
return client, err
},
t.replaceSessionFunc,
setTransactionID,
t.setTimestamp,
t.release,
)
}
// errRowNotFound returns error for not being able to read the row identified by
// key.
func errRowNotFound(table string, key Key) error {
return spannerErrorf(codes.NotFound, "row not found(Table: %v, PrimaryKey: %v)", table, key)
}
// errRowNotFoundByIndex returns error for not being able to read the row by index.
func errRowNotFoundByIndex(table string, key Key, index string) error {
return spannerErrorf(codes.NotFound, "row not found(Table: %v, IndexKey: %v, Index: %v)", table, key, index)
}
// errMultipleRowsFound returns error for receiving more than one row when reading a single row using an index.
func errMultipleRowsFound(table string, key Key, index string) error {
return spannerErrorf(codes.FailedPrecondition, "more than one row found by index(Table: %v, IndexKey: %v, Index: %v)", table, key, index)
}
// errInlineBeginTransactionFailed returns error for read-write transaction to explicitly begin the transaction
func errInlineBeginTransactionFailed() error {
return spannerErrorf(codes.Internal, "failed inline begin transaction")
}
// ReadRow reads a single row from the database.
//
// If no row is present with the given key, then ReadRow returns an error where
// spanner.ErrCode(err) is codes.NotFound.
func (t *txReadOnly) ReadRow(ctx context.Context, table string, key Key, columns []string) (*Row, error) {
return t.ReadRowWithOptions(ctx, table, key, columns, nil)
}
// ReadRowWithOptions reads a single row from the database. Pass a ReadOptions to modify the read operation.
//
// If no row is present with the given key, then ReadRowWithOptions returns an error where
// spanner.ErrCode(err) is codes.NotFound.
func (t *txReadOnly) ReadRowWithOptions(ctx context.Context, table string, key Key, columns []string, opts *ReadOptions) (*Row, error) {
iter := t.ReadWithOptions(ctx, table, key, columns, opts)
defer iter.Stop()
row, err := iter.Next()
switch err {
case iterator.Done:
return nil, errRowNotFound(table, key)
case nil:
return row, nil
default:
return nil, err
}
}
// ReadRowUsingIndex reads a single row from the database using an index.
//
// If no row is present with the given index, then ReadRowUsingIndex returns an
// error where spanner.ErrCode(err) is codes.NotFound.
//
// If more than one row received with the given index, then ReadRowUsingIndex
// returns an error where spanner.ErrCode(err) is codes.FailedPrecondition.
func (t *txReadOnly) ReadRowUsingIndex(ctx context.Context, table string, index string, key Key, columns []string) (*Row, error) {
iter := t.ReadUsingIndex(ctx, table, index, key, columns)
defer iter.Stop()
row, err := iter.Next()
switch err {
case iterator.Done:
return nil, errRowNotFoundByIndex(table, key, index)
case nil:
// If more than one row found, return an error.
_, err := iter.Next()
switch err {
case iterator.Done:
return row, nil
case nil:
return nil, errMultipleRowsFound(table, key, index)
default:
return nil, err
}
default:
return nil, err
}
}
// QueryOptions provides options for executing a sql query or update statement.
type QueryOptions struct {
Mode *sppb.ExecuteSqlRequest_QueryMode
Options *sppb.ExecuteSqlRequest_QueryOptions
// Priority is the RPC priority to use for the query/update.
Priority sppb.RequestOptions_Priority
// The request tag to use for this request.
RequestTag string
// If this is for a partitioned query and DataBoostEnabled field is set to true, the request will be executed
// via Spanner independent compute resources. Setting this option for regular query operations has no effect.
DataBoostEnabled bool
// QueryOptions option used to set the DirectedReadOptions for all ExecuteSqlRequests which indicate
// which replicas or regions should be used for executing queries.
DirectedReadOptions *sppb.DirectedReadOptions
// Controls whether to exclude recording modifications in current partitioned update operation
// from the allowed tracking change streams(with DDL option allow_txn_exclusion=true). Setting
// this value for any sql/dml requests other than partitioned udpate will receive an error.
ExcludeTxnFromChangeStreams bool
}
// merge combines two QueryOptions that the input parameter will have higher
// order of precedence.
func (qo QueryOptions) merge(opts QueryOptions) QueryOptions {
merged := QueryOptions{
Mode: qo.Mode,
Options: &sppb.ExecuteSqlRequest_QueryOptions{},
RequestTag: qo.RequestTag,
Priority: qo.Priority,
DataBoostEnabled: qo.DataBoostEnabled,
DirectedReadOptions: qo.DirectedReadOptions,
ExcludeTxnFromChangeStreams: qo.ExcludeTxnFromChangeStreams || opts.ExcludeTxnFromChangeStreams,
}
if opts.Mode != nil {
merged.Mode = opts.Mode
}
if opts.RequestTag != "" {
merged.RequestTag = opts.RequestTag
}
if opts.Priority != sppb.RequestOptions_PRIORITY_UNSPECIFIED {
merged.Priority = opts.Priority
}
if opts.DataBoostEnabled {
merged.DataBoostEnabled = opts.DataBoostEnabled
}
if opts.DirectedReadOptions != nil {
merged.DirectedReadOptions = opts.DirectedReadOptions
}
proto.Merge(merged.Options, qo.Options)
proto.Merge(merged.Options, opts.Options)
return merged
}
func createRequestOptions(prio sppb.RequestOptions_Priority, requestTag, transactionTag string) (ro *sppb.RequestOptions) {
ro = &sppb.RequestOptions{}
if prio != sppb.RequestOptions_PRIORITY_UNSPECIFIED {
ro.Priority = prio
}
if requestTag != "" {
ro.RequestTag = requestTag
}
if transactionTag != "" {
ro.TransactionTag = transactionTag
}
return ro
}
// Query executes a query against the database. It returns a RowIterator for
// retrieving the resulting rows.
//
// Query returns only row data, without a query plan or execution statistics.
// Use QueryWithStats to get rows along with the plan and statistics. Use
// AnalyzeQuery to get just the plan.
func (t *txReadOnly) Query(ctx context.Context, statement Statement) *RowIterator {
mode := sppb.ExecuteSqlRequest_NORMAL
return t.query(ctx, statement, QueryOptions{
Mode: &mode,
Options: t.qo.Options,
Priority: t.qo.Priority,
DirectedReadOptions: t.qo.DirectedReadOptions,
})
}
// QueryWithOptions executes a SQL statment against the database. It returns
// a RowIterator for retrieving the resulting rows. The sql query execution
// will be optimized based on the given query options.
func (t *txReadOnly) QueryWithOptions(ctx context.Context, statement Statement, opts QueryOptions) *RowIterator {
return t.query(ctx, statement, t.qo.merge(opts))
}
// QueryWithStats executes a SQL statement against the database. It returns
// a RowIterator for retrieving the resulting rows. The RowIterator will also
// be populated with a query plan and execution statistics.
func (t *txReadOnly) QueryWithStats(ctx context.Context, statement Statement) *RowIterator {
mode := sppb.ExecuteSqlRequest_PROFILE
return t.query(ctx, statement, QueryOptions{
Mode: &mode,
Options: t.qo.Options,
Priority: t.qo.Priority,
DirectedReadOptions: t.qo.DirectedReadOptions,
})
}
// AnalyzeQuery returns the query plan for statement.
func (t *txReadOnly) AnalyzeQuery(ctx context.Context, statement Statement) (*sppb.QueryPlan, error) {
mode := sppb.ExecuteSqlRequest_PLAN
iter := t.query(ctx, statement, QueryOptions{
Mode: &mode,
Options: t.qo.Options,
Priority: t.qo.Priority,
DirectedReadOptions: t.qo.DirectedReadOptions,
})
defer iter.Stop()
for {
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
}
if iter.QueryPlan == nil {
return nil, spannerErrorf(codes.Internal, "query plan unavailable")
}
return iter.QueryPlan, nil
}
func (t *txReadOnly) query(ctx context.Context, statement Statement, options QueryOptions) (ri *RowIterator) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/spanner.Query")
defer func() { trace.EndSpan(ctx, ri.err) }()
req, sh, err := t.prepareExecuteSQL(ctx, statement, options)
if err != nil {
return &RowIterator{err: err}
}
var setTransactionID func(transactionID)
if _, ok := req.Transaction.GetSelector().(*sppb.TransactionSelector_Begin); ok {
setTransactionID = t.setTransactionID
} else {
setTransactionID = nil
}
client := sh.getClient()
return streamWithReplaceSessionFunc(
contextWithOutgoingMetadata(ctx, sh.getMetadata(), t.disableRouteToLeader),
sh.session.logger,
func(ctx context.Context, resumeToken []byte) (streamingReceiver, error) {
req.ResumeToken = resumeToken
req.Session = t.sh.getID()
req.Transaction = t.getTransactionSelector()
t.sh.updateLastUseTime()
client, err := client.ExecuteStreamingSql(ctx, req)
if err != nil {
if _, ok := req.Transaction.GetSelector().(*sppb.TransactionSelector_Begin); ok {
t.setTransactionID(nil)
return client, errInlineBeginTransactionFailed()
}
return client, err
}
md, err := client.Header()
if getGFELatencyMetricsFlag() && md != nil && t.ct != nil {
if err := createContextAndCaptureGFELatencyMetrics(ctx, t.ct, md, "query"); err != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency. Try disabling and rerunning. Error: %v", err)
}
}
if metricErr := recordGFELatencyMetricsOT(ctx, md, "query", t.otConfig); metricErr != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency through OpenTelemetry. Error: %v", metricErr)
}
return client, err
},
t.replaceSessionFunc,
setTransactionID,
t.setTimestamp,
t.release)
}
func (t *txReadOnly) prepareExecuteSQL(ctx context.Context, stmt Statement, options QueryOptions) (*sppb.ExecuteSqlRequest, *sessionHandle, error) {
sh, ts, err := t.acquire(ctx)
if err != nil {
return nil, nil, err
}
// Cloud Spanner will return "Session not found" on bad sessions.
sid := sh.getID()
if sid == "" {
// Might happen if transaction is closed in the middle of a API call.
return nil, nil, errSessionClosed(sh)
}
params, paramTypes, err := stmt.convertParams()
if err != nil {
return nil, nil, err
}
mode := sppb.ExecuteSqlRequest_NORMAL
if options.Mode != nil {
mode = *options.Mode
}
req := &sppb.ExecuteSqlRequest{
Session: sid,
Transaction: ts,
Sql: stmt.SQL,
QueryMode: mode,
Seqno: atomic.AddInt64(&t.sequenceNumber, 1),
Params: params,
ParamTypes: paramTypes,
QueryOptions: options.Options,
RequestOptions: createRequestOptions(options.Priority, options.RequestTag, t.txOpts.TransactionTag),
DataBoostEnabled: options.DataBoostEnabled,
DirectedReadOptions: options.DirectedReadOptions,
}
return req, sh, nil
}
// txState is the status of a transaction.
type txState int
const (
// transaction is new, waiting to be initialized..
txNew txState = iota
// transaction is being initialized.
txInit
// transaction is active and can perform read/write.
txActive
// transaction is closed, cannot be used anymore.
txClosed
)
// errRtsUnavailable returns error for read transaction's read timestamp being
// unavailable.
func errRtsUnavailable() error {
return spannerErrorf(codes.Internal, "read timestamp is unavailable")
}
// errTxClosed returns error for using a closed transaction.
func errTxClosed() error {
return spannerErrorf(codes.InvalidArgument, "cannot use a closed transaction")
}
// errUnexpectedTxState returns error for transaction enters an unexpected state.
func errUnexpectedTxState(ts txState) error {
return spannerErrorf(codes.FailedPrecondition, "unexpected transaction state: %v", ts)
}
// errExcludeRequestLevelDmlFromChangeStreams returns error for passing
// QueryOptions.ExcludeTxnFromChangeStreams to request-level DML functions. This
// options should only be used for partitioned update.
func errExcludeRequestLevelDmlFromChangeStreams() error {
return spannerErrorf(codes.InvalidArgument, "cannot set exclude transaction from change streams for a request-level DML statement.")
}
// ReadOnlyTransaction provides a snapshot transaction with guaranteed
// consistency across reads, but does not allow writes. Read-only transactions
// can be configured to read at timestamps in the past.
//
// Read-only transactions do not take locks. Instead, they work by choosing a
// Cloud Spanner timestamp, then executing all reads at that timestamp. Since
// they do not acquire locks, they do not block concurrent read-write
// transactions.
//
// Unlike locking read-write transactions, read-only transactions never abort.
// They can fail if the chosen read timestamp is garbage collected; however, the
// default garbage collection policy is generous enough that most applications
// do not need to worry about this in practice. See the documentation of
// TimestampBound for more details.
//
// A ReadOnlyTransaction consumes resources on the server until Close is called.
type ReadOnlyTransaction struct {
// mu protects concurrent access to the internal states of ReadOnlyTransaction.
mu sync.Mutex
// txReadOnly contains methods for performing transactional reads.
txReadOnly
// singleUse indicates that the transaction can be used for only one read.
singleUse bool
// tx is the transaction ID in Cloud Spanner that uniquely identifies the
// ReadOnlyTransaction.
tx transactionID
// txReadyOrClosed is for broadcasting that transaction ID has been returned
// by Cloud Spanner or that transaction is closed.
txReadyOrClosed chan struct{}
// state is the current transaction status of the ReadOnly transaction.
state txState
// rts is the read timestamp returned by transactional reads.
rts time.Time
// tb is the read staleness bound specification for transactional reads.
tb TimestampBound
// isLongRunningTransaction indicates whether the transaction is long-running or not.
isLongRunningTransaction bool
}
// errTxInitTimeout returns error for timeout in waiting for initialization of
// the transaction.
func errTxInitTimeout() error {
return spannerErrorf(codes.Canceled, "timeout/context canceled in waiting for transaction's initialization")
}
// getTimestampBound returns the read staleness bound specified for the
// ReadOnlyTransaction.
func (t *ReadOnlyTransaction) getTimestampBound() TimestampBound {
t.mu.Lock()
defer t.mu.Unlock()
return t.tb
}
// begin starts a snapshot read-only Transaction on Cloud Spanner.
func (t *ReadOnlyTransaction) begin(ctx context.Context) error {
var (
locked bool
tx transactionID
rts time.Time
sh *sessionHandle
err error
res *sppb.Transaction
)
defer func() {
if !locked {
t.mu.Lock()
// Not necessary, just to make it clear that t.mu is being held when
// locked == true.
locked = true
}
if t.state != txClosed {
// Signal other initialization routines.
close(t.txReadyOrClosed)
t.txReadyOrClosed = make(chan struct{})
}
t.mu.Unlock()
if err != nil && sh != nil {
// Got a valid session handle, but failed to initialize transaction=
// on Cloud Spanner.
if isSessionNotFoundError(err) {
sh.destroy()
}
// If sh.destroy was already executed, this becomes a noop.
sh.recycle()
}
}()
// Retry the BeginTransaction call if a 'Session not found' is returned.
for {
sh, err = t.sp.take(ctx)
if err != nil {
return err
}
t.setSessionEligibilityForLongRunning(sh)
sh.updateLastUseTime()
var md metadata.MD
res, err = sh.getClient().BeginTransaction(contextWithOutgoingMetadata(ctx, sh.getMetadata(), t.disableRouteToLeader), &sppb.BeginTransactionRequest{
Session: sh.getID(),
Options: &sppb.TransactionOptions{
Mode: &sppb.TransactionOptions_ReadOnly_{
ReadOnly: buildTransactionOptionsReadOnly(t.getTimestampBound(), true),
},
},
}, gax.WithGRPCOptions(grpc.Header(&md)))
if getGFELatencyMetricsFlag() && md != nil && t.ct != nil {
if err := createContextAndCaptureGFELatencyMetrics(ctx, t.ct, md, "begin_BeginTransaction"); err != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency. Try disabling and rerunning. Error: %v", err)
}
}
if metricErr := recordGFELatencyMetricsOT(ctx, md, "begin_BeginTransaction", t.otConfig); metricErr != nil {
trace.TracePrintf(ctx, nil, "Error in recording GFE Latency through OpenTelemetry. Error: %v", metricErr)
}
if isSessionNotFoundError(err) {
sh.destroy()
continue
} else if err == nil {
tx = res.Id
if res.ReadTimestamp != nil {
rts = time.Unix(res.ReadTimestamp.Seconds, int64(res.ReadTimestamp.Nanos))
}
} else {
err = ToSpannerError(err)
}
break
}
t.mu.Lock()
// defer function will be executed with t.mu being held.
locked = true
// During the execution of t.begin(), t.Close() was invoked.
if t.state == txClosed {
return errSessionClosed(sh)
}
// If begin() fails, this allows other queries to take over the
// initialization.
t.tx = nil
if err == nil {
t.tx = tx
t.rts = rts
t.sh = sh
// State transite to txActive.
t.state = txActive
}
return err
}
// acquire implements txReadEnv.acquire.
func (t *ReadOnlyTransaction) acquire(ctx context.Context) (*sessionHandle, *sppb.TransactionSelector, error) {
if err := checkNestedTxn(ctx); err != nil {
return nil, nil, err
}
if t.singleUse {
return t.acquireSingleUse(ctx)
}
return t.acquireMultiUse(ctx)
}
func (t *ReadOnlyTransaction) acquireSingleUse(ctx context.Context) (*sessionHandle, *sppb.TransactionSelector, error) {
t.mu.Lock()
defer t.mu.Unlock()
switch t.state {
case txClosed:
// A closed single-use transaction can never be reused.
return nil, nil, errTxClosed()
case txNew:
t.state = txClosed
ts := &sppb.TransactionSelector{
Selector: &sppb.TransactionSelector_SingleUse{
SingleUse: &sppb.TransactionOptions{
Mode: &sppb.TransactionOptions_ReadOnly_{
ReadOnly: buildTransactionOptionsReadOnly(t.tb, true),
},
},
},
}
sh, err := t.sp.take(ctx)
if err != nil {
return nil, nil, err
}
// Install session handle into t, which can be used for readonly
// operations later.
t.sh = sh
return sh, ts, nil
}
us := t.state
// SingleUse transaction should only be in either txNew state or txClosed
// state.
return nil, nil, errUnexpectedTxState(us)
}
func (t *ReadOnlyTransaction) acquireMultiUse(ctx context.Context) (*sessionHandle, *sppb.TransactionSelector, error) {
for {
t.mu.Lock()
switch t.state {
case txClosed:
t.mu.Unlock()
return nil, nil, errTxClosed()
case txNew:
// State transit to txInit so that no further TimestampBound change
// is accepted.
t.state = txInit
t.mu.Unlock()
continue
case txInit:
if t.tx != nil {
// Wait for a transaction ID to become ready.
txReadyOrClosed := t.txReadyOrClosed
t.mu.Unlock()
select {
case <-txReadyOrClosed:
// Need to check transaction state again.
continue
case <-ctx.Done():
// The waiting for initialization is timeout, return error
// directly.
return nil, nil, errTxInitTimeout()
}
}
// Take the ownership of initializing the transaction.
t.tx = transactionID{}
t.mu.Unlock()
// Begin a read-only transaction.
//
// TODO: consider adding a transaction option which allow queries to
// initiate transactions by themselves. Note that this option might
// not be always good because the ID of the new transaction won't
// be ready till the query returns some data or completes.
if err := t.begin(ctx); err != nil {
return nil, nil, err
}
// If t.begin() succeeded, t.state should have been changed to
// txActive, so we can just continue here.
continue
case txActive:
sh := t.sh
ts := &sppb.TransactionSelector{
Selector: &sppb.TransactionSelector_Id{
Id: t.tx,
},
}
t.mu.Unlock()
return sh, ts, nil
}
state := t.state
t.mu.Unlock()
return nil, nil, errUnexpectedTxState(state)
}
}
func (t *ReadOnlyTransaction) getTransactionSelector() *sppb.TransactionSelector {
t.mu.Lock()
defer t.mu.Unlock()
if t.singleUse {
return &sppb.TransactionSelector{
Selector: &sppb.TransactionSelector_SingleUse{
SingleUse: &sppb.TransactionOptions{
Mode: &sppb.TransactionOptions_ReadOnly_{
ReadOnly: buildTransactionOptionsReadOnly(t.tb, true),
},
},
},
}
}
return &sppb.TransactionSelector{
Selector: &sppb.TransactionSelector_Id{
Id: t.tx,
},
}
}
func (t *ReadOnlyTransaction) setTimestamp(ts time.Time) {
t.mu.Lock()
defer t.mu.Unlock()
if t.rts.IsZero() {
t.rts = ts
}
}
// release implements txReadEnv.release.
func (t *ReadOnlyTransaction) release(err error) {
t.mu.Lock()
sh := t.sh
t.mu.Unlock()
if sh != nil { // sh could be nil if t.acquire() fails.
if isSessionNotFoundError(err) || isClientClosing(err) {
sh.destroy()
}
if t.singleUse {
// If session handle is already destroyed, this becomes a noop.
sh.recycle()
}
}
}
// Close closes a ReadOnlyTransaction, the transaction cannot perform any reads
// after being closed.
func (t *ReadOnlyTransaction) Close() {
if t.singleUse {
return
}
t.mu.Lock()
if t.state != txClosed {
t.state = txClosed
close(t.txReadyOrClosed)
}
sh := t.sh
t.mu.Unlock()
if sh == nil {
return
}
// If session handle is already destroyed, this becomes a noop. If there are
// still active queries and if the recycled session is reused before they
// complete, Cloud Spanner will cancel them on behalf of the new transaction
// on the session.
if sh != nil {
sh.recycle()
}
}
// Timestamp returns the timestamp chosen to perform reads and queries in this
// transaction. The value can only be read after some read or query has either
// returned some data or completed without returning any data.
func (t *ReadOnlyTransaction) Timestamp() (time.Time, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.rts.IsZero() {
return t.rts, errRtsUnavailable()
}
return t.rts, nil
}
// WithTimestampBound specifies the TimestampBound to use for read or query.
// This can only be used before the first read or query is invoked. Note:
// bounded staleness is not available with general ReadOnlyTransactions; use a
// single-use ReadOnlyTransaction instead.
//
// The returned value is the ReadOnlyTransaction so calls can be chained.
func (t *ReadOnlyTransaction) WithTimestampBound(tb TimestampBound) *ReadOnlyTransaction {
t.mu.Lock()
defer t.mu.Unlock()
if t.state == txNew {
// Only allow to set TimestampBound before the first query.
t.tb = tb
}
return t
}
func (t *ReadOnlyTransaction) setSessionEligibilityForLongRunning(sh *sessionHandle) {
if t != nil && sh != nil {
sh.mu.Lock()
t.mu.Lock()
sh.eligibleForLongRunning = t.isLongRunningTransaction