-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathrelay.go
1804 lines (1493 loc) · 43.6 KB
/
relay.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
package relay
import (
"context"
"fmt"
"math/rand"
"strings"
"time"
"github.com/pg-sharding/lyx/lyx"
"github.com/pg-sharding/spqr/pkg/models/distributions"
"github.com/pg-sharding/spqr/pkg/models/hashfunction"
"github.com/pg-sharding/spqr/pkg/models/spqrerror"
"github.com/pg-sharding/spqr/pkg/prepstatement"
"github.com/jackc/pgx/v5/pgproto3"
"github.com/opentracing/opentracing-go"
"github.com/pg-sharding/spqr/pkg/config"
"github.com/pg-sharding/spqr/pkg/models/kr"
"github.com/pg-sharding/spqr/pkg/shard"
"github.com/pg-sharding/spqr/pkg/spqrlog"
"github.com/pg-sharding/spqr/pkg/txstatus"
"github.com/pg-sharding/spqr/router/client"
"github.com/pg-sharding/spqr/router/parser"
"github.com/pg-sharding/spqr/router/pgcopy"
"github.com/pg-sharding/spqr/router/poolmgr"
"github.com/pg-sharding/spqr/router/qrouter"
"github.com/pg-sharding/spqr/router/route"
"github.com/pg-sharding/spqr/router/routingstate"
"github.com/pg-sharding/spqr/router/server"
"github.com/pg-sharding/spqr/router/statistics"
"golang.org/x/exp/slices"
)
type RelayStateMgr interface {
poolmgr.ConnectionKeeper
route.RouteMgr
QueryRouter() qrouter.QueryRouter
Reset() error
StartTrace()
Flush()
ConnMgr() poolmgr.PoolMgr
ShouldRetry(err error) bool
Parse(query string, doCaching bool) (parser.ParseState, string, error)
AddQuery(q pgproto3.FrontendMessage)
AddSilentQuery(q pgproto3.FrontendMessage)
TxActive() bool
PgprotoDebug() bool
RelayStep(msg pgproto3.FrontendMessage, waitForResp bool, replyCl bool) (txstatus.TXStatus, []pgproto3.BackendMessage, error)
CompleteRelay(replyCl bool) error
Close() error
Client() client.RouterClient
ProcessMessage(msg pgproto3.FrontendMessage, waitForResp, replyCl bool, cmngr poolmgr.PoolMgr) error
PrepareStatement(hash uint64, d *prepstatement.PreparedStatementDefinition) (*prepstatement.PreparedStatementDescriptor, pgproto3.BackendMessage, error)
PrepareRelayStep(cmngr poolmgr.PoolMgr) error
PrepareRelayStepOnAnyRoute(cmngr poolmgr.PoolMgr) (func() error, error)
PrepareRelayStepOnHintRoute(cmngr poolmgr.PoolMgr, route *routingstate.DataShardRoute) error
HoldRouting()
UnholdRouting()
ProcessMessageBuf(waitForResp, replyCl, completeRelay bool, cmngr poolmgr.PoolMgr) (bool, error)
RelayRunCommand(msg pgproto3.FrontendMessage, waitForResp bool, replyCl bool) error
ProcQuery(query pgproto3.FrontendMessage, waitForResp bool, replyCl bool) (txstatus.TXStatus, []pgproto3.BackendMessage, bool, error)
ProcCopyPrepare(ctx context.Context, stmt *lyx.Copy) (*pgcopy.CopyState, error)
ProcCopy(ctx context.Context, data *pgproto3.CopyData, copyState *pgcopy.CopyState) ([]byte, error)
ProcCommand(query pgproto3.FrontendMessage, waitForResp bool, replyCl bool) error
ProcCopyComplete(query *pgproto3.FrontendMessage) error
RouterMode() config.RouterMode
AddExtendedProtocMessage(q pgproto3.FrontendMessage)
ProcessExtendedBuffer(cmngr poolmgr.PoolMgr) error
}
type BufferedMessageType int
const (
// Message from client
BufferedMessageRegular = BufferedMessageType(0)
// Message produced by spqr
BufferedMessageInternal = BufferedMessageType(1)
)
type BufferedMessage struct {
msg pgproto3.FrontendMessage
tp BufferedMessageType
}
func RegularBufferedMessage(q pgproto3.FrontendMessage) BufferedMessage {
return BufferedMessage{
msg: q,
tp: BufferedMessageRegular,
}
}
func InternalBufferedMessage(q pgproto3.FrontendMessage) BufferedMessage {
return BufferedMessage{
msg: q,
tp: BufferedMessageInternal,
}
}
type PortalDesc struct {
rd *pgproto3.RowDescription
nodata *pgproto3.NoData
}
type ParseCacheEntry struct {
ps parser.ParseState
comm string
stmt lyx.Node
}
type RelayStateImpl struct {
txStatus txstatus.TXStatus
CopyActive bool
activeShards []kr.ShardKey
TargetKeyRange kr.KeyRange
traceMsgs bool
WorldShardFallback bool
routerMode config.RouterMode
pgprotoDebug bool
routingState routingstate.RoutingState
Qr qrouter.QueryRouter
qp parser.QParser
plainQ string
Cl client.RouterClient
manager poolmgr.PoolMgr
maintain_params bool
msgBuf []BufferedMessage
holdRouting bool
bindRoute *routingstate.DataShardRoute
lastBindName string
execute func() error
saveBind *pgproto3.Bind
savedPortalDesc map[string]PortalDesc
parseCache map[string]ParseCacheEntry
// buffer of messages to process on Sync request
xBuf []pgproto3.FrontendMessage
}
// HoldRouting implements RelayStateMgr.
func (rst *RelayStateImpl) HoldRouting() {
rst.holdRouting = true
}
// UnholdRouting implements RelayStateMgr.
func (rst *RelayStateImpl) UnholdRouting() {
rst.holdRouting = false
}
func NewRelayState(qr qrouter.QueryRouter, client client.RouterClient, manager poolmgr.PoolMgr, rcfg *config.Router) RelayStateMgr {
return &RelayStateImpl{
activeShards: nil,
txStatus: txstatus.TXIDLE,
msgBuf: nil,
traceMsgs: false,
Qr: qr,
Cl: client,
manager: manager,
WorldShardFallback: rcfg.WorldShardFallback,
routerMode: config.RouterMode(rcfg.RouterMode),
maintain_params: rcfg.MaintainParams,
pgprotoDebug: rcfg.PgprotoDebug,
execute: nil,
savedPortalDesc: map[string]PortalDesc{},
parseCache: map[string]ParseCacheEntry{},
}
}
func (rst *RelayStateImpl) SyncCount() int64 {
if rst.Cl.Server() == nil {
return 0
}
return rst.Cl.Server().Sync()
}
func (rst *RelayStateImpl) DataPending() bool {
if rst.Cl.Server() == nil {
return false
}
return rst.Cl.Server().DataPending()
}
func (rst *RelayStateImpl) QueryRouter() qrouter.QueryRouter {
return rst.Qr
}
func (rst *RelayStateImpl) SetTxStatus(status txstatus.TXStatus) {
rst.txStatus = status
}
func (rst *RelayStateImpl) PgprotoDebug() bool {
return rst.pgprotoDebug
}
func (rst *RelayStateImpl) Client() client.RouterClient {
return rst.Cl
}
func (rst *RelayStateImpl) TxStatus() txstatus.TXStatus {
return rst.txStatus
}
// TODO : unit tests
func (rst *RelayStateImpl) PrepareStatement(hash uint64, d *prepstatement.PreparedStatementDefinition) (*prepstatement.PreparedStatementDescriptor, pgproto3.BackendMessage, error) {
serv := rst.Client().Server()
if ok, rd := serv.HasPrepareStatement(hash); ok {
return rd, &pgproto3.ParseComplete{}, nil
}
// Do not wait for result
// simply fire backend msg
if err := serv.Send(&pgproto3.Parse{
Name: d.Name,
Query: d.Query,
ParameterOIDs: d.ParameterOIDs,
}); err != nil {
return nil, nil, err
}
err := serv.Send(&pgproto3.Describe{
ObjectType: 'S',
Name: d.Name,
})
if err != nil {
return nil, nil, err
}
spqrlog.Zero.Debug().Uint("client", rst.Client().ID()).Msg("syncing connection")
_, unreplied, err := rst.RelayStep(&pgproto3.Sync{}, true, false)
if err != nil {
return nil, nil, err
}
rd := &prepstatement.PreparedStatementDescriptor{
NoData: false,
RowDesc: nil,
ParamDesc: nil,
}
var retMsg pgproto3.BackendMessage
deployed := false
for _, msg := range unreplied {
spqrlog.Zero.Debug().Uint("client", rst.Client().ID()).Interface("type", msg).Msg("unreplied msg in prepare")
switch q := msg.(type) {
case *pgproto3.ParseComplete:
// skip
retMsg = msg
deployed = true
case *pgproto3.ErrorResponse:
retMsg = msg
case *pgproto3.NoData:
rd.NoData = true
case *pgproto3.ParameterDescription:
// copy
cp := *q
rd.ParamDesc = &cp
case *pgproto3.RowDescription:
// copy
rd.RowDesc = &pgproto3.RowDescription{}
rd.RowDesc.Fields = make([]pgproto3.FieldDescription, len(q.Fields))
for i := range len(q.Fields) {
s := make([]byte, len(q.Fields[i].Name))
copy(s, q.Fields[i].Name)
rd.RowDesc.Fields[i] = q.Fields[i]
rd.RowDesc.Fields[i].Name = s
}
default:
}
}
if deployed {
// dont need to complete relay because tx state didt changed
rst.Cl.Server().StorePrepareStatement(hash, d, rd)
}
return rd, retMsg, nil
}
func (rst *RelayStateImpl) RouterMode() config.RouterMode {
return rst.routerMode
}
func (rst *RelayStateImpl) Close() error {
defer rst.Cl.Close()
defer rst.ActiveShardsReset()
return rst.manager.UnRouteCB(rst.Cl, rst.activeShards)
}
func (rst *RelayStateImpl) TxActive() bool {
return rst.txStatus == txstatus.TXACT
}
func (rst *RelayStateImpl) ActiveShardsReset() {
rst.activeShards = nil
}
func (rst *RelayStateImpl) ActiveShards() []kr.ShardKey {
return rst.activeShards
}
// TODO : unit tests
func (rst *RelayStateImpl) Reset() error {
rst.activeShards = nil
rst.txStatus = txstatus.TXIDLE
_ = rst.Cl.Reset()
return rst.Cl.Unroute()
}
// TODO : unit tests
func (rst *RelayStateImpl) StartTrace() {
rst.traceMsgs = true
}
// TODO : unit tests
func (rst *RelayStateImpl) Flush() {
rst.msgBuf = nil
rst.traceMsgs = false
}
var ErrSkipQuery = fmt.Errorf("wait for a next query")
// TODO : unit tests
func (rst *RelayStateImpl) procRoutes(routes []*routingstate.DataShardRoute) error {
// if there is no routes configurted, there is nowhere to route to
if len(routes) == 0 {
return qrouter.MatchShardError
}
spqrlog.Zero.Debug().
Uint("relay state", spqrlog.GetPointer(rst)).
Msg("unroute previous connections")
if err := rst.Unroute(rst.activeShards); err != nil {
return err
}
rst.activeShards = nil
for _, shr := range routes {
rst.activeShards = append(rst.activeShards, shr.Shkey)
}
if rst.PgprotoDebug() {
if err := rst.Cl.ReplyDebugNoticef("matched datashard routes %+v", routes); err != nil {
return err
}
}
if err := rst.Connect(routes); err != nil {
spqrlog.Zero.Error().
Err(err).
Uint("client", rst.Client().ID()).
Msg("client encounter while initialing server connection")
_ = rst.Reset()
return err
}
return nil
}
// TODO : unit tests
func (rst *RelayStateImpl) Reroute() error {
_ = rst.Cl.ReplyDebugNotice("rerouting the client connection")
span := opentracing.StartSpan("reroute")
defer span.Finish()
span.SetTag("user", rst.Cl.Usr())
span.SetTag("db", rst.Cl.DB())
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Interface("params", rst.Client().BindParams()).
Interface("drb", rst.Client().DefaultRouteBehaviour()).
Msg("rerouting the client connection, resolving shard")
var routingState routingstate.RoutingState
var err error
if v := rst.Client().ExecuteOn(); v != "" {
routingState = routingstate.ShardMatchState{
Route: &routingstate.DataShardRoute{
Shkey: kr.ShardKey{
Name: v,
},
},
}
} else {
routingState, err = rst.Qr.Route(context.TODO(), rst.qp.Stmt(), rst.Cl)
}
if err != nil {
return fmt.Errorf("error processing query '%v': %v", rst.plainQ, err)
}
rst.routingState = routingState
switch v := routingState.(type) {
case routingstate.MultiMatchState:
if rst.TxActive() {
return fmt.Errorf("cannot route in an active transaction")
}
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Err(err).
Msgf("parsed MultiMatchState")
return rst.procRoutes(rst.Qr.DataShardsRoutes())
case routingstate.DDLState:
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Err(err).
Msgf("parsed DDLState")
return rst.procRoutes(rst.Qr.DataShardsRoutes())
case routingstate.ShardMatchState:
// TBD: do it better
return rst.procRoutes([]*routingstate.DataShardRoute{v.Route})
case routingstate.SkipRoutingState:
return ErrSkipQuery
case routingstate.RandomMatchState:
return rst.RerouteToRandomRoute()
case routingstate.WorldRouteState:
if !rst.WorldShardFallback {
return err
}
// fallback to execute query on world datashard (s)
_, _ = rst.RerouteWorld()
if err := rst.ConnectWorld(); err != nil {
return err
}
return nil
default:
return fmt.Errorf("unexpected route state %T", v)
}
}
// TODO : unit tests
func (rst *RelayStateImpl) RerouteToRandomRoute() error {
_ = rst.Cl.ReplyDebugNotice("rerouting the client connection")
span := opentracing.StartSpan("reroute")
defer span.Finish()
span.SetTag("user", rst.Cl.Usr())
span.SetTag("db", rst.Cl.DB())
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Msg("rerouting the client connection to random shard, resolving shard")
routes := rst.Qr.DataShardsRoutes()
if len(routes) == 0 {
return fmt.Errorf("no routes configured")
}
routingState := routingstate.ShardMatchState{
Route: routes[rand.Int()%len(routes)],
}
rst.routingState = routingState
return rst.procRoutes([]*routingstate.DataShardRoute{routingState.Route})
}
// TODO : unit tests
func (rst *RelayStateImpl) RerouteToTargetRoute(route *routingstate.DataShardRoute) error {
_ = rst.Cl.ReplyDebugNotice("rerouting the client connection")
span := opentracing.StartSpan("reroute")
defer span.Finish()
span.SetTag("user", rst.Cl.Usr())
span.SetTag("db", rst.Cl.DB())
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Interface("statement", rst.qp.Stmt()).
Msg("rerouting the client connection to target shard, resolving shard")
routingState := routingstate.ShardMatchState{
Route: route,
}
rst.routingState = routingState
return rst.procRoutes([]*routingstate.DataShardRoute{route})
}
// TODO : unit tests
func (rst *RelayStateImpl) CurrentRoutes() []*routingstate.DataShardRoute {
switch q := rst.routingState.(type) {
case routingstate.ShardMatchState:
return []*routingstate.DataShardRoute{q.Route}
default:
return nil
}
}
func (rst *RelayStateImpl) RerouteWorld() ([]*routingstate.DataShardRoute, error) {
span := opentracing.StartSpan("reroute to world")
defer span.Finish()
span.SetTag("user", rst.Cl.Usr())
span.SetTag("db", rst.Cl.DB())
shardRoutes := rst.Qr.WorldShardsRoutes()
if len(shardRoutes) == 0 {
_ = rst.manager.UnRouteWithError(rst.Cl, nil, qrouter.MatchShardError)
return nil, qrouter.MatchShardError
}
if err := rst.Unroute(rst.activeShards); err != nil {
return nil, err
}
for _, shr := range shardRoutes {
rst.activeShards = append(rst.activeShards, shr.Shkey)
}
return shardRoutes, nil
}
// TODO : unit tests
func (rst *RelayStateImpl) Connect(shardRoutes []*routingstate.DataShardRoute) error {
var serv server.Server
var err error
if len(shardRoutes) > 1 {
serv, err = server.NewMultiShardServer(rst.Cl.Route().ServPool())
if err != nil {
return err
}
} else {
_ = rst.Cl.ReplyDebugNotice("open a connection to the single data shard")
serv = server.NewShardServer(rst.Cl.Route().ServPool())
}
if err := rst.Cl.AssignServerConn(serv); err != nil {
return err
}
spqrlog.Zero.Debug().
Str("user", rst.Cl.Usr()).
Str("db", rst.Cl.DB()).
Uint("client", rst.Client().ID()).
Msg("connect client to datashard routes")
if err := rst.manager.RouteCB(rst.Cl, rst.activeShards); err != nil {
return err
}
/* take care of session param if we told to */
if rst.Client().MaintainParams() {
query := rst.Cl.ConstructClientParams()
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Str("query", query.String).
Msg("setting params for client")
_, _, _, err = rst.ProcQuery(query, true, false)
}
return err
}
func (rst *RelayStateImpl) ConnectWorld() error {
_ = rst.Cl.ReplyDebugNotice("open a connection to the single data shard")
serv := server.NewShardServer(rst.Cl.Route().ServPool())
if err := rst.Cl.AssignServerConn(serv); err != nil {
return err
}
spqrlog.Zero.Debug().
Str("user", rst.Cl.Usr()).
Str("db", rst.Cl.DB()).
Msg("route client to world datashard")
return rst.manager.RouteCB(rst.Cl, rst.activeShards)
}
// TODO : unit tests
func (rst *RelayStateImpl) ProcCommand(query pgproto3.FrontendMessage, waitForResp bool, replyCl bool) error {
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Interface("query", query).
Msg("client process command")
_ = rst.
Client().
ReplyDebugNotice(
fmt.Sprintf("executing your query %v", query)) // TODO performance issue
if err := rst.Client().Server().Send(query); err != nil {
return err
}
if !waitForResp {
return nil
}
for {
msg, err := rst.Client().Server().Receive()
if err != nil {
return err
}
switch v := msg.(type) {
case *pgproto3.CommandComplete:
return nil
case *pgproto3.ErrorResponse:
return fmt.Errorf("%s", v.Message)
default:
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Type("message-type", v).
Msg("got message from server")
if replyCl {
err = rst.Client().Send(msg)
if err != nil {
return err
}
}
}
}
}
// TODO : unit tests
func (rst *RelayStateImpl) RelayCommand(v pgproto3.FrontendMessage, waitForResp bool, replyCl bool) error {
if !rst.TxActive() {
if err := rst.manager.TXBeginCB(rst); err != nil {
return err
}
rst.txStatus = txstatus.TXACT
}
return rst.ProcCommand(v, waitForResp, replyCl)
}
func (rst *RelayStateImpl) RelayRunCommand(msg pgproto3.FrontendMessage, waitForResp bool, replyCl bool) error {
return rst.ProcCommand(msg, waitForResp, replyCl)
}
// TODO: unit tests
func (rst *RelayStateImpl) ProcCopyPrepare(ctx context.Context, stmt *lyx.Copy) (*pgcopy.CopyState, error) {
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Msg("client pre-process copy")
var relname string
switch q := stmt.TableRef.(type) {
case *lyx.RangeVar:
relname = q.RelationName
}
// TODO: check by whole RFQN
ds, err := rst.Qr.Mgr().GetRelationDistribution(ctx, relname)
if err != nil {
return nil, err
}
if ds.Id == distributions.REPLICATED {
return &pgcopy.CopyState{
Scatter: true,
}, nil
}
// Read delimiter from COPY options
delimiter := byte('\t')
allow_multishard := rst.Client().AllowMultishard()
for _, opt := range stmt.Options {
o := opt.(*lyx.Option)
if strings.ToLower(o.Name) == "delimiter" {
delimiter = o.Arg.(*lyx.AExprSConst).Value[0]
}
if strings.ToLower(o.Name) == "format" {
if o.Arg.(*lyx.AExprSConst).Value == "csv" {
delimiter = ','
}
}
}
if rst.Client().ExecuteOn() != "" {
return &pgcopy.CopyState{
Delimiter: delimiter,
ExpRoute: &routingstate.DataShardRoute{},
AllowMultishard: allow_multishard,
}, nil
}
TargetType := ds.ColTypes[0]
if len(ds.ColTypes) != 1 {
return nil, fmt.Errorf("multi-column copy processing is not yet supported")
}
var hashFunc hashfunction.HashFunctionType
if v, err := hashfunction.HashFunctionByName(ds.Relations[relname].DistributionKey[0].HashFunction); err != nil {
return nil, err
} else {
hashFunc = v
}
krs, err := rst.Qr.Mgr().ListKeyRanges(ctx, ds.Id)
if err != nil {
return nil, err
}
colOffset := -1
for indx, c := range stmt.Columns {
if c == ds.Relations[relname].DistributionKey[0].Column {
colOffset = indx
break
}
}
if colOffset == -1 {
return nil, fmt.Errorf("failed to resolve target copy column offset")
}
return &pgcopy.CopyState{
Delimiter: delimiter,
ExpRoute: &routingstate.DataShardRoute{},
AllowMultishard: allow_multishard,
Krs: krs,
TargetType: TargetType,
HashFunc: hashFunc,
}, nil
}
// TODO : unit tests
func (rst *RelayStateImpl) ProcCopy(ctx context.Context, data *pgproto3.CopyData, cps *pgcopy.CopyState) ([]byte, error) {
if v := rst.Client().ExecuteOn(); v != "" {
for _, sh := range rst.Client().Server().Datashards() {
if sh.Name() == v {
err := sh.Send(data)
return nil, err
}
}
return nil, fmt.Errorf("metadata corrutped")
}
/* We dont really need to parse and route tuples for DISTRIBUTED relations */
if cps.Scatter {
return nil, rst.Client().Server().Send(data)
}
var leftOvermsgData []byte = nil
rowsMp := map[string][]byte{}
values := make([]interface{}, 0)
// Parse data
// and decide where to route
prevDelimiter := 0
prevLine := 0
currentAttr := 0
for i, b := range data.Data {
if i+2 < len(data.Data) && string(data.Data[i:i+2]) == "\\." {
prevLine = len(data.Data)
break
}
if b == '\n' || b == cps.Delimiter {
if currentAttr == cps.ColumnOffset {
tmp, err := hashfunction.ApplyHashFunctionOnStringRepr(data.Data[prevDelimiter:i], cps.TargetType, cps.HashFunc)
if err != nil {
return nil, err
}
values = append(values, tmp)
}
currentAttr++
prevDelimiter = i + 1
}
if b != '\n' {
continue
}
// check where this tuple should go
currroute, err := rst.Qr.DeparseKeyWithRangesInternal(ctx, values, cps.Krs)
if err != nil {
return nil, err
}
if currroute == nil {
return nil, fmt.Errorf("multishard copy is not supported: %+v at line number %d %d %v", values[0], prevLine, i, b)
}
if !cps.AllowMultishard {
if cps.ExpRoute.Shkey.Name == "" {
*cps.ExpRoute = *currroute
}
}
if !cps.AllowMultishard && currroute.Shkey.Name != cps.ExpRoute.Shkey.Name {
return nil, fmt.Errorf("multishard copy is not supported")
}
values = nil
rowsMp[currroute.Shkey.Name] = append(rowsMp[currroute.Shkey.Name], data.Data[prevLine:i+1]...)
currentAttr = 0
prevLine = i + 1
}
if prevLine != len(data.Data) {
if spqrlog.IsDebugLevel() {
_ = rst.Client().ReplyNotice(fmt.Sprintf("leftover data saved to next iter %d - %d", prevLine, len(data.Data)))
}
leftOvermsgData = data.Data[prevLine:len(data.Data)]
}
for _, sh := range rst.Client().Server().Datashards() {
if !cps.AllowMultishard {
if cps.ExpRoute != nil && sh.Name() == cps.ExpRoute.Shkey.Name {
err := sh.Send(&pgproto3.CopyData{Data: rowsMp[sh.Name()]})
return leftOvermsgData, err
}
} else {
bts, ok := rowsMp[sh.Name()]
if ok {
err := sh.Send(&pgproto3.CopyData{Data: bts})
if err != nil {
return nil, err
}
}
}
}
// shouldn't exit from here
return leftOvermsgData, nil
}
// TODO : unit tests
func (rst *RelayStateImpl) ProcCopyComplete(query *pgproto3.FrontendMessage) error {
spqrlog.Zero.Debug().
Uint("client", rst.Client().ID()).
Type("query-type", query).
Msg("client process copy end")
if err := rst.Client().Server().Send(*query); err != nil {
return err
}
for {
msg, err := rst.Client().Server().Receive()
if err != nil {
return err
}
switch msg.(type) {
case *pgproto3.CommandComplete, *pgproto3.ErrorResponse:
return rst.Client().Send(msg)
default:
if err := rst.Client().Send(msg); err != nil {
return err
}
}
}
}
// TODO : unit tests
func (rst *RelayStateImpl) ProcQuery(query pgproto3.FrontendMessage, waitForResp bool, replyCl bool) (txstatus.TXStatus, []pgproto3.BackendMessage, bool, error) {
server := rst.Client().Server()
if server == nil {
return txstatus.TXERR, nil, false, fmt.Errorf("client %p is out of transaction sync with router", rst.Client())
}
spqrlog.Zero.Debug().
Uints("shards", shard.ShardIDs(server.Datashards())).
Type("query-type", query).
Msg("relay process query")
if err := server.Send(query); err != nil {
return txstatus.TXERR, nil, false, err
}
waitForRespLocal := waitForResp
switch query.(type) {
case *pgproto3.Query:
// ok
case *pgproto3.Sync:
// ok
default:
waitForRespLocal = false
}
if !waitForRespLocal {
return txstatus.TXCONT, nil, true, nil
}
ok := true
unreplied := make([]pgproto3.BackendMessage, 0)
for {
msg, err := server.Receive()
if err != nil {
return txstatus.TXERR, nil, false, err
}
switch v := msg.(type) {
case *pgproto3.CopyInResponse:
// handle replyCl somehow
err = rst.Client().Send(msg)
if err != nil {
return txstatus.TXERR, nil, false, err
}
q := rst.qp.Stmt().(*lyx.Copy)
if err := func() error {
var leftOvermsgData []byte
ctx := context.TODO()
cps, err := rst.ProcCopyPrepare(ctx, q)
if err != nil {
return err
}
for {
cpMsg, err := rst.Client().Receive()
if err != nil {
return err
}
switch newMsg := cpMsg.(type) {
case *pgproto3.CopyData:
leftOvermsgData = append(leftOvermsgData, newMsg.Data...)
if leftOvermsgData, err = rst.ProcCopy(ctx, &pgproto3.CopyData{Data: leftOvermsgData}, cps); err != nil {
return err
}
case *pgproto3.CopyDone, *pgproto3.CopyFail:
if err := rst.ProcCopyComplete(&cpMsg); err != nil {
return err
}
return nil
default:
/* panic? */
}
}
}(); err != nil {
return txstatus.TXERR, nil, false, err
}
case *pgproto3.ReadyForQuery:
return txstatus.TXStatus(v.TxStatus), unreplied, ok, nil
case *pgproto3.ErrorResponse:
if replyCl {
err = rst.Client().Send(msg)
if err != nil {
return txstatus.TXERR, nil, false, err
}
} else {
unreplied = append(unreplied, msg)
}
ok = false
// never resend this msgs
case *pgproto3.ParseComplete:
unreplied = append(unreplied, msg)
case *pgproto3.BindComplete:
unreplied = append(unreplied, msg)
default:
spqrlog.Zero.Debug().
Str("server", server.Name()).
Type("msg-type", v).
Msg("received message from server")
if replyCl {